K-th Smallest Entry in a Row and Column Sorted Grid
Heaps, Sorting & SearchAuto-graded · 22 test casesLast updated
Find the k-th smallest value in a two-dimensional grid where every row and column is sorted in ascending order.
You are given a 2D integer grid matrix of dimension n x m, where every individual row and column is ordered in non-decreasing order. You are also given an integer k.
Find and return the $k$-th smallest element present in the grid when considering all $n \times m$ entries sorted together in non-decreasing order (1-indexed). Duplicates should be counted individually.
Constraints
- $n == \text{len}(matrix)$
- $m == \text{len}(matrix[i])$
- $1 \le n, m \le 300$
- $-10^9 \le matrix[i][j] \le 10^9$
- $1 \le k \le n \times m$
- Each row of
matrixis sorted in non-decreasing order. - Each column of
matrixis sorted in non-decreasing order.
Examples
Example 1
Input: kth_smallest_matrix([[1, 5, 9], [10, 11, 13], [12, 13, 15]], 8)
Output: 13
Example 2
Input: kth_smallest_matrix([[1, 2], [3, 4]], 2)
Output: 2
Example 3
Input: kth_smallest_matrix([[1, 1, 1], [1, 1, 1]], 5)
Output: 1
Hints
Hint 1
The smallest possible value is at the top-left corner matrix[0][0] and the largest is at the bottom-right corner matrix[-1][-1].
Hint 2
Can you search over the range of potential values [min_val, max_val] using binary search?
Hint 3
For a candidate midpoint x, count how many elements in the matrix are less than or equal to x. Because rows are sorted, binary search (or a staircase traversal) can count this efficiently.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Instead of sorting all elements or using a min-heap to extract the minimum $k$ times, we can use binary search on the value range.
- Range Bounds: Because each row and column is sorted, the overall minimum value in the grid is at
matrix[0][0]and the overall maximum value is atmatrix[-1][-1]. - Counting Elements: For any chosen middle value
mid, we can determine how many elements in the grid are $\le \text{mid}$. Since each row is independently sorted, we can use binary search (bisect_right) on each row to count elements $\le \text{mid}$ in $O(n \log m)$ time. - Binary Search Logic:
- If the total count of elements $\le \text{mid}$ is strictly less than $k$, then
midis too small, so we move the lower bound tomid + 1. - Otherwise, there are at least $k$ elements $\le \text{mid}$, so
midcould be our answer or the answer could be smaller. Thus, we set the upper bound tomid.
- If the total count of elements $\le \text{mid}$ is strictly less than $k$, then
When lo == hi, the binary search terminates on the $k$-th smallest value.
Why the Returned Value Must Exist in the Grid
The binary search searches over numerical range, not array indices. However, the search condition checks the function $f(x) = \text{count of elements } \le x$. This step function only increases at values actually present in matrix. The smallest integer $x$ satisfying $f(x) \ge k$ is guaranteed to be an actual value from the matrix.
Complexity
- Time Complexity: $O(n \cdot \log m \cdot \log(\text{max_val} - \text{min_val}))$. For a 32-bit range, $\log(\text{max_val} - \text{min_val}) \le 32$, making this efficiently bounded by $O(n \log m)$.
- Space Complexity: $O(1)$ auxiliary space, as no extra structures are created.
from bisect import bisect_right
from typing import List
def kth_smallest_matrix(matrix: List[List[int]], k: int) -> int:
n = len(matrix)
m = len(matrix[0])
lo = matrix[0][0]
hi = matrix[-1][-1]
while lo < hi:
mid = lo + (hi - lo) // 2
count = 0
for row in matrix:
count += bisect_right(row, mid)
if count < k:
lo = mid + 1
else:
hi = mid
return lo