awelgorithms

Treat a matrix as a sorted sequence

Updated

If every row is sorted and the next row starts after the previous row ends, the matrix is one sorted sequence of length R*C. Binary search that sequence with indices 0..R*C-1, then map back to (row, col).

What to focus on

mid is an index in the flattened order, not a (r,c) pair yet. Compare a[mid/C][mid%C] to the target and shrink the 1-D range.

Worked examples

hit 11

a = [[1, 4, 9], [10, 11, 12]], target 11, C=3
  1. sequence length 6, L=0 R=5 mid=2 → a[0][2]=9 < 11, L=3
  2. mid=4 → a[1][1]=11

Result: index 4 → (1, 1)

hit 1

a = [[1, 4, 9], [10, 11, 12]], target 1, C=3
  1. L=0 R=5 mid=2 → 9 > 1, R=1
  2. mid=0 → a[0][0]=1

Result: index 0 → (0, 0)

miss 8

a = [[1, 4, 9], [10, 11, 12]], target 8, C=3
  1. mid=2 → 9 > 8, R=1
  2. mid=0 → 1 < 8, L=1
  3. mid=1 → 4 < 8, L=2 > R

Result: not found

Try it

Write searchMatrix(a, t). a is a row-major matrix that is one sorted sequence. t is the target. L, mid, and R are flattened indices in 0..R*C-1. C is the column count. Return (row, col) or not found. [[1, 4, 9], [10, 11, 12]] t=11 → index 4 → (1, 1) t=1 → index 0 → (0, 0) t=8 → not found

The matrix is non-empty; each row is sorted and the next row starts ≥ the previous row's last. C is the column count. L, mid, and R are flattened indices.