Search a 2D Matrix
Find a value in a row-sorted matrix in O(log(m * n)) by treating it as one long sorted array.
The problem
You get an m x n integer matrix where each row is sorted in increasing order and the first number of each row is bigger than the last number of the row above it. Return true if target is in the matrix and false otherwise. Your solution must run in O(log(m * n)) time.
Input matrix = [[2, 4, 7], [10, 13, 15], [21, 30, 41]], target = 13
Output true
13 is in the middle row.
Input matrix = [[1, 5], [8, 9]], target = 6
Output false
6 would fall between 5 and 8, at the break between two rows, but it isn't there.
How to spot the pattern
- Reading the rows one after another gives a single sorted list.
- The time limit, O(log(m * n)), asks for one binary search over all the cells.
The idea
Each row starts above where the previous row ended, so reading the matrix row by row gives one sorted list of m * n numbers. Run a normal binary search over the positions 0 to m * n - 1, and turn each position p into the cell at row p / n and column p % n. You never build the list; the index math does it for you.
Brute force: Check every cell, which takes O(m * n) time.
Step by step
- 1Set
lo = 0andhi = m * n - 1. - 2While
lo <= hi, takemidand read the cellmatrix[mid / n][mid % n], using integer division. - 3If the cell equals
target, returntrue. - 4If it is smaller, set
lo = mid + 1; otherwise sethi = mid - 1. - 5If the loop ends, return
false.
See the pattern move
The binary search pattern on a small example. Step through it, or press play.
Code
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m, n = len(matrix), len(matrix[0])
lo, hi = 0, m * n - 1 # positions in the matrix read row by row
while lo <= hi:
mid = lo + (hi - lo) // 2
value = matrix[mid // n][mid % n]
if value == target:
return True
if value < target:
lo = mid + 1
else:
hi = mid - 1
return FalseComplexity
Time
O(log(m * n))
Space
O(1)
One binary search over m * n positions; turning a position into a cell costs O(1).
Watch out for
- Dividing by the number of rows instead of the row length: the row of position p is
p / n, where n is the number of columns. - Copying the matrix into a flat list first, which works but costs O(m * n) time and space and defeats the point.
Follow-up questions
What if every row and every column is sorted, but a row doesn't continue from the one above?
That is Search a 2D Matrix II. Start at the top-right corner: if the value is too big, move left; if it is too small, move down. Each step removes a row or a column, so it takes O(m + n).
Can you do it with two binary searches instead?
Yes: first find the last row whose first value is at most the target, then binary search inside that row. That is O(log m + log n), which equals O(log(m * n)).
In Hinglish
Matrix ko ek lambi sorted list samjho; position p ka row p / n aur column p % n hai, bas normal binary search chalao.