Tensorum
LeetCode 54 · Matrix

Spiral Matrix

LeetCode 54 · Medium · solution, intuition & step-by-step walkthrough

Four shrinking boundaries; guard the bottom and left passes.

MediumArrayMatrixSimulation
0 msruntime · beats 100%
19.3 MBmemory · beats 15%
1approach
4accepted runs · last 8 Mar 2026

This is how I solved Spiral Matrix (LeetCode 54), a medium problem from the Matrix pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Peel the matrix layer by layer with four boundaries. Walk the top row, the right column, the bottom row backwards and the left column upwards, shrinking each boundary after you use it.

Approach

  1. 1

    top, bottom, left, right define the unvisited rectangle.

  2. 2

    Left→right along top, then top++.

  3. 3

    Top→bottom along right, then right−−.

  4. 4

    If rows remain, right→left along bottom; if columns remain, bottom→top along left.

How I solved it

Boundary simulationPythonO(m·n) time
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        #4 pointers, top, right, bottom, left
        #move from left to right
        #move from top to bottom
        #move from right to left - handle single row
        #move from bottom to top - handle single col
        m = len(matrix)
        n = len(matrix[0])
        top=0
        bottom = m-1
        left = 0
        right = n-1
        res=[]
        while top<=bottom and left<=right:
            for i in range(left,right+1):
                res.append(matrix[top][i])
            top+=1
            for i in range(top,bottom+1):
                res.append(matrix[i][right])
            right-=1
            if top<=bottom:
                for j in range(right,left-1,-1):
                    res.append(matrix[bottom][j])   
                bottom-=1
            if left<=right:
                for i in range(bottom,top-1,-1):
                    res.append(matrix[i][left]) 
                left+=1
        return res  
Loading the step-through…

Spiral Matrix — FAQ

What is the intuition behind Spiral Matrix?

Peel the matrix layer by layer with four boundaries. Walk the top row, the right column, the bottom row backwards and the left column upwards, shrinking each boundary after you use it.

How do you solve Spiral Matrix (LeetCode 54)?

1. top, bottom, left, right define the unvisited rectangle. 2. Left→right along top, then top++. 3. Top→bottom along right, then right−−. 4. If rows remain, right→left along bottom; if columns remain, bottom→top along left.

What is the time and space complexity of Spiral Matrix?

Time: O(m·n). Space: O(1) extra. (Accepted approach: Boundary simulation.)

What are common mistakes in Spiral Matrix?

Without the top ≤ bottom and left ≤ right checks, a single remaining row or column is read twice.