Binary Search Searching a matrix
255. Kth Smallest Element in a Sorted Matrix
You are given a square grid of integers matrix with n rows and n columns. Every row is sorted from
left to right, and every column is sorted from top to bottom, both in non-decreasing order.
Return the k-th smallest value in the grid. Picture all n2 values written out in one sorted
list: the answer is the value at position k of that list, counting from 1. Equal values each take their
own place in the list, so the answer is the k-th smallest value, not the k-th smallest distinct value.
Example 1
Input: matrix = [[2, 5, 9], [4, 8, 12], [7, 10, 15]], k = 5
8Explanation: In sorted order the values are 2, 4, 5, 7, 8, 9, 10, 12, 15. The fifth of them is 8.
Example 2
Input: matrix = [[-6, -6, -1],
[-6, 0, 3],
[-2, 3, 3]]
k = 4
-2Explanation: The three copies of -6 take the first three places, so the fourth smallest value is -2.
Example 3
Input: matrix = [[-1000000000, 7], [3, 1000000000]], k = 4
1000000000Explanation: The grid has four cells, so the fourth smallest value is the largest one.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
n == matrix.length == matrix[i].length1 ≤ n ≤ 400-109 ≤ matrix[i][j] ≤ 109- Every row and every column of
matrixis sorted in non-decreasing order. 1 ≤ k ≤ n2
Clarifying questions
What you would ask an interviewer before writing any code.