#240

Search a 2D Matrix II

Medium Staircase search

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Rows are sorted left to right and columns top to bottom (but rows don't continue each other). Decide if target is present.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: rows and columns are each sorted; is the target there?

Why this works: start top-right. Going left decreases, going down increases, so each step throws away a whole row or column.

Example: target 5, top-right 15

15 > 5 → left 11 → left 7 → left 44 < 5 → down 5 ✓

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Starting at the top-left, where both directions increase and you can't decide where to go.

Solve on LeetCode ↗
Complexity
  • Time: O(m + n).
  • Space: O(1).
Topic: 2D Arrays & Matrix
🎬 Episode 14: video coming soon