I ran into an interview question recently.
We have
m*n
matrix such that each row is in non-decreasing order (sorted with distinct elements). design an algorithm on orderO(m (log m+ log n))
to findk
-th smallest element on this matrix (just one element ask
-th smallest element).
I think this is not possible so search on Google and find this link and another solution and this answer to a similar question.
I think as follows:
Put the median of all rows into an array and we find the median of this array in
O(m)
and called it pivotWe find the rank of this element in
O(m log n)
. i.e: in each row how many elements are lower than the pivot found in step (1).By comparing
k
and "rank of the pivot" we can know that in each row works on the right half or left half. (reduce tom*n/2
matrix.)
But the time complexity of this algorithm is O(m * log^2 n)
. What is the algorithm that can works on O(m (log n + log m))
? Is there any idea?