A worked example: the k-th smallest in a sorted matrix
The problem: an n by n matrix of integers in which every row and every column is sorted ascending. Given k from 1 to n², return the k-th smallest value, counting repeats. It's worth working because it has two good answers, and the real question is which one to use when.
Clarify, then give the plain answer
Here n is 4 and k is 6:
M = [[2, 6, 9, 14],
[3, 8, 12, 17],
[7, 10, 15, 20],
[11, 13, 18, 25]]
print(sorted(v for row in M for v in row)[:6])
[2, 3, 6, 7, 8, 9]
The sixth smallest is 9.
Clarify. Repeats count separately, so in [[1, 1], [1, 2]] the third smallest is 1. k counts from 1. Values are integers, which matters for the second method.
Give the plain answer. Flatten and sort: O(n² log n) time and O(n²) memory. Say it and its cost, then do better.
The rows are sorted streams, so merge them and stop at the k-th
That's the merge pattern. A heap holds each row's front. Popping k times hands out the values in order, and the k-th pop is the answer. You don't need the pops, only the k-th value, so look at heap[0] after k - 1 of them:
def kth_by_heap(matrix, k):
# each row's smallest
heap = [(row[0], r, 0) for r, row in enumerate(matrix)]
heapq.heapify(heap)
for _ in range(k - 1):
value, r, c = heap[0]
if c + 1 < len(matrix[r]):
heapq.heapreplace(heap, (matrix[r][c + 1], r, c + 1))
else:
heapq.heappop(heap)
return heap[0][0]
print(kth_by_heap(M, 6))
9
Each pop takes one row's front and pushes the next value from that row:
| Step | Pops | From row | Pushes | Heap values after |
|---|---|---|---|---|
| 1 | 2 | 0 | 6 | 3, 6, 7, 11 |
| 2 | 3 | 1 | 8 | 6, 7, 8, 11 |
| 3 | 6 | 0 | 9 | 7, 8, 9, 11 |
| 4 | 7 | 2 | 10 | 8, 9, 10, 11 |
| 5 | 8 | 1 | 12 | 9, 10, 11, 12 |
After those five pops, the heap holds one front per row, and the popped values sit to their left:
M Blue values are popped: 2, 3, 6, 7, 8. Orange values are in the heap, one front per row, with 9 on top.
heap[0] holds 9. The cost is O(n + k log n) time and O(n) memory. The column sorting goes unused.
In the editor, M is the matrix above. Write smallest_k(matrix, k): merge its rows with a heap of (value, row, column) fronts, and return the k smallest values in order.