matrix
binary-search
You are given an n x n matrix where every row is sorted in ascending order and every column is also sorted in ascending order.
Return the kth smallest element in the matrix. Count duplicates as separate positions in sorted order.
Input / output
- Input:
matrix: int[][],k: int - Output: the
kth smallest integer
Examples
matrix = [[1,5,9],[10,11,13],[12,13,15]],k = 8returns13.matrix = [[-5]],k = 1returns-5.matrix = [[1,2],[1,3]],k = 2returns1because duplicates still occupy separate ranks.
Constraints
1 <= n <= 300-10^9 <= matrix[i][j] <= 10^9- Each row and each column is sorted ascending.
1 <= k <= n * n
Edge cases
- The answer may appear multiple times in the matrix.
- Negative values are allowed.
kcan be1orn * n.
Target complexity
- Aim for
O(n log(value range))time andO(1)extra space.
Hints
- Binary-search the answer value, not the index.
- For a candidate value
mid, count how many matrix entries are<= midinO(n)time by walking from the bottom-left corner.
Follow-up How would the trade-offs change if you used a min-heap that merges rows instead of binary-searching the value range?
Examples
Example 1
Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
Output: 13
Example 2
Input: matrix = [[-5]], k = 1
Output: -5
Example 3
Input: matrix = [[1,2],[1,3]], k = 2
Output: 1
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.