Browse Curriculum
FAANGPrep Sprint
Medium

Spiral Matrix

Return all elements of the matrix in spiral order.
10 min read
Time: O(n)
Space: O(1)
Solve on LeetCode

Problem Understanding

Given an m x n matrix, return all elements of the matrix in spiral order (Right -> Down -> Left -> Up).

Interactive Visualization

Step 1 / 1

Visualization data missing

Initializing...

1x

Watch the path as we peel the matrix layer by layer.

Strategy

We can simulate the spiral movement by defining boundaries (top, bottom, left, right):

  1. Move Right: Traverse from left to right. Increment top.
  2. Move Down: Traverse from top to bottom. Decrement right.
  3. Move Left: Traverse from right to left. Decrement bottom. (Check top <= bottom first)
  4. Move Up: Traverse from bottom to top. Increment left. (Check left <= right first)
  • Initialize top=0, bottom=rows-1, left=0, right=cols-1.

  • Loop while top <= bottom and left <= right.

Dry Run

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

Step Action Output After Step Boundaries Update
1 Right [1, 2, 3] top becomes 1
2 Down [..., 6, 9] right becomes 1
3 Left [..., 8, 7] bottom becomes 1
4 Up [..., 4] left becomes 1
5 Right [..., 5] top becomes 2. Loop Ends.

Edge Cases & Common Mistakes

Watch out for:

  • Single Row/Column: Ensure the inner loops (left check, top check) prevent double-counting.

  • Empty Matrix: Handle gracefully.

  • Non-Square Matrix: Logic must hold for m != n.

Complexity Analysis

  • Time Complexity: O(M * N). Visit every element once.
  • Space Complexity: O(1). Output array doesn't count towards space.

Solution

Simulation with boundaries.

1class Solution:
2 def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
3 result = []
4 if not matrix: return result
5
6 top, bottom = 0, len(matrix) - 1
7 left, right = 0, len(matrix[0]) - 1
8
9 while top <= bottom and left <= right:
10 # Move Right
11 for i in range(left, right + 1):
12 result.append(matrix[top][i])
13 top += 1
14
15 # Move Down
16 for i in range(top, bottom + 1):
17 result.append(matrix[i][right])
18 right -= 1
19
20 if top <= bottom:
21 # Move Left
22 for i in range(right, left - 1, -1):
23 result.append(matrix[bottom][i])
24 bottom -= 1
25
26 if left <= right:
27 # Move Up
28 for i in range(bottom, top - 1, -1):
29 result.append(matrix[i][left])
30 left += 1
31
32 return result