LeetCode #74 Medium

Search a 2D Matrix

Search a 2D Matrix is LeetCode 74 (Medium). You get an m x n grid of integers and a target. Each row is sorted in non-decreasing order, and the first value of every row is greater than the last value of the row above it. Return true if target is in the grid, otherwise false.

  • The solution must run in O(log(m · n)) time.
  • The grid always has at least one row and one column, and at most 100 of each.
Constraints
  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 100
  • -10⁴ <= matrix[i][j], target <= 10⁴
arraybinary-searchmatrix
Open on LeetCode ↗
02

Intuition

The second rule is what matters. If every row starts above where the previous row ended, then reading the grid row by row, left to right, gives one sorted list of m · n values. The grid is only that list cut into rows of length n.

So run an ordinary binary search over positions 0 to m · n − 1, and turn a position back into a cell only when you need its value: position p lives in row p // n, column p % n. Nothing is copied, and every comparison still halves the range.

How to spot this pattern

A grid whose rows join end to start into one sorted run, with a yes/no lookup: binary search over cell positions, not over rows and columns separately.

03

Approach

Try it first

Before reading on, write the cells of a small grid in reading order and number them from 0. Which row and column does number 7 belong to in a grid with 4 columns? Turn that into a binary search with O(1) extra space.

1

Number the cells in reading order

Let n be the row length. Position p stands for row p // n and column p % n, so positions 0 to m · n − 1 cover every cell once, in sorted order. Search that range with lo = 0 and hi = m · n − 1.

2

Read the middle cell

Take mid = (lo + hi) // 2 and read matrix[mid // n][mid % n]. The division gives how many full rows come before the position, and the remainder gives how far into the next row it is.

3

Throw away the half that cannot match

If the value equals target, return true. If it is smaller, the target can only be at a later position, so set lo = mid + 1; if it is larger, set hi = mid - 1. The middle cell is ruled out either way.

4

Stop when the range is empty

Loop while lo <= hi. When lo passes hi, every position that could hold target has been ruled out, so return false.

04

Code in Python, C++ and Java

▶1from typing import List
▶2 
▶3 
▶4class Solution:
▶5 def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
▶6 m, n = len(matrix), len(matrix[0])
▶7 lo, hi = 0, m * n - 1
▶8 while lo <= hi:
▶9 mid = (lo + hi) // 2
▶10 value = matrix[mid // n][mid % n]
▶11 if value == target:
▶12 return True
▶13 if value < target:
▶14 lo = mid + 1
▶15 else:
▶16 hi = mid - 1
▶17 return False
row 01357row 110111620row 223303460positionrow, columnrow 0row 1row 210lo31527310411516620723830934106011hisearch positions 0 to 11 for 3
lo0
hi11
row length n4
Each row starts above where the row before it ended, so the 12 cells read left to right, top to bottom, form one sorted list. The bottom strip is that list. The search runs over its positions and never builds it.
row 01357row 110111620row 223303460position5row, column11row 0row 1row 210lo315273104115mid16620723830934106011hi11 is bigger than 3 → keep positions 0 to 4
mid5
cell(1, 1)
hi4
Position 5 has 1 full row of 4 before it and sits 1 into the next, so it is row 1, column 1, holding 11. It is bigger than 3, and every later position is bigger still, so the target can only come earlier.
row 01357row 110111620row 223303460position2row, column02row 0row 1row 210lo3152mid73104hi115166207238309341060115 is bigger than 3 → keep positions 0 to 1
mid2
cell(0, 2)
hi1
Position 2 has 0 full rows of 4 before it and sits 2 into the next, so it is row 0, column 2, holding 5. It is bigger than 3, and every later position is bigger still, so the target can only come earlier.
row 01357row 110111620row 223303460position0row, column00row 0row 1row 210lomid31hi5273104115166207238309341060111 is smaller than 3 → keep position 1
mid0
cell(0, 0)
lo1
Position 0 has 0 full rows of 4 before it and sits 0 into the next, so it is row 0, column 0, holding 1. It is smaller than 3, and every earlier position is smaller still, so the target can only come later.
row 01357row 110111620row 223303460position1row, column01row 0row 1row 21031lohi527310411516620723830934106011position 1 holds 3 → found it
mid1
cell(0, 1)
answertrue
Position 1 has 0 full rows of 4 before it and sits 1 into the next, so it is row 0, column 1, holding 3. That is the target, so return true. It took 4 comparisons for 12 cells.
05

Common pitfalls

Dividing by the number of rows

✗ Wrong
value = matrix[mid // m][mid % m]
✓ Right
value = matrix[mid // n][mid % n]

A position skips one row for every n cells, so n (the row length) is the divisor. On the 2 × 3 grid [[1, 2, 3], [4, 5, 6]], position 3 is the 4; dividing by m = 2 reads the 5 instead, and position 5 asks for row 2, which does not exist.

Letting hi start one past the last cell

✗ Wrong
lo, hi = 0, m * n
✓ Right
lo, hi = 0, m * n - 1

With lo <= hi the range includes hi itself, so it must be a real cell. On [[1]] with target 5, the middle moves to position 1 and reads row 1 of a one-row grid, which crashes.

06

Edge cases

A single column, e.g. [[1], [3], [5]]

Here n = 1, so position p is simply row p and column 0. The same loop becomes a binary search down the column with no special case.

07

Complexity

Time
O(log(m · n))
Space
O(1)
A 100 × 100 grid has 10,000 cells, so at most 14 comparisons. Only three indices are stored; the grid is never copied into a flat list.
08

Search a 2D Matrix FAQ

Can I find the row first and then search inside it?

Yes. Binary search the first column for the last row that starts at or below target, then binary search that row. That is O(log m + log n), the same as O(log(m · n)); it just takes two loops where the position trick needs one.

Does the walk from the top-right corner work on this grid?

It gives the right answer, since this grid is also sorted down each column. It costs O(m + n), though: up to 199 steps on a 100 × 100 grid against 14 here. That walk is the right tool for Search a 2D Matrix II, where rows do not follow on from each other and there is no single sorted list to search.