Search Sorted Grid

Search Sorted Grid

Each row of the grid is sorted left-to-right and each column is sorted top-to-bottom. Return true if target appears in the grid.

searchGrid(grid, target)

Input format: rows | target, where rows are separated by ; and the values in each row are space-separated. For example 1 4 7;2 5 8;3 6 9 | 5.

Examples

[[1,4,7],[2,5,8],[3,6,9]], target=5   // → true
[[1,4,7],[2,5,8],[3,6,9]], target=0   // → false

Walkthrough

Thinking it through

Each row is sorted left to right, each column top to bottom — richer structure than a single sorted list, but there's no single global ordering across two dimensions, so plain binary search on the whole grid doesn't directly apply. The challenge is finding a starting position where every comparison gives an unambiguous direction.

Why the top-left and bottom-right corners don't work

The top-left corner is the smallest value in the grid — if it's less than the target, both "move right" and "move down" lead to larger values, so you learn nothing about direction. Top-left and bottom-right are the two corners where increasing rows and increasing columns push the value the same way, so a comparison there only rules out that one cell.

Why the top-right (or bottom-left) corner works

The top-right corner is the largest value in its row and the smallest in its column — simultaneously. That dual property makes every comparison decisive:

  • Equal to target? Done.
  • Greater than target? It's already the smallest in its column, so everything below is even larger — eliminate the whole column, move left.
  • Less than target? It's already the largest in its row, so everything left is even smaller — eliminate the whole row, move down.

Each comparison eliminates a whole row or column, never just one cell.

Why this is efficient

Every step moves left (one fewer column) or down (one fewer row), stopping on a match or falling off the grid. Since you can move left at most "columns" times and down at most "rows" times, total steps are bounded by rows plus columns — far better than checking every cell (rows × columns). This staircase walk is the two-dimensional version of binary search's elimination principle: each comparison must rule out a large chunk of the remaining space, never just one element.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.