LeetCode #240 Medium

Search a 2D Matrix II

Search a 2D Matrix II is LeetCode 240 (Medium). An m x n grid has every row sorted left to right and every column sorted top to bottom, both ascending. Return true if target appears anywhere in it.

  • Unlike Search a 2D Matrix, a row may start below where the row above ended, so reading the rows in order does not give one sorted list.
  • The grid can be 300 × 300. Checking all 90,000 cells works, but it ignores both sort orders.
Constraints
  • m == matrix.length
  • n == matrix[i].length
  • 1 <= n, m <= 300
  • -10⁹ <= matrix[i][j] <= 10⁹
  • All the integers in each row are sorted in ascending order.
  • All the integers in each column are sorted in ascending order.
  • -10⁹ <= target <= 10⁹
arraymatrixbinary-searchdivide-and-conquer
Open on LeetCode ↗
02

Intuition

Stand on the top-right cell. Everything to its left in that row is smaller, and everything below it in that column is larger. So one comparison with target always clears a whole line:

  • Cell bigger than the target: the cells below it are bigger still, so its column cannot match. Step left.
  • Cell smaller than the target: the cells to its left are smaller still, so its row cannot match. Step down.

Every step removes a row or a column, so the walk ends after at most m + n steps, on the target or off the edge of the grid.

How to spot this pattern

A grid sorted along both rows and columns, but not as one run: start at a corner where one direction rises and the other falls, and let each comparison remove a row or a column.

03

Approach

Try it first

Before reading on, put your finger on each of the four corners of a small grid. From which corner does a single comparison always tell you which way to move? Aim for O(m + n) time and O(1) space.

1

Start in the top-right corner

Set row = 0 and col = n - 1. From this cell the row falls to the left and the column rises downward, so a comparison always points one way. The bottom-left corner works too, mirrored.

2

Cell too big: move left

If matrix[row][col] > target, every cell from here down the column is at least this big, and the rows above are already ruled out. Nothing left in the column can match, so col -= 1.

3

Cell too small: move down

If matrix[row][col] < target, every remaining cell in this row is to the left and no bigger. Nothing left in the row can match, so row += 1.

4

Stop on a match or at the edge

Return true when the cell equals target. When row reaches m or col falls below 0, all rows or all columns have been ruled out, so return false.

04

Code in Python, C++ and Java

▶1from typing import List
▶2 
▶3 
▶4class Solution:
▶5 def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
▶6 row, col = 0, len(matrix[0]) - 1
▶7 while row < len(matrix) and col >= 0:
▶8 value = matrix[row][col]
▶9 if value == target:
▶10 return True
▶11 if value > target:
▶12 col -= 1
▶13 else:
▶14 row += 1
▶15 return False
14711152581219369162210131417241821232630start at the top-right corner, 15
row0
col4
target5
From the top-right cell, values fall to the left along the row and rise downward along the column. That is why one comparison with 5 always says which way to go.
1471115258121936916221013141724182123263015 is bigger than 5 → drop its column, step left
cell15
col3
15 is bigger than 5. The cells below it in column 4 are bigger still, and the cells above were already ruled out, so the whole column is gone.
1471115258121936916221013141724182123263011 is bigger than 5 → drop its column, step left
cell11
col2
11 is bigger than 5. The cells below it in column 3 are bigger still, and the cells above were already ruled out, so the whole column is gone.
147111525812193691622101314172418212326307 is bigger than 5 → drop its column, step left
cell7
col1
7 is bigger than 5. The cells below it in column 2 are bigger still, and the cells above were already ruled out, so the whole column is gone.
147111525812193691622101314172418212326304 is smaller than 5 → drop its row, step down
cell4
row1
4 is smaller than 5. The cells left of it in row 0 are smaller still, so the whole row is gone.
14711152581219369162210131417241821232630row 1, column 1 holds 5 → found it
row1
col1
answertrue
The cell equals the target, so return true. The walk read 5 of the 25 cells; every other cell was ruled out a whole row or column at a time.
05

Binary search in every row

Each row is sorted on its own, so binary search it for target and stop at the first hit. The column order is never used, which is why this costs O(m log n) rather than O(m + n).

▶1from bisect import bisect_left
▶2from typing import List
▶3 
▶4 
▶5class Solution:
▶6 def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
▶7 for row in matrix:
▶8 i = bisect_left(row, target)
▶9 if i < len(row) and row[i] == target:
▶10 return True
▶11 return False
06

Common pitfalls

Starting at the top-left corner

✗ Wrong
row, col = 0, 0
✓ Right
row, col = 0, len(matrix[0]) - 1

From the top-left, the cell to the right and the cell below are both bigger, so a cell smaller than target does not say which way to go. In [[1, 4], [2, 5]] with target 2, a walk that steps right from the 1 lands on 4 and has passed the 2 for good.

Binary searching the cells in reading order

✗ Wrong
value = matrix[mid // n][mid % n]
✓ Right
walk from the top-right corner

Reading [[1, 4], [2, 5]] row by row gives 1, 4, 2, 5, which is not sorted. A search for 2 reads the 4 and goes left, reads the 1 and goes right, then stops with the range empty and answers false.

07

Complexity

Time
O(m + n)
Space
O(1)
Each comparison removes one of the m rows or one of the n columns, so there are at most m + n − 1 of them: 599 on a 300 × 300 grid.
08

Search a 2D Matrix II FAQ

Why can't a cleverer search get this down to O(log(m · n))?

Look at the diagonal from the top-right corner to the bottom-left. Those cells are never compared by the sort rules, so any one of them can be raised or lowered without breaking the grid. A search that skips one of them cannot know whether it is the target. On an n × n grid that is n cells that must be read, so O(m + n) is the best possible for square grids.

Can the same walk count how many values are at most x?

Yes, from the bottom-left corner. When the cell is at most x, it and every cell above it in that column count, so add row + 1 and step right; otherwise step up. That count is the core of Kth Smallest Element in a Sorted Matrix.