简体   繁体   中英

Algorithm with O(m (log n + log m)) time complexity for finding kth smallest element in n*m matrix with each row sorted?

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 order O(m (log m+ log n)) to find k -th smallest element on this matrix (just one element as k -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:

  1. Put the median of all rows into an array and we find the median of this array in O(m) and called it pivot

  2. We find the rank of this element in O(m log n) . ie: in each row how many elements are lower than the pivot found in step (1).

  3. By comparing k and "rank of the pivot" we can know that in each row works on the right half or left half. (reduce to m*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?

m - rows n - columns

  • Is it compulsory that you want a solution with O(m (log m+ log n)) Complexity?

  • I Can Think of a Solution with Complexity O(k * log-m) with extra space of O(m)

    • You can use a modified PriorityQueue (heap) DataStructure for this complexity
     class PQObject { int value; // PQ sorting happens on this int.. int m; // And m and n are positions. int n; }
  • You can just put all the values from the first column to the Priority Queue and Start popping until the kth smallest element

    • Every time you pop re-insert the next value of the row using m and n in the popped object.
  • Ultimately the problem comes down to find the kth smallest element in M sorted arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM