Search a 2D Matrix – Solution & Complexity
Solution Walkthrough
Step 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.
Step 2: Brute-force scan
- Visit every cell and compare it with the target.
- Correct but
O(m * n), ignoring the sorted structure.
Step 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.
- Number the cells
Step 4: Single binary search
- Keep
lo/hibounds over the flat index space. - Convert
midback to row/column with the division and modulo.
- Keep
Step 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] = 1111 > 3,hi = 40 4 2 [0][2] = 55 > 3,hi = 10 1 0 [0][0] = 11 < 3,lo = 11 1 1 [0][1] = 3match, return trueStep 6: Final solution and complexity
The flattened binary search runs in
O(log(m * n))time andO(1)extra space.