Can anyone assess below approaches and help with thoughts.
What would be expected from interviewer?
Enjoy your interview!
Given a matrix A: 1
[[0,0,1,1,1],
[0,1,1,1,1], n rows m cols
[0,0,1,1,1],
[0,0,0,0,0]]
Each cell is either a 0 or a 1
In each row, as you go from left to right, once you first see a 1 in the row, the rest of the cells will also be a 1
Q: Find the leftmost column that contains a 1
public int findLeftMostWithOne(int A[][]){
int res =-1;
int tmp=Integer.MAX_VALUE;
for(int i=0; i<A.length ;i++){ //n
for(int j=0 ;j<A[0].length ; j++){ //n
if(A[i][j] == 1){
tmp =Math.min(tmp,j); //2 1
j=A[0].length-1;
}
}
}
return tmp> -1 ? tmp : res;
}Q: Given a non-empty array of integers and also an int k, return up to k most freq elements in the order of freq DESC
[1, 1, 1, 2, 2, 3] k = 2: [1,2]
public int[] mostFre(int arr[] , int k){
int res[] = new int[k];
if(arr==null) return res;
Map<Integer, Integer> mp = new HashMap();
for(int i =0;i< arr.length ;i++){
mp.put(arr[i] , mp.getOrDefault(arr[i] , 0)+1); // ele / count
}
PriorityQueue<Map.Entry<Integer, Integer>> q = new PriorityQueue<>((a,b) -> b.getValue() - a.getValue());
for(Map.Entry<Integer, Integer> e : mp.entrySet()){
q.offer(e);
}
int index=0;
while(k-- >0){
Map.Entry<Integer, Integer> e = q.poll();
res[index] = (int)e.getKey();
index++;
}
return res;
}Time complexity - N(LOGN)