MediumPro challengePythonJavaScriptTypeScript
Binary Search — Kth Smallest in a Sorted Matrix
AlgorithmsBinary SearchBinary Search on AnswerMatrix
solve(matrix, k) — matrix is n × n and both its rows and its columns are sorted
ascending (unlike in Search a 2D Matrix, a row can start below the end of the row
above it). Return the k-th smallest
value, counting duplicates (k is 1-based).
A min-heap works in O(k log n). A tighter solution binary searches the value range[matrix[0][0], matrix[n-1][n-1]]: for a candidate x, count how many cells are<= x with a staircase walk from the bottom-left corner in O(n). The answer is the
smallest x whose count reaches k.
Examples
solve([[1,5,9],[10,11,13],[12,13,15]], 8) → 13
solve([[-5]], 1) → -5
solve([[1,2],[1,3]], 3) → 2 // 1, 1, 2, 3Sample tests
Test #1Classic example
Input: [[[1,5,9],[10,11,13],[12,13,15]],8]
Output: 13
Test #2Single negative cell
Input: [[[-5]],1]
Output: -5
Test #3Duplicates counted
Input: [[[1,2],[1,3]],3]
Output: 2