🧠
Binary Search on Each Row
💡 This approach improves over brute force by using binary search on each row, leveraging the sorted nature of rows.
Intuition
Since each row is sorted, we can binary search each row individually to find the target faster than scanning all elements.
Algorithm
- For each row in the matrix:
- Perform binary search to find the target in that row.
- If found, return true immediately.
- If target not found in any row, return false.
💡 The key is applying binary search on each row independently, which is faster than linear search but still not optimal.
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return True
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return False
def searchMatrix(matrix, target):
for row in matrix:
if binary_search(row, target):
return True
return False
# Driver code
if __name__ == '__main__':
matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]]
target = 3
print(searchMatrix(matrix, target)) # True
Line Notes
left, right = 0, len(arr) - 1Initialize binary search boundaries
mid = (left + right) // 2Find middle index to check
if arr[mid] == target:Check if middle element is target
if binary_search(row, target):Return true immediately if target found in any row
public class Solution {
public static boolean binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) return true;
else if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return false;
}
public static boolean searchMatrix(int[][] matrix, int target) {
for (int[] row : matrix) {
if (binarySearch(row, target)) return true;
}
return false;
}
public static void main(String[] args) {
int[][] matrix = {{1,3,5,7},{10,11,16,20},{23,30,34,60}};
int target = 3;
System.out.println(searchMatrix(matrix, target)); // true
}
}
Line Notes
int left = 0, right = arr.length - 1;Set initial binary search boundaries
int mid = left + (right - left) / 2;Calculate mid index safely to avoid overflow
if (arr[mid] == target) return true;Return true if target found at mid
if (binarySearch(row, target)) return true;Stop searching rows once target found
#include <iostream>
#include <vector>
using namespace std;
bool binarySearch(const vector<int>& arr, int target) {
int left = 0, right = (int)arr.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) return true;
else if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return false;
}
bool searchMatrix(const vector<vector<int>>& matrix, int target) {
for (const auto& row : matrix) {
if (binarySearch(row, target)) return true;
}
return false;
}
int main() {
vector<vector<int>> matrix = {{1,3,5,7},{10,11,16,20},{23,30,34,60}};
int target = 3;
cout << (searchMatrix(matrix, target) ? "true" : "false") << endl; // true
return 0;
}
Line Notes
int left = 0, right = (int)arr.size() - 1;Initialize binary search boundaries
int mid = left + (right - left) / 2;Calculate mid index safely
if (arr[mid] == target) return true;Return true if target found
if (binarySearch(row, target)) return true;Return early if target found in any row
function binarySearch(arr, target) {
let left = 0, right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) return true;
else if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return false;
}
function searchMatrix(matrix, target) {
for (const row of matrix) {
if (binarySearch(row, target)) return true;
}
return false;
}
// Test
const matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]];
const target = 3;
console.log(searchMatrix(matrix, target)); // true
Line Notes
let left = 0, right = arr.length - 1;Initialize binary search boundaries
const mid = Math.floor((left + right) / 2);Calculate middle index
if (arr[mid] === target) return true;Return true if target found
if (binarySearch(row, target)) return true;Return early if target found in any row
TimeO(m * log n)
SpaceO(1)
We do binary search on each of the m rows, each binary search takes O(log n).
💡 For 100 rows and 100 columns, this means about 100 * 7 = 700 operations, much faster than brute force.
Interview Verdict: Accepted, better but not optimal
This approach is a good improvement but still not the best because it does not use the full matrix ordering.