74. Search A 2D Matrix¶
Difficulty: Medium
LeetCode Problem View on GitHub
74. Search a 2D Matrix
Medium
You are given an m x n integer matrix matrix with the following two properties:
- Each row is sorted in non-decreasing order.
- The first integer of each row is greater than the last integer of the previous row.
Given an integer target, return true if target is in matrix or false otherwise.
You must write a solution in O(log(m * n)) time complexity.
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:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 100-104 <= matrix[i][j], target <= 104
Solution¶
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int n = matrix.length, m = matrix[0].length;
int low = 0, high = n - 1, ans = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (target >= matrix[mid][0] && target <= matrix[mid][m - 1]) {
return BS(matrix[mid], target);
}
else if (target > matrix[mid][m - 1]) {
low = mid + 1;
}
else high = mid - 1;
}
return false;
}
private boolean BS(int arr[], int target) {
int n = arr.length;
int low = 0, high = n - 1, ans = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target)
return true;
else if (arr[mid] > target) {
high = mid - 1;
}
else low = mid + 1;
}
return false;
}
}
Complexity Analysis¶
- Time Complexity:
O(?) - Space Complexity:
O(?)
Approach¶
Detailed explanation of the approach will be added here