LeetEye LeetEye
Medium Math & Geometry ~5 min

Spiral Matrix

math-and-geometry spiral-matrix

Problem

Given an m x n matrix, return all elements of the matrix in spiral order.

Examples

Example 1
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Example 2
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]
Key Insight

Track four boundaries (top, bottom, left, right). Process each edge, shrink boundary, repeat.

Track four boundaries. Traverse right->down->left->up, shrinking boundaries after each direction. Stop when boundaries cross.

How to Approach This Problem

Pattern Recognition: When you see keywords like spiral matrix math-and-geometry, think Math & Geometry.

Step-by-Step Reasoning

1 Spiral traversal order is:
Answer: Left->Right, Top->Bottom, Right->Left, Bottom->Top
Start at top-left, go right, down, left, up, then repeat inward.
2 We track:
Answer: top, bottom, left, right
Four boundaries define the current "ring" to traverse.
3 After traversing top row (left to right):
Answer: Increment top
Top row is done. Next ring's top is one row lower.
4 Stop when:
Answer: All of above
Boundaries crossing means no more elements to process.
5 For single row or column:
Answer: Boundaries naturally handle it
Boundary checks (top <= bottom, left <= right) handle degenerate cases.

Solution

def spiralOrder(matrix: List[List[int]]) -> List[int]:
    if not matrix:
        return []
    
    result = []
    top, bottom = 0, len(matrix) - 1
    left, right = 0, len(matrix[0]) - 1
    
    while top <= bottom and left <= right:
        # Traverse right
        for col in range(left, right + 1):
            result.append(matrix[top][col])
        top += 1
        
        # Traverse down
        for row in range(top, bottom + 1):
            result.append(matrix[row][right])
        right -= 1
        
        # Traverse left (if rows remain)
        if top <= bottom:
            for col in range(right, left - 1, -1):
                result.append(matrix[bottom][col])
            bottom -= 1
        
        # Traverse up (if columns remain)
        if left <= right:
            for row in range(bottom, top - 1, -1):
                result.append(matrix[row][left])
            left += 1
    
    return result

Complexity Analysis

Time O(m × n)
Space O(1)

Master This Pattern

Build intuition with interactive MCQs. Practice Math & Geometry problems in the LeetEye app.

Download LeetEye Free
Practice in LeetEye