54. Spiral Matrix - Detailed Explanation
Problem Statement
Description:
You are given an m x n matrix containing integers. Your task is to return all the elements of the matrix in spiral order. The traversal starts at the top-left corner and proceeds in a spiral (clockwise) path until every element is visited.
Key Details:
- You must traverse the matrix in a spiral pattern (right → down → left → up, then repeat).
- The matrix can be rectangular (not necessarily a square).
Example Inputs, Outputs, and Explanations
- 
Example 1: - Input:
[ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
- Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
- Explanation:
- Start with the first row: 1, 2, 3
- Then the last column (excluding the first element already visited): 6, 9
- Then the last row in reverse: 8, 7
- Then the first column upward: 4
- Finally, the middle element: 5
 
- Start with the first row: 
 
- Input:
- 
Example 2: - Input:
[ [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]
- Explanation:
- Traverse the top row: 1, 2, 3, 4
- Then the right column: 8, 12
- Then the bottom row in reverse: 11, 10, 9
- Then the left column upward: 5
- Finally, the remaining inner row: 6, 7
 
- Traverse the top row: 
 
- Input:
- 
Example 3 (Edge Case): - Input: [](an empty matrix)
- Output: []
- Explanation:
- An empty matrix returns an empty list.
 
 
- Input: 
Constraints
- The matrix dimensions m(number of rows) andn(number of columns) can vary.
- It is possible that m != n, meaning the matrix can be rectangular.
- The matrix can be empty.
Hints to Approach the Solution
- 
Boundary Variables: - Think of maintaining four boundaries: top,bottom,left, andright. These boundaries represent the current limits of the rows and columns that still need to be traversed.
 
- Think of maintaining four boundaries: 
- 
Layer-by-Layer Traversal: - Process the matrix layer by layer (or ring by ring). For each layer, traverse:
- From the left to the right on the top row.
- From the top to the bottom on the right column.
- From the right to the left on the bottom row (if the top and bottom rows are not the same).
- From the bottom to the top on the left column (if the left and right columns are not the same).
 
 
- Process the matrix layer by layer (or ring by ring). For each layer, traverse:
- 
Update Boundaries: - After processing one complete spiral layer, update the boundaries to move inward.
 
Approach 1: Simulation with Boundary Pointers
Explanation
- Idea:
- Use four pointers (top,bottom,left, andright) to keep track of the boundaries.
- While the pointers do not cross each other, traverse the outer layer in the order:
- Left to right (top row).
- Top to bottom (right column).
- Right to left (bottom row), if applicable.
- Bottom to top (left column), if applicable.
 
- After each complete traversal, adjust the boundaries inward and repeat.
 
- Use four pointers (
Pseudocode
result = []
top = 0, bottom = m - 1, left = 0, right = n - 1
while (top <= bottom and left <= right):
    # Traverse from left to right.
    for j from left to right:
        result.add(matrix[top][j])
    top += 1
    # Traverse from top to bottom.
    for i from top to bottom:
        result.add(matrix[i][right])
    right -= 1
    # Traverse from right to left if top <= bottom.
    if top <= bottom:
        for j from right to left:
            result.add(matrix[bottom][j])
        bottom -= 1
    # Traverse from bottom to top if left <= right.
    if left <= right:
        for i from bottom to top:
            result.add(matrix[i][left])
        left += 1
return result
Approach 2: Direction Array Simulation
Explanation
- Idea:
- Use a direction vector (e.g., right, down, left, up) and a visited marker or boundaries to determine the next position.
- This method simulates the movement until all elements are visited.
- It is slightly more general, but for this problem the boundary approach is usually simpler.
 
Why the Boundary Approach is Often Preferred
- The boundary approach explicitly manages the layer-by-layer traversal and naturally handles the cases where the matrix is not a perfect square.
- It avoids extra space for visited flags since the boundaries implicitly track what has been visited.
Code Implementations
Python Code
Python3
Python3
. . . .
Java Code
Java
Java
. . . .
Complexity Analysis
- 
Time Complexity: - O(m * n) where mis the number of rows andnis the number of columns.
- Each element is visited exactly once.
 
- O(m * n) where 
- 
Space Complexity: - O(1) extra space (excluding the output list).
- The output list itself requires O(m * n) space to store the elements.
 
Step-by-Step Walkthrough (Visual Example)
Consider the matrix:
[
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]
- 
Initialization: - top = 0,- bottom = 2,- left = 0,- right = 2.
 
- 
First Layer (Outer Ring): - Traverse top row: Append [1, 2, 3]→ updatetopto 1.
- Traverse right column: Append [6, 9]→ updaterightto 1.
- Traverse bottom row: Append [8, 7](reverse order) → updatebottomto 1.
- Traverse left column: Append [4](upwards) → updateleftto 1.
 
- Traverse top row: Append 
- 
Second Layer (Inner Ring): - Now only one element remains at matrix[1][1]which is5.
- Append [5].
 
- Now only one element remains at 
- 
Final Result: [1, 2, 3, 6, 9, 8, 7, 4, 5].
Common Mistakes & Edge Cases
Common Mistakes
- Boundary Overlap:
- Not checking whether the current topis still less than or equal tobottomorleftis less than or equal torightbefore traversing a row or column.
 
- Not checking whether the current 
- Double Counting:
- Re-visiting elements if boundaries are not updated correctly.
 
- Handling Single Row or Column:
- Special care is needed when the matrix has only one row or one column.
 
Edge Cases
- Empty Matrix:
- Return an empty list.
 
- Matrix with a Single Row or Column:
- The spiral order is the same as the row or column itself.
 
- Non-Square Matrix:
- Ensure that the solution works for both rectangular and square matrices.
 
Alternative Variations and Related Problems
Variations
- Spiral Matrix II:
- Instead of reading a matrix, generate a matrix filled with elements in spiral order.
 
- Rotate Image:
- A related problem that involves rotating a matrix by 90 degrees.
 
Related Problems for Further Practice
- Spiral Matrix II
- Rotate Image
- Pascal's Triangle
TAGS
LeetCode
CONTRIBUTOR
Design Gurus Team
-
GET YOUR FREE
Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
1570. Dot Product of Two Sparse Vectors - Detailed Explanation
Learn to solve Leetcode 1570. Dot Product of Two Sparse Vectors with multiple approaches.
9. Palindrome Number - Detailed Explanation
Learn to solve Leetcode 9. Palindrome Number with multiple approaches.
440. K-th Smallest in Lexicographical Order - Detailed Explanation
Learn to solve Leetcode 440. K-th Smallest in Lexicographical Order with multiple approaches.
539. Minimum Time Difference - Detailed Explanation
Learn to solve Leetcode 539. Minimum Time Difference with multiple approaches.
380. Insert Delete GetRandom O(1) - Detailed Explanation
Learn to solve Leetcode 380. Insert Delete GetRandom O(1) with multiple approaches.
20. Valid Parentheses - Detailed Explanation
Learn to solve Leetcode 20. Valid Parentheses with multiple approaches.
Related Courses
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
4.6
(69,299 learners)
$197
New

Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
3.9
(1,107 learners)
$78
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
4
(26,683 learners)
$78
One-Stop Portal For Tech Interviews.
Copyright © 2025 Design Gurus, LLC. All rights reserved.