Skip to main content

Search a 2D Matrix II

Problem statement

Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:

  • Integers in each row are sorted in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.

Example 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 = 5Output: true

Example 2:

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 = 20Output: false

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= n, m <= 300
  • -109 <= matrix[i][j] <= 109
  • All the integers in each row are sorted in ascending order.
  • All the integers in each column are sorted in ascending order.
  • -109 <= target <= 109

My solution

/**
* @param {number[][]} matrix
* @param {number} target
* @return {boolean}
*/
var searchMatrix = function(matrix, target) {
if (matrix.length === 0) {
return false;
}

for (let i = 0; i < matrix.length; i++) {
const row = matrix[i];

if (row.length > 0 && row[0] <= target && row[row.length - 1] >= target) {
if (search(row, target)) {
return true;
}
}
}

return false;
};

function search(arr, target) {
let left = 0;
let right = arr.length;

while (left < right) {
const mid = Math.floor((right + left) / 2);

const curr = arr[mid]

if (curr === target) {
return true
} else {
if (arr[mid] < target) {
left = mid + 1
} else {
right = mid
}
}
}

return false;
}