TRT
Sign in
mediumCoreLeetCode#staircase search

Search a 2D matrix II

Search a matrix whose rows and columns are sorted independently, in O(m + n), with a staircase walk from the top-right corner.

The Runtime Theory Team1 min read
Taught inRotated and two-dimensional dataPro — members onlyBinary search still works when sorted data has been rotated, because one half of any range is always sorted. Sorted grids can be searched as one long array, or with a staircase walk from a corner.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inmatrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5

outtrue

insame matrix, target = 20

outfalse

inmatrix = [[-5]], target = -5

outtrue

In an m × n matrix, every row is sorted left to right and every column top to bottom. Return whether the target is present.

Before you code

The rows don't continue each other, so the matrix is not one sorted sequence and flat binary search is wrong. Find a starting cell from which every comparison rules out a whole row or column.

Hints

  1. Start at the top-right corner: the largest value in its row and the smallest in its column.
  2. If the target is smaller, the whole current column is too big: move left. If larger, the whole row is too small: move down.
  3. Stop when found or when you leave the matrix. At most m + n steps.

Production & complexity notes

When solving Search a 2D matrix II on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Rotated and two-dimensional data to reinforce the underlying pattern.

What it practices

Ruling out regions with each comparison, from Rotated and two-dimensional data.

Not started

Sign in to save your learning progress.

Sign in to save