This is an interview question.
Find the Kth smallest element in a matrix with sorted rows and columns.
Is it correct that the Kth small
O(k log(k))
solution.
Build a minheap.
Add (0,0)
to the heap. While, we haven't found the kth
smallest element, remove the top element (x,y)
from heap and add next two elements [(x+1,y)
and (x,y+1)]
if they haven't been visited before.
We are doing O(k)
operations on a heap of size O(k)
and hence the complexity.
As people mentioned previously the easiest way is to build a min heap
. Here's a Java implementation using PriorityQueue:
private int kthSmallestUsingHeap(int[][] matrix, int k) {
int n = matrix.length;
// This is not necessary since this is the default Int comparator behavior
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
};
// building a minHeap
PriorityQueue<Integer> pq = new PriorityQueue<>(n*n, comparator);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
pq.add(matrix[i][j]);
}
}
int ans = -1;
// remove the min element k times
for (int i = 0; i < k; i++) {
ans = pq.poll();
}
return ans;
}
Kth smallest element in the matrix :
The problem can be narrowed down as below.
if k is 20, then take k*k matrix (where answer will definitely lie.)
Now you can merge the rows in pair repeatedly to build a sorted array and then find the kth smallest number.