Find kth smallest in sorted matrix
Company: Meta
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Onsite
Quick Answer: This question evaluates algorithmic problem-solving and data-structure knowledge, focusing on selection in a row-and-column-sorted matrix and the comparative use of min-heaps versus value-space binary search along with time/space complexity and edge-case analysis.
Constraints
- n == matrix.length == matrix[i].length
- 1 <= n <= 300
- Each row and each column of matrix is sorted in non-decreasing order
- 1 <= k <= n^2
- -10^9 <= matrix[i][j] <= 10^9
Examples
Input: ([[1,5,9],[10,11,13],[12,13,15]], 8)
Expected Output: 13
Explanation: Sorted order: 1,5,9,10,11,12,13,13,15. The 8th smallest is 13 (the second 13).
Input: ([[1,2],[1,3]], 2)
Expected Output: 1
Explanation: Sorted order: 1,1,2,3. Duplicates count, so the 2nd smallest is the second 1.
Input: ([[-5]], 1)
Expected Output: -5
Explanation: Single-cell matrix; the only element is the 1st smallest.
Input: ([[1,5,9],[10,11,13],[12,13,15]], 1)
Expected Output: 1
Explanation: k=1 boundary: the smallest element is the top-left corner.
Input: ([[1,5,9],[10,11,13],[12,13,15]], 9)
Expected Output: 15
Explanation: k=n^2 boundary: the largest element is the bottom-right corner.
Input: ([[1,3,5],[6,7,12],[11,14,14]], 6)
Expected Output: 11
Explanation: Sorted order: 1,3,5,6,7,11,12,14,14. The 6th smallest is 11.
Input: ([[1,2],[3,3]], 4)
Expected Output: 3
Explanation: Sorted order: 1,2,3,3. The 4th (last) smallest is 3.
Hints
- The whole matrix isn't globally sorted, but each row IS sorted. Think of merging n sorted lists (the rows) and stopping after k elements.
- Use a min-heap seeded with the head of each row: (value, rowIndex, colIndex). Pop the smallest, then push the next element from that same row.
- After k pops, the last popped value is the answer. Each value pushed/popped costs O(log n).
- Alternative: binary search on the value range [matrix[0][0], matrix[n-1][n-1]]. For a candidate x, count how many entries are <= x by walking from the bottom-left corner in O(n); shrink the range until you isolate the k-th smallest.