Kth Smallest Element in a Sorted Matrix solution explained
To find the k-th smallest value in an n x n matrix whose rows and columns are both sorted ascending, either pop the smallest item from a min-heap of row fronts k times, in O(k log n), or binary search on the value itself. For a guess x, a staircase walk from the bottom-left corner counts the entries at most x in O(n), and the smallest x whose count reaches k is the answer, for O(n log(max - min)) time and O(1) extra memory.
By Evin JohnPublished 8 min read
The problem, restated
A square grid of numbers is sorted two ways: each row reads left to right in non-decreasing order, and each column reads top to bottom in non-decreasing order. Given a position k between 1 and n², return the value that would sit at position k if you wrote all n² entries in one sorted list. Repeated values each take their own position.
| Col 1 | Col 2 | Col 3 | |
|---|---|---|---|
| Row 1 | 2 | 6 | 9 |
| Row 2 | 4 | 7 | 11 |
| Row 3 | 5 | 10 | 14 |
| Grid | k | Answer | Why |
|---|---|---|---|
| The grid above | 5 | 7 | Sorted: 2, 4, 5, 6, 7, 9, 10, 11, 14 |
| The grid above | 1 | 2 | Always the top-left corner |
| The grid above | 9 | 14 | Always the bottom-right corner |
| [[1, 3], [3, 3]] | 3 | 3 | Duplicates count separately: 1, 3, 3, 3 |
| [[-5]] | 1 | -5 | One cell |
Notice that the grid is not sorted as a whole. Row 1 ends with 9 while row 2 starts with 4, so you cannot treat it as one long sorted array and index into it.
What interviewers listen for
Most candidates reach the heap answer, because it is the same idea as merging k sorted lists. The stronger signal is the second idea: searching over the range of values instead of over positions, using a counting function that takes advantage of both sort orders. Interviewers also ask why the binary search result is guaranteed to be an actual entry of the grid, which is a good test of whether you understand the search rather than having memorized it.
Follow-ups
- A rectangular grid. Both methods still work; the staircase walk takes O(rows + cols).
- Many k values for the same grid. Sorting once and indexing becomes attractive.
- Real numbers instead of integers. Binary search on value needs a stopping tolerance, or a search over the sorted distinct values; the heap method is unchanged.
- Is there a linear algorithm? Selection algorithms for sorted matrices that run in O(n) exist in the research literature, but interviewers rarely expect them; naming the heap and value-search trade-offs is enough.
Brute force
Copy all n² values into a list, sort it and return the item at index k - 1. That is O(n² log n) time and O(n²) memory. A max-heap of size k over all entries brings it to O(n² log k), but still reads every entry and uses neither sort order.
A min-heap of row fronts
Each row is a sorted list, so this is merging n sorted lists and stopping after k items. Put the first entry of each row in a min-heap along with its row and column. Pop the smallest; then push the next entry from that same row. After k - 1 pops, the smallest item left in the heap is the k-th smallest overall. Only the first min(n, k) rows matter, since a row starting below position k cannot contribute earlier.
import heapq
def kth_smallest_heap(matrix, k):
n = len(matrix)
heap = [(matrix[r][0], r, 0) for r in range(min(n, k))]
heapq.heapify(heap)
for _ in range(k - 1):
value, r, c = heapq.heappop(heap)
if c + 1 < n:
heapq.heappush(heap, (matrix[r][c + 1], r, c + 1))
return heap[0][0]The optimal approach: binary search on value
The answer lies between the top-left and bottom-right corners. Pick a middle value and count how many entries are at most that value. If the count is at least k, the answer is that value or smaller; otherwise it is larger. Halve the range each time, as with any search for the first value where a yes-or-no test turns true.
Counting is where the two sort orders pay off. Start at the bottom-left cell. If it is at most x, then so is every cell above it in that column, so add the whole column height and step right. If it is larger than x, step up. Each step leaves one row or one column behind for good, so the walk takes at most 2n steps.
def count_at_most(matrix, x):
n = len(matrix)
row, col, count = n - 1, 0, 0
while row >= 0 and col < n:
if matrix[row][col] <= x:
count += row + 1 # this cell and every cell above it
col += 1
else:
row -= 1
return count
def kth_smallest(matrix, k):
lo, hi = matrix[0][0], matrix[-1][-1]
while lo < hi:
mid = (lo + hi) // 2
if count_at_most(matrix, mid) >= k:
hi = mid
else:
lo = mid + 1
return lofunction kthSmallest(matrix, k) {
const n = matrix.length;
const countAtMost = (x) => {
let row = n - 1;
let col = 0;
let count = 0;
while (row >= 0 && col < n) {
if (matrix[row][col] <= x) {
count += row + 1;
col++;
} else {
row--;
}
}
return count;
};
let lo = matrix[0][0];
let hi = matrix[n - 1][n - 1];
while (lo < hi) {
const mid = Math.floor((lo + hi) / 2);
if (countAtMost(mid) >= k) hi = mid;
else lo = mid + 1;
}
return lo;
}Why the result is always in the grid
The loop ends at the smallest integer v with count(v) at least k. Then count(v - 1) is below k, so going from v - 1 to v added at least one entry, and an entry counted at v but not at v - 1 must equal v. So v is a real entry, and it is the k-th smallest. This argument needs integer values; it is a good thing to say without being asked.
Trace k = 5 on the grid above. The range starts at 2 to 14 and mid is 8: the entries at most 8 are 2, 4, 5, 6, 7, five of them, so hi becomes 8. Next mid is 5, count 3, so lo becomes 6. Then mid 7, count 5, hi becomes 7. Then mid 6, count 4, lo becomes 7. lo equals hi at 7, the answer.
Complexity
| Approach | Time | Extra memory |
|---|---|---|
| Flatten and sort | O(n² log n) | O(n²) |
| Max-heap of size k over all entries | O(n² log k) | O(k) |
| Min-heap of row fronts | O(n + k log n) | O(n) |
| Binary search on value with staircase count | O(n log(max - min)) | O(1) |
Which is better depends on the inputs. For small k the heap wins. For k near n² with a modest value range, the value search wins clearly. Saying that instead of declaring one universal winner is the kind of judgment interviewers look for.
Edge cases
- A 1 x 1 grid.
- k = 1 and k = n², which should return the two corners.
- Every entry equal, where the count jumps from 0 to n² at once.
- Negative values, where the midpoint must round down, not toward zero.
Common mistakes
- Treating the grid as one sorted array and indexing row k / n.
- In the binary search, setting hi = mid - 1 when the count is at least k, which can skip the answer.
- Starting the staircase at the top-left, where both directions increase and the walk has no clear move.
- Pushing the cell below as well as the cell to the right in the heap version, which adds duplicates unless you track visited cells.
- Rounding the midpoint toward zero with negative numbers, which can loop forever.
How to explain it out loud
Fictional example
- Candidate
- Each row is sorted, so a heap of row fronts merges them and I stop after k pops. That is k log n.
- Candidate
- I can also search over values. For a guess x, I count entries at most x by starting bottom-left: if the cell fits, the whole column above it fits, so I add that and move right; otherwise I move up. That count is linear in n.
- Candidate
- Then I binary search for the smallest x with count at least k. That x has to be an entry, because the count changed between x minus 1 and x. It runs in n times log of the value range with constant memory.
Related problems
Search Insert Position is the plain form of the first-true binary search used here. Ugly Number II generates a sorted sequence from candidate streams, the same idea as the heap of row fronts. Merge k Sorted Lists is the heap merge on its own.
Practicing with Natively
Explaining the staircase count clearly takes practice, because it is easy to say and easy to get backward. When you rehearse, Natively on Mac or Windows can read the grid problem from a screenshot and suggest the value-search approach as a comparison for your own, and its transcript of your mock shows whether you argued why the answer is an entry. See the AI interview assistant.
Questions people ask
How do you find the kth smallest element in a sorted matrix?
Either merge the rows with a min-heap and stop after k pops, or binary search on the value: for a guess x, count entries at most x with a staircase walk from the bottom-left corner, and find the smallest x whose count is at least k.
What is the time complexity of kth smallest in a sorted matrix?
The heap of row fronts takes O(n + k log n) time. Binary search on value takes O(n log(max - min)) time with O(1) extra memory, because each count is a linear staircase walk.
Why is the binary search answer always an element of the matrix?
The search returns the smallest integer v with at least k entries at most v. Fewer than k entries are at most v - 1, so some entry is counted at v but not at v - 1, which means that entry equals v.
How does the staircase count work?
Start at the bottom-left cell. If it is at most x, every cell above it in that column is too, so add the column height and move right; otherwise move up. It finishes in at most 2n steps.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
