Search a 2D Matrix 1 - Elements sorted row-wise and first integer of each row is greater than last element of previous row is greater than last element of previous row
Medium
Subtopics
array·binary-search·matrix
Companies
adobe·amazon·apple·bloomberg·facebook·google·microsoft·uberLast updated: Aug 2, 2025
Because each row is sorted and the first element of each row is greater than the last element of the previous row, the entire matrix can be viewed as a single sorted 1D array. This allows us to use classic binary search by mapping a 1D index to 2D coordinates.
classSolution {
public:bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size(), n = matrix[0].size();
int left =0, right = m * n -1;
while (left <= right) {
int mid = left + (right - left) /2;
int row = mid / n, col = mid % n;
int val = matrix[row][col];
if (val == target) return true;
elseif (val < target) left = mid +1;
else right = mid -1;
}
return false;
}
};
classSolution {
publicbooleansearchMatrix(int[][] matrix, int target) {
int m = matrix.length, n = matrix[0].length;
int left = 0, right = m * n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
int row = mid / n, col = mid % n;
int val = matrix[row][col];
if (val == target) returntrue;
elseif (val < target) left = mid + 1;
else right = mid - 1;
}
returnfalse;
}
}
classSolution {
funsearchMatrix(matrix: Array<IntArray>, target: Int): Boolean {
val m = matrix.size
val n = matrix[0].size
var left = 0var right = m * n - 1while (left <= right) {
val mid = left + (right - left) / 2val row = mid / n
val col = mid % n
val value = matrix[row][col]
when {
value== target ->returntruevalue < target -> left = mid + 1else-> right = mid - 1 }
}
returnfalse }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
defsearchMatrix(self, matrix: list[list[int]], target: int) -> bool:
m, n = len(matrix), len(matrix[0])
left, right =0, m * n -1while left <= right:
mid = (left + right) //2 row, col = divmod(mid, n)
val = matrix[row][col]
if val == target:
returnTrueelif val < target:
left = mid +1else:
right = mid -1returnFalse
impl Solution {
pubfnsearch_matrix(matrix: Vec<Vec<i32>>, target: i32) -> bool {
let (m, n) = (matrix.len(), matrix[0].len());
let (mut left, mut right) = (0, (m * n) asi32-1);
while left <= right {
let mid = left + (right - left) /2;
let row = (mid / n asi32) asusize;
let col = (mid % n asi32) asusize;
let val = matrix[row][col];
if val == target {
returntrue;
} elseif val < target {
left = mid +1;
} else {
right = mid -1;
}
}
false }
}
⏰ Time complexity: O(log(mn)), where m is the number of rows and n is the number of columns. Binary search is performed over the entire matrix as a flat array.
🧺 Space complexity: O(1), as only a constant amount of extra space is used.