#54

Spiral Matrix

Medium Shrinking boundaries

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

?The problem

Return all elements of an m × n matrix in clockwise spiral order.

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

◎Understanding

Really asking: read the matrix around the edges, inward.

Why this works: four walls (top, bottom, left, right) shrink after each side is read.

Example: [[1,2,3],[4,5,6],[7,8,9]]

top row 1 2 3, right col 6 9bottom row 8 7, left col 4middle 5 → [1,2,3,6,9,8,7,4,5]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Not re-checking boundaries before the bottom row and left column, which prints the middle row or column twice.

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