Search a 2D Matrix II

Medium

Topics
ArrayBinary SearchDivide and ConquerMatrix

matrix has every row sorted ascending left to right, and every column sorted ascending top to bottom. Return true if target is present.

Note what is not guaranteed: the rows are not a single sorted sequence end to end. A row can start below the previous row’s last value.

Example 1

14711258123691610131417
the target
Searching this matrix for 5 gives true, at the shaded cell. Every row increases left to right and every column increases top to bottom, which is less than it sounds: the rows do not run on from each other — row 1 starts below where the row above it ended — so the cells read in order are not a sorted sequence.
Only presence is returned, not a position.
Input:  matrix = [[1,4,7,11],[2,5,8,12],[3,6,9,16],[10,13,14,17]], target = 5
Output: true
Explanation: 5 sits at row 1, column 1.

Example 2

14711258123691610131417
Searching this matrix for 15 gives false, because no cell holds it.
Input:  matrix = [[1,4,7,11],[2,5,8,12],[3,6,9,16],[10,13,14,17]], target = 15
Output: false
Explanation: 15 is between 14 and 16 but appears nowhere.

Example 3

-5
the target
Every row increases left to right and every column increases top to bottom, which is less than it sounds: on this particular matrix the rows also happen to run on from each other, but that is not promised and cannot be relied on.
Input:  matrix = [[-5]], target = -5
Output: true
Explanation: A single cell, which is both the smallest and largest value.

Constraints

  • 1 <= matrix.length, matrix[0].length <= 300
  • -10^9 <= matrix[i][j] <= 10^9
  • Each row is sorted ascending
  • Each column is sorted ascending
  • -10^9 <= target <= 10^9
Editorial — intuition, approach, complexity and pitfalls

Intuition

Flattening the matrix and searching it as one sorted array is the tempting move and it is wrong here. The rows are individually sorted but not continuous with each other — row 2 starts at 3 while row 1 ends at 12 — so the flattened sequence is not sorted and a halving search on it is meaningless. This is the difference between this problem and Search a 2D Matrix.

What the two sortings do give is a corner where the comparison is decisive. Stand at the top-right cell. Everything to its left in that row is smaller; everything below it in that column is larger. So one comparison always eliminates an entire row or an entire column:

If the cell is larger than the target, the target cannot be anywhere in that column — every cell below is even larger — so step left. If the cell is smaller, the target cannot be anywhere in that row — every cell to the left is even smaller — so step down.

Each step retires one row or one column for good, so the walk visits at most rows + columns cells. The bottom-left corner works identically with the directions swapped; the top-left and bottom-right corners do not work, because there both neighbours move the same way and no comparison eliminates anything.

Approach

  1. Start at row 0, column cols - 1, the top-right cell.
  2. While the position is inside the matrix, compare the cell with the target.
  3. Equal: return true.
  4. Cell greater than the target: decrement the column, discarding that column.
  5. Cell less than the target: increment the row, discarding that row.
  6. Falling off the edge means the target is absent, so return false.

Walkthrough

matrix = [[1, 4, 7,11],
          [2, 5, 8,12],
          [3, 6, 9,16],
          [10,13,14,17]]
target = 5

start top-right at (0,3) = 11
   11 > 5  -> column 3 is out, step left
(0,2) = 7
   7 > 5   -> column 2 is out, step left
(0,1) = 4
   4 < 5   -> row 0 is out, step down
(1,1) = 5
   found, true

target = 15
(0,3)=11 < 15 -> down
(1,3)=12 < 15 -> down
(2,3)=16 > 15 -> left
(2,2)=9  < 15 -> down
(3,2)=14 < 15 -> down
   row 4 does not exist, so false

why not the top-left corner
   at (0,0) = 1 with target 5, both right and down lead
   to larger values, so a "greater than" result tells you
   nothing about which way to go.

Complexity

  • Time — O(rows + cols): every step removes one row or one column permanently.
  • Space — O(1): two indices.

Common Pitfalls

  • Flattening and running a halving search. That needs the rows to be continuous, which this problem does not promise.
  • Starting at the top-left or bottom-right corner, where a comparison does not eliminate anything.
  • Running a halving search per row. It is correct, and slower than the corner walk at log per row.
  • Writing the loop bound as c > 0, which never examines column 0.
  • Moving both indices on one comparison. Exactly one moves.

Full Solution — all languages

class Solution:
    def searchMatrix(self, matrix, target):
        rows, cols = len(matrix), len(matrix[0])

        # Top-right: left is strictly smaller, below is strictly larger, so one
        # comparison always retires a whole row or a whole column.
        r, c = 0, cols - 1

        while r < rows and c >= 0:
            value = matrix[r][c]
            if value == target:
                return True
            if value > target:
                c -= 1      # nothing in this column can be the target
            else:
                r += 1      # nothing in this row can be the target

        return False
SensAI
Beta
Tap the mic to stop voice mode