Skip to content
BytePatterns

Search A Sorted Grid

MediumMatrix & Grid#staircase-walk#grid-search~25m

Problem

A grid has every row sorted increasing from left to right, and every column sorted increasing from top to bottom. Find a target value and report its position as a row and column pair, or report that it is absent. Scanning every cell is too slow for a large grid.

Examples

Input:  grid = [[1, 4, 7, 11],
                [2, 5, 8, 12],
                [3, 6, 9, 16]], target = 5
Output: (1, 1)
Input:  same grid, target = 10
Output: None
Why:    10 sits between 9 and 11 but appears nowhere
Input:  grid = [[1]], target = 1
Output: (0, 0)
Why:    edge case, a single cell grid

Hints

0 / 3

Stuck on the idea rather than the code? Search a 2D Matrix covers it.