Skip to main content

Search a 2D Matrix

Problem

Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

Solution Approach

Click - to see solution code
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int n = matrix.size();
int start = 0, end = n - 1;
int mid, indx = 0;

while (start <= end) {
mid = (start + end) / 2;
if (matrix[mid][0] > target) {
end = mid - 1;
} else {
indx = mid;
start = mid + 1;
}
}

start = 0, end = matrix[0].size() - 1;
int i = 0;
while (start <= end) {
mid = (start + end) / 2;
if (matrix[indx][mid] > target) {
end = mid - 1;
} else {
i = mid;
start = mid + 1;
}
}
if (matrix[indx][i] == target) return true;
return false;
}
};