SDE & MLE Prep

240. Search a 2D Matrix II

Problem

In the m×n matrix, every row is sorted left to right and every column is sorted top to bottom. Decide whether target is in it.

Example: [[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 = 5 → true, target = 20 → false

Constraints: up to 300 × 300.

Rows and columns sorted (but rows don't continue each other). Start at the top-right: if bigger than target move left (the whole column below is bigger too), if smaller move down.

 1  4  7 [11] 15      target 5: 11 > 5 <-, 7 > 5 <-, 4 < 5 v, 5 found
 2  5  8  12  19
 3  6  9  16  22

Complexity: O(m + n).

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        r, c = 0, len(matrix[0]) - 1
        while r < len(matrix) and c >= 0:
            v = matrix[r][c]
            if v == target:
                return True
            if v > target:
                c -= 1
            else:
                r += 1
        return False