Kth Smallest Element in a Sorted Matrix – Solution & Complexity
Solution Walkthrough
1. Separate matrix order from global order
- The matrix is not fully flattened in sorted order, but rows and columns still give strong structure.
- That structure is enough to count how many values are below a target without examining every cell from scratch.
2. Brute-force by flattening and sorting
- Copy every value into one array, sort it, and read the
(k - 1)th index. - This is simple and correct, but it spends
O(n^2 log n)time andO(n^2)extra space.
3. Binary-search the answer value
- If at least
kentries are<= mid, the true answer is at mostmid. - Otherwise, the answer must be larger than
mid.
4. Count values <= mid in linear matrix time
- Start at the bottom-left corner.
- When
matrix[row][col] <= target, everything above it in that column also qualifies, so addrow + 1and move right. Otherwise move up.
5. Dry run / binary-search trace
Trace matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8.
| low | high | mid | count of values <= mid | decision |
|---|---|---|---|---|
| 1 | 15 | 8 | 2 | need larger values, so low = 9 |
| 9 | 15 | 12 | 6 | still too few, so low = 13 |
| 13 | 15 | 14 | 8 | enough values, so high = 14 |
| 13 | 14 | 13 | 8 | enough values, so high = 13 |
When low meets high, that value is the smallest number whose rank is at least k.
6. Final solution and complexity
Binary-search the value range and count rank in O(n) per probe, for O(n log(value range)) time and constant extra space.