Day 17 - Search a 2d Matrix
Question
You are given an m x n 2-D integer array matrix and an integer target.
Each row in
matrixis sorted in non-decreasing order.The first integer of every row is greater than the last integer of the previous row.
Return true if target exists within matrix or false otherwise.
Example 1
Input: matrix = [[1,2,4,8],[10,11,12,13],[14,20,30,40]], target = 10
Output: true
Example 2
Input: matrix = [[1,2,4,8],[10,11,12,13],[14,20,30,40]], target = 15
Output: false
Approach
To solve this problem, we have two approach. Brute Force and Binary Search.
Brute Force
We will use a for loop to iterate through the matrix, applying binary search to each array to determine if the target exists. The time complexity is O(n log m), where n is the number of arrays in the matrix and m is the length of each individual array.
Algorithm
For index i from 0 to length of matrix
Create two variables left and right to store start of array and end of array.
While left <= right:
Compute the mid of array
Check if element at mid is equal to target, then return true
Else if element at mid is greater than target, then decrement right
Else increment left
After the loop, return false.
Solution (JS code)
class Solution {
/**
* @param {number[][]} matrix
* @param {number} target
* @return {boolean}
*/
searchMatrix(matrix, target) {
for (let m of matrix) {
let l = 0;
let r = m.length-1;
while (l <= r) {
let mid = Math.trunc((l+r)/2);
if (m[mid] === target) {
console.log("mid : ", m[mid])
return true
}
else if (m[mid] > target) {
r = mid - 1;
}
else {
l = mid + 1;
}
}
}
return false;
}
}
Time Complexity
O(n log m)
Space Complexity
O(1)
Binary Search
Instead of apply binary search inside the for loop, we can convert the 2d matrix in 1d array and then we can apply binary search. This way the time complexity will be O(log (m * n)) and space complexity will be O(1).
Algorithm
Store number of rows and cols in variables.
Create variables left = 0 and right = rows * cols - 1
While left <= right:
Compute mid = left + right / 2
Compute row = Math.floor(mid / cols) and col = mid % cols
Check if element at row and col is greater than target then update right = mid - 1
Else if element at row and col is less than target then update left = mid + 1
Else return true
After the loop, return false
Solution (JS code)
class Solution {
/**
* @param {number[][]} matrix
* @param {number} target
* @return {boolean}
*/
searchMatrix(matrix, target) {
let ROWS = matrix.length,
COLS = matrix[0].length;
let l = 0,
r = ROWS * COLS - 1;
while (l <= r) {
let m = l + Math.floor((r - l) / 2);
let row = Math.floor(m / COLS),
col = m % COLS;
if (target > matrix[row][col]) {
l = m + 1;
} else if (target < matrix[row][col]) {
r = m - 1;
} else {
return true;
}
}
return false;
}
}
Time Complexity
O(log (ROWS * COLS))
Space Complexity
O(1)



