Search a 2D Matrix II

Pattern: Binary search on 2D matrices

medium

Rows and columns are sorted, but rows do not chain. Start at the top-right corner. A value too big rules out its column, and a value too small rules out its row, so walk left or down until you find the target or leave the matrix.

The problem

You are given a matrix where every row is sorted left to right and every column is sorted top to bottom. Return whether a target value is in the matrix. For example, the 5 × 5 matrix in the dry run gives true for 5 and false for 20.

The function name searchMatrix matches LeetCode. Use the link above for the exact statement and limits. Unlike Search a 2D Matrix, a row may start below the previous row's end.

Think first

  • From the top-left corner, both moves (right and down) make values bigger. Why is that a problem?
  • Which corner has one move that makes values smaller and one that makes them bigger?
  • Each comparison from that corner can rule out what?

Hints

    Brute force, and why it fails

    Check every cell: O(R × C). Binary search in every row: O(R log C). The staircase walk takes at most R + C steps.

    The key insight

    From the top-right corner, each comparison throws away a whole row or a whole column. That is not halving, but it is a search that never looks back, in O(R + C).

    Dry run

    1 4 7 11 150r
    2 5 8 12 191 
    3 6 9 16 222 
    10 13 14 17 243 
    18 21 23 26 304 
    c4
    value15

    The rows are 1 4 7 11 15, 2 5 8 12 19, 3 6 9 16 22, 10 13 14 17 24 and 18 21 23 26 30, and the target is 5. Start at the top-right, 15.

    Step 1 of 4

    The plan

    r = 0, c = C - 1
    while r < R and c >= 0:
        if matrix[r][c] == target: return true
        if matrix[r][c] > target: c = c - 1
        else: r = r + 1
    return false
    

    Complexity

    Time
    O(R + C)
    Space
    O(1)

    Each step moves one row down or one column left.

    Edge cases

    • One cell: compare directly.
    • Target smaller than the top-left value or bigger than the bottom-right: false.
    • Repeated values: the walk still stops at a match.
    I've built my logic, show the code

    Java

    class Solution {
        public boolean searchMatrix(int[][] matrix, int target) {
            int r = 0, c = matrix[0].length - 1;    // start at the top-right corner
            while (r < matrix.length && c >= 0) {
                int v = matrix[r][c];
                if (v == target) return true;
                if (v > target) c--;                // everything below in this column is even bigger
                else r++;                           // everything left in this row is even smaller
            }
            return false;
        }
    }

    C++

    class Solution {
    public:
        bool searchMatrix(vector<vector<int>>& matrix, int target) {
            int r = 0, c = static_cast<int>(matrix[0].size()) - 1;   // start at the top-right corner
            while (r < static_cast<int>(matrix.size()) && c >= 0) {
                int v = matrix[r][c];
                if (v == target) return true;
                if (v > target) c--;                // everything below in this column is even bigger
                else r++;                           // everything left in this row is even smaller
            }
            return false;
        }
    };

    Python

    class Solution:
        def searchMatrix(self, matrix: list[list[int]], target: int) -> bool:
            r, c = 0, len(matrix[0]) - 1            # start at the top-right corner
            while r < len(matrix) and c >= 0:
                v = matrix[r][c]
                if v == target:
                    return True
                if v > target:
                    c -= 1                          # everything below in this column is even bigger
                else:
                    r += 1                          # everything left in this row is even smaller
            return False

    Common mistakes

    • Starting at the top-left, where a comparison cannot pick a direction.
    • Moving down when the value is too big.
    • Using the flattened 1D search, which assumes the rows chain.

    Similar problems