iq.lab
Python starts when a code cell comes near or you run one
mediumBinary search target 25 min

Search a sorted grid

A grid of integers matrix has m rows and n columns and is sorted in reading order, the order of words on a page: left to right along a row, then on to the next row. Two facts make that true. Along a row, values never go down from left to right (repeats are allowed). And the first value of each row is bigger than the last value of the row above it.

Report whether some cell holds target: return True if one does and False if none does.

Checking every cell gives the right answer but fails the speed test. Aim for O(log(m·n)) time.

Example 1
Inputmatrix = [[1, 4, 7], [10, 13, 16], [20, 25, 30]], target = 13OutputTrue

13 is in row 1, column 1.

Example 2
Inputmatrix = [[1, 4, 7], [10, 13, 16], [20, 25, 30]], target = 8OutputFalse

In reading order, 8 would fall between 7, the end of row 0, and 10, the start of row 1. No cell holds it.

Example 3
Inputmatrix = [[3, 5, 8, 12]], target = 3OutputTrue

A grid can have a single row. 3 is its first cell.

Constraints
  • 1 ≤ m, n ≤ 6,500: the grid is never empty, and every row has n values.

  • Values and target are integers.

  • The speed test passes a 6,500 by 6,500 grid (42,250,000 cells) that computes each cell when you read it. It supports len(matrix), matrix[r], len(matrix[r]) and matrix[r][c] (negative indexes too) but not slicing. Reading every cell takes seconds.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.