Binary search on 2D matrices
A sorted matrix can be searched three ways. If the rows chain into one sorted list, treat it as a 1D array. If only rows and columns are sorted, walk a staircase from a corner. And to find the k-th value or the median, binary search on the value itself and count how many cells are at most it.
How to recognise it
- The input is a matrix whose rows (and maybe columns) are sorted.
- The question asks whether a value is present, which row has the most of something, the k-th smallest or the median.
- O(rows × cols) is too slow, or the question asks for something like O(log(rows × cols)) or O(rows + cols).
The idea in one picture
Picture a sorted matrix as a map where values rise as you go right, and often also as you go down. Each kind of question uses that rise differently: as one long sorted line, as a staircase, or as a count.
Three tools
| Matrix shape | Tool | Problem here |
|---|---|---|
| Rows chain into one sorted list | Binary search over positions 0..R·C - 1, cell (p / C, p mod C) | Search a 2D Matrix |
| Rows sorted, columns sorted | Staircase from the top-right corner, O(R + C) | Search a 2D Matrix II |
| Each row sorted on its own | Lower bound in every row | Find row with maximum 1's |
| Rows (and maybe columns) sorted, need a rank | Binary search on the value and count cells at most it | Median, k-th smallest |
| No order at all | Binary search over columns, climbing to a bigger neighbour | Find a Peak Element II |
Template: binary search on the value with a count
lo = smallest value, hi = largest value
while lo < hi:
mid = lo + (hi - lo) / 2
if countAtMost(mid) >= k: hi = mid
else: lo = mid + 1
return lo
The answer is always a value in the matrix: it is the smallest value with at least k cells at most it, and the count
only changes at values that appear.
The staircase count
When rows and columns are both sorted, start at the bottom-left. If the cell is at most x, the whole column above it
is too: add row + 1 and move right. Otherwise move up. That counts in O(R + C).
Common mistakes
- Starting the staircase at the top-left or bottom-right, where both moves go the same way.
- Mixing up
p / Candp mod Cin the 1D view. - Searching indexes when the question asks about values, as for the median.
- Expecting the 1D trick to work when only rows and columns are sorted, not chained.
Problems
- Find row with maximum 1'smediumguide ready
- Search a 2D Matrixmediumguide ready
- Search a 2D Matrix IImediumguide ready
- Find a Peak Element IImediumguide ready
- Median of a Row Wise Sorted Matrixmediumguide ready
- Kth smallest element in a row-cpumn wise sorted matrixmediumguide ready