Given a 2D array matrix where each row is sorted in ascending order from left to right and each column is sorted in ascending order from top to bottom, write an efficient algorithm to search for a specific integer target in the matrix.
Input: 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
Output: True
Explanation: The target 5 exists in the matrix in the index (1,1)
Input: 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 = 20
Output: False
Explanation: The target 20 does not exist in the matrix.
Input: 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 = 1
Since the given matrix is sorted (both row-wise and column-wise), this information can be used to optimize the brute-force solution. The brute-force approach involves checking each cell of the matrix for the given target, similar to how it was done in the problem Search in 2D matrix. Here, to optimize the solution, use binary search in each row of the matrix to search for the target. If the target is found return true, else return false.
#include <bits/stdc++.h>
using namespace std;
class Solution {
private:
//Helper function to perform binary search
bool binarySearch(vector<int>& nums, int target) {
int n = nums.size();
int low = 0, high = n - 1;
// Perform the steps:
while (low <= high) {
int mid = (low + high) / 2;
//Return true if target is found
if (nums[mid] == target) return true;
else if (target > nums[mid]) low = mid + 1;
else high = mid - 1;
}
//Return false if target not found
return false;
}
public:
//Function to search for a given target in matrix
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int n = matrix.size();
int m = matrix[0].size();
//Traverse through each row
for (int i = 0; i < n; i++) {
/*Check if target is
present in the current row*/
bool flag = binarySearch(matrix[i], target);
if (flag) return true;
}
// Return false if target is not found
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 = 8;
//Create an instace of Solution class
Solution sol;
bool result = sol.searchMatrix(matrix, target);
// Output the result
result ? cout << "true\n" : cout << "false\n";
return 0;
}
import java.util.*;
class Solution {
// Helper function to perform binary search
private boolean binarySearch(int[] nums, int target) {
int n = nums.length;
int low = 0, high = n - 1;
// Perform the steps:
while (low <= high) {
int mid = (low + high) / 2;
// Return true if target is found
if (nums[mid] == target) return true;
else if (target > nums[mid]) low = mid + 1;
else high = mid - 1;
}
// Return false if target not found
return false;
}
// Function to search for a given target in matrix
public boolean searchMatrix(int[][] matrix, int target) {
int n = matrix.length;
int m = matrix[0].length;
// Traverse through each row
for (int i = 0; i < n; i++) {
/* Check if target is
present in the current row*/
boolean flag = binarySearch(matrix[i], target);
if (flag) return true;
}
// Return false if target is not found
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 = 8;
// Create an instance of Solution class
Solution sol = new Solution();
boolean result = sol.searchMatrix(matrix, target);
// Output the result
System.out.println(result ? "true" : "false");
}
}
class Solution:
# Helper function to perform binary search
def binarySearch(self, nums, target):
n = len(nums)
low, high = 0, n - 1
# Perform the steps:
while low <= high:
mid = (low + high) // 2
# Return true if target is found
if nums[mid] == target:
return True
elif target > nums[mid]:
low = mid + 1
else:
high = mid - 1
# Return false if target not found
return False
# Function to search for a given target in matrix
def searchMatrix(self, matrix, target):
n = len(matrix)
m = len(matrix[0])
# Traverse through each row
for i in range(n):
""" Check if target is
present in the current row"""
flag = self.binarySearch(matrix[i], target)
if flag:
return True
# Return false if target is not found
return False
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 = 8
# Create an instance of Solution class
sol = Solution()
result = sol.searchMatrix(matrix, target)
# Output the result
print("true" if result else "false")
class Solution {
// Helper function to perform binary search
binarySearch(nums, target) {
let n = nums.length;
let low = 0, high = n - 1;
// Perform the steps:
while (low <= high) {
let mid = Math.floor((low + high) / 2);
// Return true if target is found
if (nums[mid] === target) return true;
else if (target > nums[mid]) low = mid + 1;
else high = mid - 1;
}
// Return false if target not found
return false;
}
// Function to search for a given target in matrix
searchMatrix(matrix, target) {
let n = matrix.length;
let m = matrix[0].length;
// Traverse through each row
for (let i = 0; i < n; i++) {
/* Check if target is
present in the current row*/
let flag = this.binarySearch(matrix[i], target);
if (flag) return true;
}
// Return false if target is not found
return false;
}
}
let 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]];
let target = 8;
// Create an instance of Solution class
let sol = new Solution();
let result = sol.searchMatrix(matrix, target);
// Output the result
console.log(result ? "true" : "false");
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
//Function to search for a given target in matrix
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int n = matrix.size();
int m = matrix[0].size();
//Intialize the row and col
int row = 0, col = m - 1;
//Traverse the matrix from (0, m-1):
while (row < n && col >= 0) {
//Return true of target is found
if (matrix[row][col] == target) return true;
else if (matrix[row][col] < target) row++;
else col--;
}
//Return false if target not found
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 = 8;
//Create an instace of Solution class
Solution sol;
bool result = sol.searchMatrix(matrix, target);
// Output the result
result ? cout << "true\n" : cout << "false\n";
return 0;
}
import java.util.*;
class Solution {
// Function to search for a given target in matrix
public boolean searchMatrix(int[][] matrix, int target) {
int n = matrix.length;
int m = matrix[0].length;
// Initialize the row and col
int row = 0, col = m - 1;
// Traverse the matrix from (0, m-1):
while (row < n && col >= 0) {
// Return true if target is found
if (matrix[row][col] == target) return true;
else if (matrix[row][col] < target) row++;
else col--;
}
// Return false if target not found
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 = 8;
// Create an instance of Solution class
Solution sol = new Solution();
boolean result = sol.searchMatrix(matrix, target);
// Output the result
System.out.println(result ? "true" : "false");
}
}
class Solution:
# Function to search for a given target in matrix
def searchMatrix(self, matrix, target):
n = len(matrix)
m = len(matrix[0])
# Initialize the row and col
row, col = 0, m - 1
# Traverse the matrix from (0, m-1):
while row < n and col >= 0:
# Return true if target is found
if matrix[row][col] == target:
return True
elif matrix[row][col] < target:
row += 1
else:
col -= 1
# Return false if target not found
return False
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 = 8
# Create an instance of Solution class
sol = Solution()
result = sol.searchMatrix(matrix, target)
# Output the result
print("true" if result else "false")
class Solution {
// Function to search for a given target in matrix
searchMatrix(matrix, target) {
let n = matrix.length;
let m = matrix[0].length;
// Initialize the row and col
let row = 0, col = m - 1;
// Traverse the matrix from (0, m-1):
while (row < n && col >= 0) {
// Return true if target is found
if (matrix[row][col] === target) return true;
else if (matrix[row][col] < target) row++;
else col--;
}
// Return false if target not found
return false;
}
}
let 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]
];
let target = 8;
// Create an instance of Solution class
let sol = new Solution();
let result = sol.searchMatrix(matrix, target);
// Output the result
console.log(result ? "true" : "false");
Q: Why use the top-right corner for the search?
A: Starting at the top-right corner simplifies the search logic: You can directly move left or down based on comparisons. Other corners (e.g., bottom-left) also work but reverse the movement logic.
Q: Can this approach handle duplicate values in the matrix?
A: Yes, duplicates do not affect the algorithm because the search is based on comparisons with the target, not the uniqueness of values.
Q: How would you find the smallest element larger than the target?
A: Keep track of the current candidate for the smallest element larger than the target while moving through the matrix. Use a modified version of the search logic to update the candidate whenever a larger element is encountered.