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.
Variables
m=3
n=4
lo=0
hi=11
target=3
How to think about it
- The matrix is one sorted sequence read in row-major order.
- Map flat index k to (row = k/n, col = k%n).
- 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 1
true{"grid":[[1,3,5,7],[10,11,16,20],[23,30,34,60]],"target":3}
Example 2
false{"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