SDE & MLE Prep

74. Search a 2D Matrix

Problem

In the m×n matrix, each row is sorted ascending and each row's first value is greater than the previous row's last value. Decide whether target is in the matrix, in O(log(m·n)).

Example: [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 → true

Rows are sorted and each row starts after the previous ends → it's one sorted array of length m·n. Index k ↦ (k // n, k % n).

Complexity: O(log(m·n)).

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        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