← DSA
MEDIUM

Spiral Matrix

PracticeNeetCode ↗LeetCode ↗

Given an m × n matrix, return all of its elements in spiral order — starting at the top-left, moving right, then spiraling inward.

Example

Input matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output [1,2,3,6,9,8,7,4,5]

Key Pointers

Step-by-Step Analysis

  1. Initialize top = 0, bottom = rows - 1, left = 0, right = cols - 1.
  2. While top <= bottom and left <= right: walk left→right along row top, then increment top.
  3. Walk top→bottom along column right, then decrement right.
  4. If top <= bottom, walk right→left along row bottom, then decrement bottom.
  5. If left <= right, walk bottom→top along column left, then increment left. Repeat until the boundaries cross.

Complexity

Time: O(m · n) — Space: O(1) extra, excluding the output

Code

def spiralOrder(matrix: list[list[int]]) -> list[int]:
    result = []
    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):
            result.append(matrix[top][c])
        top += 1

        for r in range(top, bottom + 1):
            result.append(matrix[r][right])
        right -= 1

        if top <= bottom:
            for c in range(right, left - 1, -1):
                result.append(matrix[bottom][c])
            bottom -= 1

        if left <= right:
            for r in range(bottom, top - 1, -1):
                result.append(matrix[r][left])
            left += 1

    return result

Code Explanation

How the solution above works, piece by piece.

  1. Keep four boundaries: top, bottom, left, right.
  2. Walk the top row left → right, then move top down. Walk the right column top → bottom, then move right left.
  3. Walk the bottom row right → left and the left column bottom → top, but only if rows/columns remain (top <= bottom, left <= right). Without these checks a single leftover row or column would be read twice.
  4. Repeat while the boundaries haven't crossed.
  5. Every cell is visited once: O(m × n).

Visual Walkthrough

Running it on matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]:

Spiral order through a 3 by 3 matrix123456789top row →, right column ↓,bottom row ←, left column ↑,then shrink the boundaries[1, 2, 3, 6, 9, 8, 7, 4, 5]
Four boundaries (top, bottom, left, right) close in after each side is walked. The centre 5 is reached on the second lap, when top = bottom = left = right = 1.
first lapsecond lap

Video Explanation

NeetCode — Spiral Matrix, LeetCode 54