Spiral Matrix

Medium

Topics
ArrayMatrixSimulation

Given an m x n matrix, return all elements in spiral order (clockwise starting from the top-left).

Example 1

012314562789012
The figure shades the walk order, lighter for the first half and darker for the second: right along the top row, down the right column, back along the bottom, up the left, then repeat on the ring inside. The answer is the values in that order.
2D grid — one row per line.
Input:  matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]

Example 2

0123415678291011120123
Input:  matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

Constraints

  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

Peel the matrix like an onion: walk the top row, right column, bottom row, left column, then shrink the boundaries inward and repeat.

Approach

  1. Track four boundaries: top, bottom, left, right.
  2. Traverse top row left-to-right, right column top-to-bottom, bottom row right-to-left, left column bottom-to-top.
  3. After each edge, move the corresponding boundary inward; stop when boundaries cross.

Dry Run

matrix  1  2  3  4
        5  6  7  8
        9 10 11 12
Four shrinking bounds, one layer per outer iteration.
  pass 1  top row     1 2 3 4       top    -> 1
          right col   8 12          right  -> 2
          bottom row  11 10 9       bottom -> 1
          left col    5             left   -> 1
  pass 2  top row     6 7           top    -> 2
          right col   (empty)       right  -> 1
          bottom row  SKIPPED, top 2 is now past bottom 1
          left col    (empty)       left   -> 2
  loop exits: top 2 > bottom 1
answer 1 2 3 4 8 12 11 10 9 5 6 7
The two mid-loop re-checks are what the pitfall is about, and pass 2 shows one
firing. By the time the bottom row would be read, `top` has already advanced past
`bottom` -- the middle row was consumed as a top row, and reading it again as a
bottom row would emit it twice.
It is easiest to see on a degenerate shape. Without the re-checks, the single row
[[1,2,3]] comes back as 1 2 3 2 1, and the single column [[1],[2],[3]] as
1 2 3 2 -- the leftover line gets walked back the other way.
Nothing is marked visited and no extra space is used. The bounds alone encode
which cells remain, which is why each of the four inner loops must also update
its own bound immediately after running.

Complexity

  • Time — O(m*n): each element is appended exactly once.
  • Space — O(1): aside from the output, only boundary counters.

Common Pitfalls

  • Re-check top <= bottom and left <= right before the bottom row and left column to avoid double-visiting on non-square matrices.

Full Solution — all languages

class Solution:
    def spiralOrder(self, matrix):
        res=[]
        top,bottom=0,len(matrix)-1
        left,right=0,len(matrix[0])-1
        while top<=bottom and left<=right:
            for c in range(left,right+1): res.append(matrix[top][c])
            top+=1
            for r in range(top,bottom+1): res.append(matrix[r][right])
            right-=1
            if top<=bottom:
                for c in range(right,left-1,-1): res.append(matrix[bottom][c])
                bottom-=1
            if left<=right:
                for r in range(bottom,top-1,-1): res.append(matrix[r][left])
                left+=1
        return res
SensAI
Beta
Tap the mic to stop voice mode