Search a 2D Matrix
Find a number in a sorted grid where each row continues the row before it
DSA, Medium, Binary Search
Which structure or algorithm, and what does it cost.
A grid matrix has rows of equal length. Each row is sorted from smallest to largest. The first number of each row is larger than the last number of the row before it. You also get a number target. Return True if target appears anywhere in the grid, otherwise return False.
Examples
Constraints
- 1 <= number of rows <= 300 and 1 <= number of columns <= 300.
- Every row has the same number of cells.
- Each value is a whole number between -1,000,000,000 and 1,000,000,000, and so is
target. - Each row is sorted. The first number of each row is larger than the last number of the row before it.
- The grid is searched many times, so checking every cell is not accepted.
Your answer must contain
- The simple method and why it is too slow; the better method; code; time and memory cost; a hand trace of example 1.
Target Aim for O(log(rows * columns)) time and O(1) memory.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Look at the last number of one row and the first number of the next row. What does the order look like across that boundary?
Hint 2 the approach
This is one sorted list in disguise. You can search it as a list without building a copy of it.
Hint 3 the key step
Search positions 0 to rows times columns minus 1. How do you turn one position back into a row and a column, using only the column count?
Walkthrough
Full walkthrough brute force to best
Brute force
Check every cell. That is O(rows * columns) time and O(1) memory, up to 90,000 checks for a 300 by 300 grid. It ignores the sorted order.
Better method
Binary search the first column to find the last row whose first value is at most the target. Then binary search inside that row. This costs O(log rows + log columns) time, the same order as the best method, but it needs two loops and two sets of edge cases.
Best method
Each row starts above the end of the row before it, so reading the grid row by row gives one sorted list of rows * columns values. Run binary search on the positions 0 to rows * columns - 1 and never build the list. Position p lives at row p // columns and column p % columns. Compare that value with the target and keep the left or the right part, as in a plain binary search. There is one loop and one range, so there are fewer places to slip.
Hand trace
Run on the 3 by 3 grid with target 27. There are 9 positions, so lo is 0 and hi is 8. The middle position 4 is row 1, column 1, value 14. 14 is smaller than 27, so lo becomes 5. The middle position 6 is row 2, column 0, value 23. It is smaller again, so lo becomes 7. The middle position 7 is row 2, column 1, value 27. It matches, so return True.
Code
def search_matrix(matrix, target):
rows, cols = len(matrix), len(matrix[0])
lo, hi = 0, rows * cols - 1 # positions in the grid read row by row
while lo <= hi:
mid = (lo + hi) // 2
value = matrix[mid // cols][mid % cols]
if value == target:
return True
if value < target:
lo = mid + 1
else:
hi = mid - 1
return FalseTime and memory
O(log(rows * columns)) time, because the range of positions halves each step: at most 17 steps for 90,000 cells. O(1) memory, since the flat list is never built.
Common mistakes
- Swapping rows and columns in the position formula. The row is
p // columnsand the column isp % columns. - Building the flat list first. That costs O(rows * columns) time and memory and throws away the benefit of searching.
- Ignoring the rule that each row starts above the end of the row before it. Without it the grid is not one sorted list, and this method can give wrong answers.