DSA Tracker

Visualize

Search a 2D Matrix

Treat it as one sorted array

time O(log(rows * cols))space O(1)

Each row's smallest value exceeds the previous row's largest value, so reading the matrix row by row, left to right, produces one fully sorted sequence. That means there's no need for a 2D search at all — plain binary search over the flattened array finds the target in O(log(rows*cols)).

Details

Animated on: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 (shown flattened row-major into a 12-cell sorted array).

Problem:Search a 2D MatrixMedium

Treat it as one sorted array

step 1 / 9

1
[0]
3
[1]
5
[2]
7
[3]
10
[4]
11
[5]
16
[6]
20
[7]
23
[8]
30
[9]
34
[10]
60
[11]

Each row's values exceed the previous row's, so the flattened matrix is fully sorted — binary search works directly. target=3.

  • low=0· arr[0] = 1
  • high=11· arr[11] = 60
Pseudocode
1FUNCTION searchMatrix(matrix, target):
2 flat = read the matrix row by row into one list (already sorted, since each row's values exceed the previous row's)
3 low = 0, high = the length of flat - 1
4 WHILE low <= high:
5 mid = (low + high) / 2, rounded down
6 IF flat[mid] equals target: RETURN true
7 ELSE IF flat[mid] > target: high = mid - 1
8 ELSE: low = mid + 1
9 RETURN false

← / → step · space play · Home restart

Every step in words

Show all 9 steps
  1. Each row's values exceed the previous row's, so the flattened matrix is fully sorted — binary search works directly. target=3.
  2. mid = (0+11)/2 = 5 → value 11. 11 > 3, so search the left half.
  3. Narrow the search to low=0, high=4.
  4. mid = (0+4)/2 = 2 → value 5. 5 > 3, search the left half again.
  5. Narrow the search to low=0, high=1.
  6. mid = (0+1)/2 = 0 → value 1. 1 < 3, so search the right half.
  7. Narrow the search to low=1, high=1.
  8. mid = (1+1)/2 = 1 → value 3. 3 === 3 — found!
  9. Target 3 found at flattened index 1 (row0, col1 in the original matrix). Answer: true.

Now solve it yourself

Watching is the first half. The second is writing it without the animation.