Ecommet

Search a 2D Matrix

Medium Problem 41 of 151 Java and Python

Problem

You are given an m × n integer matrix where each row is sorted ascending and the first number of each row is greater than the last number of the previous row.

Given target, return true if it is in the matrix. The solution must run in O(log(m · n)) time.

Example 1

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

Example 2

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

Constraints

  • 1 ≤ m, n ≤ 100
  • -10⁴ ≤ matrix[i][j], target ≤ 10⁴

Explanation

Read the rows one after another and you get a single sorted list of m · n numbers. Position k in that list is cell (k / n, k % n).

So run an ordinary binary search over 0 … m·n - 1 and convert each middle index to a cell.

Approach 1 · Better

Find the row, then search it

  • Time O(m + log n)
  • Space O(1)

Walk down the rows to find the one whose range contains the target, then binary-search that row.

  1. Find the row r with matrix[r][0] <= target <= matrix[r][n - 1].
  2. Binary-search row r.
Java
import java.util.*;

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        for (int[] row : matrix) {
            if (row[0] <= target && target <= row[row.length - 1]) {
                return Arrays.binarySearch(row, target) >= 0;
            }
        }
        return false;
    }
}
Python
from bisect import bisect_left

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        for row in matrix:
            if row[0] <= target <= row[-1]:
                i = bisect_left(row, target)
                return row[i] == target
        return False

Approach 2 · Optimal

One binary search over all cells

  • Time O(log(m · n))
  • Space O(1)

Binary-search the virtual index 0 … m·n - 1, mapping index k to matrix[k / n][k % n].

  1. Set lo = 0, hi = m * n - 1.
  2. mid → value matrix[mid / n][mid % n]; compare with target as usual.
Java
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int n = matrix[0].length;
        int lo = 0;
        int hi = matrix.length * n - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            int value = matrix[mid / n][mid % n];
            if (value == target) {
                return true;
            } else if (value < target) {
                lo = mid + 1;
            } else {
                hi = mid - 1;
            }
        }
        return false;
    }
}
Python
class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        n = len(matrix[0])
        lo, hi = 0, len(matrix) * n - 1
        while lo <= hi:
            mid = (lo + hi) // 2
            value = matrix[mid // n][mid % n]
            if value == target:
                return True
            if value < target:
                lo = mid + 1
            else:
                hi = mid - 1
        return False

Complexity compared

ApproachTimeSpace
Better Find the row, then search itO(m + log n)O(1)
Optimal One binary search over all cellsO(log(m · n))O(1)

Key takeaways

  • Index ↔ cell: k → (k / n, k % n) and (r, c) → r · n + c.
  • If only rows and columns are sorted separately (Search a 2D Matrix II), start at the top-right corner instead.

Your notes

Saved in this browser as you type.

Solved it on your own?

Mark it done to track your progress, or star it to come back before an interview.

Next problem