Search a 2D Matrix
Pattern: Binary search on 2D matrices
Each row is sorted and starts above the previous row's end, so the whole matrix read row by row is one sorted list. Binary search positions 0 to R·C - 1, turning position p into cell (p / C, p mod C).
The problem
You are given a matrix in which each row is sorted in increasing order, and the first value of each row is bigger than
the last value of the row before it. Return whether a target value is in the matrix, in O(log(R × C)) time. For example,
[[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]] gives true for 3 and false for 13.
The function name searchMatrix matches LeetCode. Use the link above for the exact statement and limits.
Think first
- If you read the matrix row by row, what do you get?
- Given a position
pin that long list, which row and column is it? - Can you search the list without building it?
Hints
Brute force, and why it fails
Check every cell: O(R × C). Binary search for the row, then within the row, also works in O(log R + log C). The 1D view does the same in one loop.
The key insight
A matrix is just a way of laying out a list. When the layout keeps the order, an index formula turns the matrix back into a sorted array.
Dry run
The matrix rows are 1 3 5 7, 10 11 16 20 and 23 30 34 60, and the target is 3. Read row by row, it is one sorted list of 12 values.
The plan
lo = 0, hi = R * C - 1
while lo <= hi:
mid = lo + (hi - lo) / 2
v = matrix[mid / C][mid mod C]
if v == target: return true
if v < target: lo = mid + 1
else: hi = mid - 1
return false
Complexity
- Time
O(log(R × C))- Space
O(1)
One binary search over all positions.
Edge cases
- One cell: compare directly.
- One row or one column: the formula still works.
- Target below the first value or above the last: the search ends with false.
I've built my logic, show the code
Java
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int rows = matrix.length, cols = matrix[0].length;
int lo = 0, hi = rows * cols - 1; // read the matrix row by row as one sorted array
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
int v = matrix[mid / cols][mid % cols]; // index mid is row mid / cols, column mid % cols
if (v == target) return true;
if (v < target) lo = mid + 1;
else hi = mid - 1;
}
return false;
}
}C++
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int rows = static_cast<int>(matrix.size()), cols = static_cast<int>(matrix[0].size());
int lo = 0, hi = rows * cols - 1; // read the matrix row by row as one sorted array
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
int v = matrix[mid / cols][mid % cols]; // index mid is row mid / cols, column mid % cols
if (v == target) return true;
if (v < target) lo = mid + 1;
else hi = mid - 1;
}
return false;
}
};Python
class Solution:
def searchMatrix(self, matrix: list[list[int]], target: int) -> bool:
rows, cols = len(matrix), len(matrix[0])
lo, hi = 0, rows * cols - 1 # read the matrix row by row as one sorted array
while lo <= hi:
mid = (lo + hi) // 2
v = matrix[mid // cols][mid % cols] # index mid is row mid // cols, column mid % cols
if v == target:
return True
if v < target:
lo = mid + 1
else:
hi = mid - 1
return FalseCommon mistakes
- Dividing by the number of rows instead of columns.
- Using this on a matrix where only rows and columns are sorted (Search a 2D Matrix II), where the rows do not chain.
- Building the flattened list first, which costs O(R × C).