Search a 2D Matrix

Difficulty: Medium

You're given a grid of numbers where:

  • Every row is sorted left to right.
  • The first number in each row is bigger than the last number in the row above.

So reading the grid row by row gives one sorted sequence. The grid is really a single sorted list split into rows.

Given the grid and a target, decide whether the target appears in it.

Examples

Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true

3 appears in the first row.

Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: false

13 falls between 11 and 16 in the second row, so it doesn't appear anywhere in the grid.

Input: matrix = [[1]], target = 1
Output: true

A 1x1 grid whose only value is the target.

Constraints

  • m == matrix.length

  • n == matrix[i].length

  • 1 <= m, n <= 100

  • -10^4 <= matrix[i][j], target <= 10^4

Approach

You could check every cell, or find the right row first and then search it. Both work, but miss the bigger picture: read row by row, the grid is one sorted sequence of m * n numbers.

The faster way treats the grid as one flattened sorted array, without building it. Index i from 0 to m * n - 1 maps to row Math.floor(i / n) and column i % n. Binary search over [0, m*n - 1] like a normal sorted array, converting each index to a row and column as you go.

Solutions

Brute Force — Scan Every Cell

Check every cell until the target turns up. Simple, but ignores that the rows are sorted and chained together.

function searchMatrix(matrix, target) {
  for (let r = 0; r < matrix.length; r++) {
    for (let c = 0; c < matrix[r].length; c++) {
      if (matrix[r][c] === target) return true;
    }
  }
  return false;
}

Time: O(m * n) · Space: O(1)

Optimal — Binary Search Over a Flattened Index

Binary search over [0, m*n - 1] as if the grid were one sorted array, converting each index to a row and column to read its value.

function searchMatrix(matrix, target) {
  const m = matrix.length;
  const n = matrix[0].length;
  let left = 0;
  let right = m * n - 1;

  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    const value = matrix[Math.floor(mid / n)][mid % n];

    if (value === target) {
      return true;
    } else if (value < target) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }

  return false;
}

Time: O(log(m * n)) · Space: O(1)