Binary-search the value, not a position
This is the binary search from the sorting and binary search lesson, with one change: lo and hi are values, not indexes into a list. The question at each middle value is "are at least k entries at most mid?"
The two bounds keep two promises:
- Every value below
lohas fewer than k entries at most it, so the answer is at leastlo. It starts atM[0][0], the smallest value, where nothing is below. hihas at least k entries at most it, so the answer is at mosthi. It starts atM[-1][-1], the largest value, which has all n² entries at most it.
Each round counts at mid = (lo + hi) // 2. At least k means mid might be the answer, so hi = mid keeps it. Fewer than k means the answer is above mid, so lo = mid + 1 drops it. Either way the range shrinks, and the loop stops when lo == hi. Both promises still hold, so that one value is the smallest x with at least k entries at most x: the k-th smallest.
print([kth_by_search(M, k) for k in (1, 6, 16)])
[2, 9, 25]
Here are the rounds for k = 6:
| lo | hi | mid | Entries at most mid | Next |
|---|---|---|---|---|
| 2 | 25 | 13 | 10 | at least 6, so hi = 13 |
| 2 | 13 | 7 | 4 | fewer than 6, so lo = 8 |
| 8 | 13 | 10 | 7 | hi = 10 |
| 8 | 10 | 9 | 6 | hi = 9 |
| 8 | 9 | 8 | 5 | lo = 9 |
lo and hi meet at 9. That value is always in the matrix. If it weren't, x - 1 would have the same count, and x wouldn't be the smallest. The cost is O(n log(hi - lo)) time and O(1) memory, and it doesn't depend on k.
Here's where the integer clarification counts: mid = (lo + hi) // 2 needs integers. With floats, search over the matrix's distinct values instead, or use the heap.
In the editor, count_at_most is the staircase walk you wrote. Write kth_by_search(matrix, k): the loop with the two promises, returning the value where lo and hi meet.