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

Test the edges, then pick: the heap for small k, the binary search for large k

Test the edges. k = 1 returns M[0][0], and k = n² returns M[-1][-1]. Repeats are where an off-by-one hides, so check both methods against sorting. On 500 random matrices up to 6 by 6, with values from 0 to 29 and full of repeats, both agreed with sorting for every k.

Measure. On a 1,000 by 1,000 matrix with values below 10910^9, which is about 30 rounds of the binary search:

kHeapBinary searchSort everything
100.09 ms2.4 ms85 ms
1,0000.38 ms2.0 ms82 ms
500,000202.34 ms3.6 ms88 ms

Answer the real question. The heap costs O(n + k log n) and wins when k is small. The binary search costs O(n) per round for about 30 rounds, whatever k is. At k = 500,000, the heap is slower than sorting all million values. Say that tradeoff before they ask for it.

In the editor, write first_disagreement(kth, matrix), a tester for any k-th smallest function kth(matrix, k). Three functions are there to test it on: by_sort sorts every value and is right, skips_repeats drops repeated values, and last_one_wrong is wrong only at the last k.