26. Search a 2D Matrix
Each row of matrix is sorted, and the first value of every row is greater than the last value of the row above. Return whether target exists, in O(log(m·n)).
Example 1
Input:
matrix = [[1,4,7],[10,13,16],[20,22,25]], target = 13Output:
trueExample 2
Input:
matrix = [[1,4,7],[10,13,16],[20,22,25]], target = 15Output:
falseHint 1
Reading the rows one after another gives a single sorted array of length m·n.
Hint 2
Index k maps to row k / n, column k % n.
Approach 1: Row then column
Binary-search the row, then the column.
⏱ Time O(log m + log n)💾 Space O(1)
Approach 2: Flattened binary search ✅
One binary search over virtual indices 0..m·n−1.
⏱ Time O(log(m·n))💾 Space O(1)
Reference solution for Flattened binary search (time O(log(m·n)), space O(1)). Each solution passes every test in all four languages.
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 # treat the matrix as one sorted array
while lo <= hi:
mid = (lo + hi) // 2
v = matrix[mid // n][mid % n]
if v == target:
return True
if v < target:
lo = mid + 1
else:
hi = mid - 1
return Falseclass Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length, n = matrix[0].length, lo = 0, hi = m * n - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2, v = matrix[mid / n][mid % n];
if (v == target) return true;
if (v < target) lo = mid + 1; else hi = mid - 1;
}
return false;
}
}class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size(), n = matrix[0].size(), lo = 0, hi = m * n - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2, v = matrix[mid / n][mid % n];
if (v == target) return true;
if (v < target) lo = mid + 1; else hi = mid - 1;
}
return false;
}
};function searchMatrix(matrix, target) {
const m = matrix.length, n = matrix[0].length;
let lo = 0, hi = m * n - 1;
while (lo <= hi) {
const mid = (lo + hi) >> 1, v = matrix[Math.floor(mid / n)][mid % n];
if (v === target) return true;
if (v < target) lo = mid + 1; else hi = mid - 1;
}
return false;
}Try solving it yourself first. Interviewers care more about how you explain the approach than about the finished code.
This problem is explained in the lesson Binary Search.
Run your code to see results here.