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.
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 100
- -10⁴ <= matrix[i][j], target <= 10⁴
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.
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.
Approach
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.
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.
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.
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.
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.
Code in Python, C++ and Java
lo (6) has passed hi (5). Every position was ruled out by a comparison, so return false. 13 would sit between 11 and 16, and no cell holds it.Common pitfalls
Dividing by the number of rows
value = matrix[mid // m][mid % m]
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
lo, hi = 0, m * n
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.
Edge cases
[[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.
Complexity
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.