30/40
Part 7 of 8 · The worked exampleLearn and do

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 lo has fewer than k entries at most it, so the answer is at least lo. It starts at M[0][0], the smallest value, where nothing is below.
  • hi has at least k entries at most it, so the answer is at most hi. It starts at M[-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:

lohimidEntries at most midNext
2251310at least 6, so hi = 13
21374fewer than 6, so lo = 8
813107hi = 10
81096hi = 9
8985lo = 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.