Learn / Binary search

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 shapeToolProblem here
Rows chain into one sorted listBinary search over positions 0..R·C - 1, cell (p / C, p mod C)Search a 2D Matrix
Rows sorted, columns sortedStaircase from the top-right corner, O(R + C)Search a 2D Matrix II
Each row sorted on its ownLower bound in every rowFind row with maximum 1's
Rows (and maybe columns) sorted, need a rankBinary search on the value and count cells at most itMedian, k-th smallest
No order at allBinary search over columns, climbing to a bigger neighbourFind 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 / C and p mod C in 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

0 of 6 solved

Check yourself

In a matrix whose rows chain into one sorted list, with cols columns, which cell is position p of that list?

Why start the staircase search at the top-right corner?

To find the median of a matrix with sorted rows, the search is over...

In Find a Peak Element II, the biggest value of the middle column is smaller than its right neighbour. Which columns can be dropped?