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 , which is about 30 rounds of the binary search:
| k | Heap | Binary search | Sort everything |
|---|---|---|---|
| 10 | 0.09 ms | 2.4 ms | 85 ms |
| 1,000 | 0.38 ms | 2.0 ms | 82 ms |
| 500,000 | 202.34 ms | 3.6 ms | 88 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.