Skip to content

visual walkthrough

Search a 2D Matrix II

MediumStaircase SearchReported at: AmazonMicrosoftMeta+3

Start at a corner and eliminate a row or column per step.

Solve on LeetCode

The idea

Rows and columns are sorted, but the matrix isn't one sorted list, so plain binary search doesn't apply.

The top-right corner is special: it's the largest in its row and the smallest in its column. Comparing it with the target always rules out a whole row or column.

Complexity

approachtimespace
Check every cellO(R · C)O(1)
Staircase from the top-rightO(R + C)O(1)

More walkthroughs