Kth smallest element in a row-cpumn wise sorted matrix
Pattern: Binary search on 2D matrices
Binary search on the value. Rows and columns are both sorted, so the cells at most x can be counted with a staircase walk from the bottom-left corner in O(R + C). The answer is the smallest x with at least k cells at most it.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
You are given a matrix where every row and every column is sorted in increasing order. Return the k-th smallest value
among all its cells, counting repeats. For example, [[1, 5, 9], [10, 11, 13], [12, 13, 15]] with k = 8 gives 13.
This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet (LeetCode's "Kth Smallest
Element in a Sorted Matrix" is very close). The function name kthSmallest is this guide's own.
Think first
- For a guess
x, how can you count the cells at mostxusing both orders at once? - What does that count tell you about the k-th smallest?
- Why is the answer always a value that is really in the matrix?
Hints
Brute force, and why it fails
Put every value in one list and sort: O(R C log(R C)). A min-heap that pops k times is O(k log R). Binary search on the
value with a staircase count is O((R + C) log V).
The key insight
Sorted rows and columns make counting easy, and counting is all a rank question needs. The search space is the values, not the positions.
Dry run
| lo | 1 |
|---|---|
| hi | 15 |
matrix rows are 1 5 9, 10 11 13 and 12 13 15, and k = 8. Values run from 1 to 15.
The plan
lo = matrix[0][0], hi = matrix[R - 1][C - 1]
while lo < hi:
mid = lo + (hi - lo) / 2
if countAtMost(mid) >= k: hi = mid
else: lo = mid + 1
return lo
countAtMost(x): count = 0, r = R - 1, c = 0
while r >= 0 and c < C:
if matrix[r][c] <= x: count = count + r + 1; c = c + 1
else: r = r - 1
return count
Complexity
- Time
O((R + C) log V)- Space
O(1)
V is the range of values. Each guess walks a staircase of at most R + C steps.
Edge cases
k = 1: the top-left value.k = R × C: the bottom-right value.- Repeats: they all count, so
[[1, 2], [1, 3]]withk = 2gives 1. - One cell: that value.
I've built my logic, show the code
Java
class Solution {
public int kthSmallest(int[][] matrix, int k) {
int n = matrix.length;
int lo = matrix[0][0], hi = matrix[n - 1][matrix[0].length - 1];
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (countAtMost(matrix, mid) >= k) hi = mid; // at least k values <= mid: answer is mid or less
else lo = mid + 1;
}
return lo;
}
private int countAtMost(int[][] m, int x) { // staircase from the bottom-left corner
int count = 0, r = m.length - 1, c = 0;
while (r >= 0 && c < m[0].length) {
if (m[r][c] <= x) { count += r + 1; c++; } // the whole column above r is <= x too
else r--;
}
return count;
}
}C++
class Solution {
public:
int kthSmallest(vector<vector<int>>& matrix, int k) {
int lo = matrix[0][0], hi = matrix.back().back();
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (countAtMost(matrix, mid) >= k) hi = mid; // at least k values <= mid: answer is mid or less
else lo = mid + 1;
}
return lo;
}
int countAtMost(vector<vector<int>>& m, int x) { // staircase from the bottom-left corner
int count = 0, r = static_cast<int>(m.size()) - 1, c = 0;
while (r >= 0 && c < static_cast<int>(m[0].size())) {
if (m[r][c] <= x) { count += r + 1; c++; } // the whole column above r is <= x too
else r--;
}
return count;
}
};Python
class Solution:
def kthSmallest(self, matrix: list[list[int]], k: int) -> int:
lo, hi = matrix[0][0], matrix[-1][-1]
while lo < hi:
mid = (lo + hi) // 2
if self.count_at_most(matrix, mid) >= k:
hi = mid # at least k values <= mid: answer is mid or less
else:
lo = mid + 1
return lo
def count_at_most(self, m: list[list[int]], x: int) -> int: # staircase from the bottom-left corner
count, r, c = 0, len(m) - 1, 0
while r >= 0 and c < len(m[0]):
if m[r][c] <= x:
count += r + 1 # the whole column above r is <= x too
c += 1
else:
r -= 1
return countCommon mistakes
- Counting with
<instead of≤, which skips repeated values. - Starting the staircase at the top-left.
- Returning
midwhen the count equalsk;midmay not be in the matrix.