Search a 2D Matrix
Medium
Binary SearchMatrix
Problem
Each row of the matrix is sorted ascending, and the first integer of each row is greater than the last integer of the previous row. Return true iff target is in the matrix. Aim for O(log m·n).
Example 1
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true
Example 2
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: false
Constraints
- 1 ≤ m, n ≤ 100
- −10⁴ ≤ matrix[i][j], target ≤ 10⁴
Approach — Binary Search
This is a Binary Search problem. The idea: repeatedly halve the search space, discarding the half that can't contain the answer. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(log n) time.
Solution code
Python
class Solution:
def searchMatrix(self, matrix, target):
if not matrix or not matrix[0]:
return False
rows, cols = len(matrix), len(matrix[0])
lo, hi = 0, rows * cols - 1
while lo <= hi:
mid = (lo + hi) // 2
v = matrix[mid // cols][mid % cols]
if v == target:
return True
if v < target:
lo = mid + 1
else:
hi = mid - 1
return False
Java
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length, n = matrix[0].length;
int l = 0, r = m * n - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
int v = matrix[mid / n][mid % n];
if (v == target) return true;
if (v < target) l = mid + 1;
else r = mid - 1;
}
return false;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Search a 2D Matrix interactively → ← All solutions