CodeArchon

mediumBinary SearchAmazonGoogle

Flattened Grid Lookup

A warehouse packs items row-first into a grid whose rows and row-starts are both sorted. Find a specific SKU.

Given an m × n matrix where each row is sorted and `grid[r][0] > grid[r−1][n−1]`, decide whether a target exists.

Choose approach

1
3
5
7
10
11
16
20
23
30
34
60
1/5
Narrationstep 1 of 5

Treat the m × n matrix as one sorted sequence of length 12. Binary-search its indices.

1def flattened_grid_lookup(grid: list[list[int]], target: int) -> bool:
2 m, n = len(grid), len(grid[0])
3 lo, hi = 0, m * n - 1
4 while lo <= hi:
5 mid = (lo + hi) // 2
6 v = grid[mid // n][mid % n]
7 if v == target:
8 return True
9 if v < target:
10 lo = mid + 1
11 else:
12 hi = mid - 1
13 return False
Variables
m=3
n=4
lo=0
hi=11
target=3

How to think about it

  1. The matrix is one sorted sequence read in row-major order.
  2. Map flat index k to (row = k/n, col = k%n).
  3. Classic O(log(mn)) binary search applies.

Edge cases to catch in interview

  • Single row — degenerates to 1D search.
  • Single column — same.
  • Target smaller than first or larger than last → quickly false.

Examples

Example 1true
{"grid":[[1,3,5,7],[10,11,16,20],[23,30,34,60]],"target":3}
Example 2false
{"grid":[[1,3,5,7],[10,11,16,20],[23,30,34,60]],"target":13}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed