Searching something that is not a list

Binary Search

Searching something that is not a list

Any structure you can index in order can be binary searched, including a grid.

Key idea

The loop does not care what it is searching

The template from the last lesson never touches a list. It manipulates numbers and calls a property. So it can search anything you can address by an integer position, provided the property stays monotone.

A grid whose rows are sorted and where each row starts above the previous row's end is, read row by row, one long sorted sequence. It just is not stored that way.

Why it works

Position to coordinates

Number the cells from 0 in reading order. For a grid with cols columns, position p sits at row p // cols and column p % cols.

Integer division counts how many complete rows fit before you, and the remainder is how far along the current row you are. This is the same arithmetic as the block index from Unit 1, used for the opposite purpose: there it collapsed coordinates into a region, here it expands a position into coordinates.

With that mapping, searching the grid is the ordinary boundary loop with one substitution.

Edge cases

Guard the shape first

An empty grid, or a grid whose rows are empty, breaks len(grid[0]) before any searching happens. Check the shape before computing cols.

Also confirm the problem's guarantee. This works because each row starts above the previous row's last value. If rows are individually sorted but rows do not chain that way, the flattened sequence is not sorted and this approach is simply wrong; that variant needs a staircase walk from a corner instead.

Tip

The two-stage alternative

You can also binary search for the right row, then binary search within it. That is two O(log) searches instead of one, so the complexity is the same, and it needs no index arithmetic.

Either is a fine answer. The flattened version is shorter; the two-stage version is easier to explain out loud. Say which you are doing and why.

Where does position 7 sit?

A grid has 3 columns. Using reading order numbered from 0, which cell is position 7?

Search A 2d Matrix

Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.

Loading the workspace…
← Previous