You are given an m x n integer matrix matrix with the following two properties:
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.
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: false
The key insight is that the matrix is fully sorted - if we flatten it into a 1D array, it would be sorted. We can perform binary search on this "virtual" 1D array without actually creating it!
Mapping: Given index i in flattened array:
i / colsi % colsThis lets us use standard binary search while working with the 2D structure.
This is Binary Search on 2D Matrix with these characteristics:
Treat as 1D Array:
m * n0 to m * n - 1Binary Search:
left = 0, right = m * n - 1mid = left + (right - left) / 2row = mid / n, col = mid % nmatrix[row][col]Standard Binary Search Logic:
matrix[row][col] == target: Return truematrix[row][col] < target: Search right halfmatrix[row][col] > target: Search left halfNot Found: Return false
Time Complexity: O(log(m * n)) where m = rows, n = cols
Space Complexity: O(1)
Two Binary Searches: O(log m + log n)
Linear Search Each Row: O(m * n)
1class Solution {
2 public boolean searchMatrix(int[][] matrix, int target) {
3 if (matrix == null || matrix.length == 0) {
4 return false;
5 }
6
7 int m = matrix.length; // rows
8 int n = matrix[0].length; // cols
9
10 // Binary search on "virtual" 1D array
11 int left = 0;
12 int right = m * n - 1;
13
14 while (left <= right) {
15 int mid = left + (right - left) / 2;
16
17 // Convert 1D index to 2D coordinates
18 int row = mid / n;
19 int col = mid % n;
20 int midValue = matrix[row][col];
21
22 if (midValue == target) {
23 return true;
24 } else if (midValue < target) {
25 left = mid + 1;
26 } else {
27 right = mid - 1;
28 }
29 }
30
31 return false;
32 }
33}
34