sagelearnai

Search a 2D Matrix

Difficulty: Medium · Pattern: Binary Search · LeetCode #74

Each row of the m × n matrix is sorted ascending, and the first value of each row is greater than the last value of the previous row. Return whether target exists, in O(log(m·n)).

Example

text
matrix = [[1,  4,  6,  9],
          [11, 13, 17, 21],
          [25, 30, 41, 50]]
target = 17  →  true
target = 10  →  false

Hints

  1. Read row by row, the matrix is one long sorted list.
  2. Map a flat index k to (k // n, k % n).

Approach

Binary search over flat indices 0 … m·n − 1, converting mid into matrix[mid // n][mid % n]. Everything else is standard binary search. (Alternatively, binary search the rows first, then within the row; same complexity.)

Complexity

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

Python solution
def searchMatrix(matrix, target):
    m, n = len(matrix), len(matrix[0])
    lo, hi = 0, m * n - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        v = matrix[mid // n][mid % n]
        if v == target:
            return True
        if v < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return False
JavaScript solution
function searchMatrix(matrix, target) {
  const m = matrix.length, n = matrix[0].length;
  let lo = 0, hi = m * n - 1;
  while (lo <= hi) {
    const mid = (lo + hi) >> 1;
    const v = matrix[Math.floor(mid / n)][mid % n];
    if (v === target) return true;
    if (v < target) lo = mid + 1; else hi = mid - 1;
  }
  return false;
}