Skip to content
Problem 54 · LeetCode 54(opens in a new tab)

Spiral Matrix

MediumArrays

You are given a grid of numbers, matrix, with m rows and n columns. Read every number exactly once in a spiral: go right along the top row, down the right edge, left along the bottom row and up the left edge, then repeat on the smaller ring inside.

Return the numbers in the order you read them.

Example 1

Input:  matrix = [[5, 1, 8],
                  [2, 7, 4]]
Output: [5, 1, 8, 4, 7, 2]
Why:    across the top, down to 4, back along the bottom
2 more examples and the constraints

Example 2

Input:  matrix = [[7], [8], [9]]
Output: [7, 8, 9]
Why:    a single column is read straight down

Example 3

Input:  matrix = [[2, 4, 6],
                  [8, 10, 12],
                  [14, 16, 18]]
Output: [2, 4, 6, 12, 18, 16, 14, 8, 10]
Why:    the outer ring first, then the centre

Constraints

  • 1 ≤ m, n ≤ 10
  • −100 ≤ matrix[r][c] ≤ 100

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Walk and turnO(m·n)
  2. Shrinking boundariesO(m·n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 10 × 10 gridVerdict
Walk and turnO(m·n), O(m·n) space
Passes; needs a seen grid
Shrinking boundariesO(m·n), O(1) space
Best; no extra memory

m = rows, n = columns.

Edge cases to test

  • One cell. [[5]] gives [5].
  • One row. [[1, 2, 3, 4]] is read once, left to right, and never back.
  • One column. [[7], [8], [9]] is read straight down.
  • Taller than wide. A 5 × 3 grid ends with a short vertical strip in the middle: 5, 8, 11.

Common mistakes

  • Leaving out the top ≤ bottom or left ≤ right check, so a single row or column is read twice.
  • Moving a boundary before reading its side, which skips a corner.
  • Writing the loop bounds off by one on the reverse sides: the bottom row runs from right down to left, inclusive.

How to talk through it

  1. 1Clarify. Clockwise from the top-left? Can the grid be a single row or column? Can it be empty?
  2. 2Describe the walk. Right, down, left, up, turning at walls or read cells. Say it needs a seen grid.
  3. 3Replace the seen grid. Four boundaries fence the unread part; each side read moves one of them inward.
  4. 4Code the boundaries. Top row, right column, then the two guarded sides.
  5. 5Test out loud. Run one row, one column and a 5 × 3 grid before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?