Kth Smallest Element in a Sorted Matrix – Solution & Complexity
Solution Walkthrough
Step 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.
Step 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.
- Copy every value into one array, sort it, and read the
Step 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.
- If at least
Step 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.
Step 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 = 99 15 12 6 still too few, so low = 1313 15 14 8 enough values, so high = 1413 14 13 8 enough values, so high = 13When
lowmeetshigh, that value is the smallest number whose rank is at leastk.Step 6: Final solution and complexity
Binary-search the value range and count rank in
O(n)per probe, forO(n log(value range))time and constant extra space.