Kth Smallest Element in a Sorted Matrix
Kth Smallest Element in a Sorted Matrix is LeetCode 378 (Medium). You get an n x n matrix whose every row and every column is sorted in non-decreasing order, and an integer k. Return the kth smallest value in the whole matrix.
- It is the kth value in sorted order, not the kth distinct value: repeated numbers count once per copy.
- The solution must use less than O(n²) memory, so copying all the values into one list and sorting it is not allowed.
- Values can be negative, down to -10⁹.
- n == matrix.length == matrix[i].length
- 1 <= n <= 300
- -10⁹ <= matrix[i][j] <= 10⁹
- All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order.
- 1 <= k <= n²
Intuition
Rows and columns are sorted, but the matrix as a whole is not, so you cannot jump to position k. Binary search on the value instead. For any guess x, count how many cells are at most x. That count only grows as x grows, so the answer is the smallest x whose count reaches k.
The count is cheap because of the sorting:
- Start at the bottom-left cell. If it is at most
x, so is everything above it, and the whole column counts at once; move right. - If it is bigger than
x, so is everything to its right, and that row is done; move up.
Each move retires a row or a column, so one count takes at most 2n moves.
When a structure is too awkward to index but easy to count against, binary search on the answer's value: guess, count how many items are at most the guess, and shrink the range. The same move solves Median in a Row-Wise Sorted Matrix and Find K-th Smallest Pair Distance.
Approach
Before reading on, take the guess 12 for the matrix [[1, 5, 9], [10, 11, 13], [12, 13, 15]] and count the cells at most 12 without checking all nine. Which corner lets every comparison settle a whole row or column? Then decide how that count tells you whether the 8th smallest is above or below 12.
Two ways to solve it
Guess a value, count the cells at most it with a staircase walk, and halve the range.
- Constant memory: meets the follow-up.
- Fast for any k: the cost does not grow with k.
The stronger interview answer.
Treat each row as a sorted list and merge them with a heap, popping k times.
- Familiar: the same merge as Merge k Sorted Lists.
- Slower for big k: k can be 90,000.
The obvious first idea, and accepted.
Both are accepted. Binary search on the value uses constant memory and does not slow down as k grows, so the steps, code and demo follow it; the heap version comes after the demo.
Set the value range
The smallest value is matrix[0][0] and the largest is matrix[n-1][n-1], so set lo and hi to them. The answer is always inside [lo, hi], and every step keeps it there.
Count the cells at most mid
Start at row n - 1, column 0. If the cell is at most mid, add r + 1 for the column above it and move right; otherwise move up. Stop when you leave the grid. Each move discards a whole row or column, which keeps a count at O(n).
Shrink the range
With mid = lo + (hi - lo) // 2: if the count is at least k, the kth smallest is mid or less, so set hi = mid and keep mid as a candidate. Otherwise it is bigger than mid, so set lo = mid + 1.
Return when the range is one value
When lo == hi, that value is the smallest number with at least k cells at most it, which is exactly the kth smallest. Return lo.
Code in Python, C++ and Java
Min-heap over the rows
Each row is a sorted list, so the matrix is n lists to merge. Start the heap with the first cell of every row. Each pop gives the next smallest value overall; then push the cell to its right in the same row. The kth pop is the answer, and the heap never holds more than n cells.
Common pitfalls
Returning mid as soon as the count equals k
if count_at_most(mid) == k:
return midif count_at_most(mid) >= k:
hi = mid
else:
lo = mid + 1mid is any number in the range, not necessarily a cell. For [[1, 5], [10, 11]] with k = 2, the first guess is 6 and two cells are at most 6, so this returns 6; the answer is 5.
Testing count > k instead of count >= k
if count_at_most(mid) > k:
hi = midif count_at_most(mid) >= k:
hi = midA count of exactly k means mid could be the answer, so it must stay in the range. For [[1, 2], [1, 3]] with k = 2, three cells are at most 2 and two are at most 1, so the strict test moves lo past 1 and returns 2; the answer is 1.
Computing mid as (lo + hi) / 2 in C++ or Java
int mid = (lo + hi) / 2;
int mid = lo + (hi - lo) / 2;
Integer division rounds toward zero, so with negative values mid can land on hi. For [[-3, -2], [-2, -2]] with k = 1, lo = -3, hi = -2 gives mid = -2 forever and the loop never ends. Python's // rounds down, so this one is a C++ and Java trap.
Edge cases
lo and hi start equal, the loop never runs, and the single value is returned.
The range closes on matrix[0][0] or matrix[n-1][n-1], the two corners. No special case is needed, since both are inside the starting range.
Complexity
Kth Smallest Element in a Sorted Matrix FAQ
Why is the returned value always in the matrix?
The loop ends on the smallest x with at least k cells at most x. Suppose no cell equals x. Then the cells at most x are the same cells as those at most x - 1, so x - 1 also has at least k, and x was not the smallest. That contradiction means some cell holds x.
Why start the count at the bottom-left corner?
From there, moving up always gives a smaller value and moving right always gives a bigger one, so each comparison settles a whole column or a whole row. The top-right corner works the same way. From the top-left, both moves give bigger values, so a comparison tells you nothing about which way to go.
Can it be done in O(n) time?
Yes, with a selection algorithm by Frederickson and Johnson that works on sorted matrices, but it is long and rarely asked. In interviews, binary search on the value or the min-heap is expected.