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.
- 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⁹
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.
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.
Approach
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.
Two ways to search the grid
Walk from the top-right corner, dropping a row or a column with each comparison.
- Uses both sort orders: rows and columns.
- Few steps on square grids: at most 599 on a 300 × 300 grid.
The usual interview answer.
Binary search each row on its own and ignore the column order.
- Quick to write: one library call per row.
- Slower on square grids: about 2,500 steps on 300 × 300, but better when there are only a few very long rows.
Both use constant extra space. The staircase walk is the one traced below; the row-by-row version follows the demo.
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.
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.
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.
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.
Code in Python, C++ and Java
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).
Common pitfalls
Starting at the top-left corner
row, col = 0, 0
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
value = matrix[mid // n][mid % n]
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.
Complexity
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.