Python coding

Find a value in a sorted grid

A grid of distinct integers is sorted so that reading it row by row, left to right, gives one increasing sequence: each row increases, and each row's first value is greater than the last value of the row before. Given that grid grid (m rows of n values) and an integer target, return [row, col] where target sits, or [-1, -1] if it is not there.

grid may be empty ([]); otherwise every row has the same length, at least 1. Aim for O(log(m · n)): checking every cell is O(m · n).

  • find_in_grid([[2,5,9,11],[14,18,21,30],[33,40,47,52]], 21) → [1,2]
  • find_in_grid([[2,5,9,11],[14,18,21,30],[33,40,47,52]], 13) → [-1,-1]
  • find_in_grid([[2,5,9,11],[14,18,21,30],[33,40,47,52]], 2) → [0,0]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Read row by row, the grid is one sorted list. You don't need to build it: binary search its indexes 0 … m·n − 1 directly.

Hint 2

Index i of that virtual list is the cell divmod(i, n), where n is the number of columns. Run a lower bound for target, then check the cell it lands on.

Hint 3

Divide by the number of columns, not rows. A square grid hides that mix-up; try a 3 × 4 grid and a single column.

Solution and why it works
pythonO(log(m · n)) · O(1)
def find_in_grid(grid: list[list[int]], target: int) -> list[int]:
    if not grid:
        return [-1, -1]
    cols = len(grid[0])
    lo, hi = 0, len(grid) * cols          # half-open range over the flattened grid
    while lo < hi:
        mid = (lo + hi) // 2
        row, col = divmod(mid, cols)
        if grid[row][col] < target:
            lo = mid + 1
        else:
            hi = mid
    row, col = divmod(lo, cols)
    if lo < len(grid) * cols and grid[row][col] == target:
        return [row, col]
    return [-1, -1]

Read row by row, the grid is one sorted list of m · n values, and index i of that list is cell (i // n, i % n). So one binary search over 0 … m·n − 1 finds target in O(log(m · n)) without copying a cell. The trap is dividing by the number of rows instead of columns: a square grid hides the bug, a 3 × 4 grid exposes it. A row search followed by a column search also works, with two boundaries to get right instead of one.

Related lab: Loops in motion