awelgorithms

Search a row then a column

Updated

When each row is sorted, you can reject a row from its ends, then binary search only the rows that could hold the target. One useful cut: if a[r][C-1] < target, skip row r; if a[r][0] > target, skip it the other way.

What to focus on

After you land on a candidate row, binary search that row alone. You do not flatten. A column-sorted matrix can pick a column first instead.

Worked examples

row 1 then mid col

a = [[1, 4, 9], [10, 11, 12]], target 11
  1. row 0 last 9 < 11, skip
  2. row 1 first 10 ≤ 11 ≤ last 12
  3. binary search cols 0..2, mid=1 a[1][1]=11

Result: (1, 1)

row 0

a = [[1, 4, 9], [10, 11, 12]], target 4
  1. row 0 last 9 ≥ 4 and first 1 ≤ 4
  2. cols 0..2 mid=1 a[0][1]=4

Result: (0, 1)

no row

a = [[1, 4, 9], [10, 11, 12]], target 8
  1. row 0 last 9 ≥ 8, search [1,4,9] miss
  2. row 1 first 10 > 8, skip

Result: not found

Try it

Write searchRowThenCol(a, t). a is a matrix with sorted rows. t is the target. On a chosen row, L, mid, and R are column indices. Return (row, col) or not found. [[1, 4, 9], [10, 11, 12]] t=11 → (1, 1) t=4 → (0, 1) t=8 → not found

Each row is sorted non-decreasing. The matrix is non-empty with at least one column. L, mid, and R are column indices on the chosen row.