🧠
Binary Search on Each Row
💡 This approach applies binary search on each row individually, leveraging the sorted rows but ignoring column sorting, improving over brute force but less efficient than staircase search.
Intuition
Since each row is sorted, perform binary search on each row to find the target. If found in any row, return true.
Algorithm
- For each row in the matrix:
- Perform binary search to find the target in that row.
- If found, return true.
- If all rows searched without success, return false.
💡 This approach improves search within rows but still requires scanning all rows, so it is not fully optimal.
def binary_search(row, target):
left, right = 0, len(row) - 1
while left <= right:
mid = (left + right) // 2
if row[mid] == target:
return True
elif row[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,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]]
target = 5
print(searchMatrix(matrix, target)) # Expected: True
Line Notes
left, right = 0, len(row) - 1Initialize binary search pointers for the current row to define search boundaries.
mid = (left + right) // 2Calculate middle index to check the middle element efficiently.
if row[mid] == target:Return true immediately if target found to stop searching this row.
for row in matrix:Iterate over each row to apply binary search individually.
public class Solution {
private static boolean binarySearch(int[] row, int target) {
int left = 0, right = row.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (row[mid] == target) return true;
else if (row[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,4,7,11,15},
{2,5,8,12,19},
{3,6,9,16,22},
{10,13,14,17,24},
{18,21,23,26,30}
};
int target = 5;
System.out.println(searchMatrix(matrix, target)); // Expected: true
}
}
Line Notes
int left = 0, right = row.length - 1;Initialize binary search pointers to define the search range in the row.
int mid = left + (right - left) / 2;Calculate mid index safely to avoid overflow.
if (row[mid] == target) return true;Return true immediately if target found to stop searching this row.
for (int[] row : matrix)Iterate over each row to apply binary search individually.
#include <iostream>
#include <vector>
using namespace std;
bool binarySearch(const vector<int>& row, int target) {
int left = 0, right = (int)row.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (row[mid] == target) return true;
else if (row[mid] < target) left = mid + 1;
else right = mid - 1;
}
return false;
}
bool searchMatrix(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,4,7,11,15},
{2,5,8,12,19},
{3,6,9,16,22},
{10,13,14,17,24},
{18,21,23,26,30}
};
int target = 5;
cout << (searchMatrix(matrix, target) ? "true" : "false") << endl; // Expected: true
return 0;
}
Line Notes
int left = 0, right = (int)row.size() - 1;Initialize binary search pointers to define the search range in the row.
int mid = left + (right - left) / 2;Calculate mid index safely to avoid overflow.
if (row[mid] == target) return true;Return true immediately if target found to stop searching this row.
for (const auto& row : matrix)Iterate over each row to apply binary search individually.
function binarySearch(row, target) {
let left = 0, right = row.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (row[mid] === target) return true;
else if (row[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,4,7,11,15],
[2,5,8,12,19],
[3,6,9,16,22],
[10,13,14,17,24],
[18,21,23,26,30]
];
const target = 5;
console.log(searchMatrix(matrix, target)); // Expected: true
Line Notes
let left = 0, right = row.length - 1;Initialize binary search pointers to define the search range in the row.
let mid = Math.floor((left + right) / 2);Calculate mid index to check the middle element efficiently.
if (row[mid] === target) return true;Return true immediately if target found to stop searching this row.
for (const row of matrix)Iterate over each row to apply binary search individually.
TimeO(m * log n)
SpaceO(1)
Binary search on each of the m rows takes O(log n) time, so total is O(m log n). Space is constant.
💡 For a 300x300 matrix, this means about 300 * 9 = 2700 operations, which is efficient but slower than staircase search.
Interview Verdict: Accepted but not optimal
This approach is a good improvement over brute force but not the best. Interviewers expect the staircase search for optimality.