Search a 2D Matrix – Solution & Complexity
Solution Walkthrough
1. Exploit both sorting rules
- Every row is ascending, and each row starts after the previous row ends.
- Concatenating the rows would produce one fully sorted sequence of
m * nvalues. - That means a single binary search can cover the whole matrix.
2. Brute-force scan
- Visit every cell and compare it with the target.
- Correct but
O(m * n), ignoring the sorted structure.
3. Flatten with index math
- Number the cells
0 .. m*n - 1in row-major order. - Flat index
imaps tomatrix[i // n][i % n]. - Now run an ordinary binary search over
0 .. m*n - 1.
4. Single binary search
- Keep
lo/hibounds over the flat index space. - Convert
midback to row/column with the division and modulo.
5. Dry run
Trace matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 (cols = 4).
| lo | hi | mid | cell [mid/4][mid%4] | value vs 3 |
|---|---|---|---|---|
| 0 | 11 | 5 | [1][1] = 11 | 11 > 3, hi = 4 |
| 0 | 4 | 2 | [0][2] = 5 | 5 > 3, hi = 1 |
| 0 | 1 | 0 | [0][0] = 1 | 1 < 3, lo = 1 |
| 1 | 1 | 1 | [0][1] = 3 | match, return true |
6. Final solution and complexity
The flattened binary search runs in O(log(m * n)) time and O(1) extra space.