Spiral Matrix: Optimal Simulation (Data-Backed Guide)

By DSA Prep Team · March 4, 2026 · 8 min read · Algorithms

Spiral Matrix is the #18 most asked LeetCode problem globally — the standard matrix simulation problem that tests your ability to manage boundary conditions cleanly under pressure.

Our analysis of 10,385 verified interview questions across 259 companies shows it appeared 60 times across 24 companies — including Google, Amazon, Meta, Microsoft, Goldman Sachs, Bloomberg, Databricks, DE Shaw, CrowdStrike, J.P. Morgan, and Capital One.

There are two clean approaches: boundary shrinking (track top/bottom/left/right walls and peel the matrix layer by layer) and direction vector (walk in a direction until you hit a wall or visited cell, then turn right). Boundary shrinking is more predictable and easier to explain in interviews.

Table of Contents

The Data: 24 Companies Ask This

MetricValue
Total Interview Appearances60 verified mentions
Companies That Ask It24 companies
Global Rank#18 out of 10,385 questions
DifficultyMedium
Core PatternsArray, Matrix, Simulation

šŸ“Œ Companies That Ask This Problem

Google, Amazon, Meta, Microsoft, Goldman Sachs, Bloomberg, Databricks, DE Shaw, CrowdStrike, J.P. Morgan, Capital One, AMD, Adobe, Anduril, Apple, Cisco, Deutsche Bank, Epic Systems, IBM, Infosys, Intuit, Lenskart, and 2 more.

Problem Statement

LeetCode #54 — Spiral Matrix

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

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

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]

The Core Intuition: Peel Layers

Maintain four boundary pointers: top, bottom, left, right. On each pass, traverse the current outer layer in four directions — left-to-right along top, top-to-bottom along right, right-to-left along bottom, bottom-to-top along left — then shrink each boundary inward by 1. Repeat until boundaries cross.

šŸ’” The Four Traversals Per Layer

  1. Left → Right along top row, then top++
  2. Top → Bottom along right column, then right--
  3. Right → Left along bottom row (if top <= bottom), then bottom--
  4. Bottom → Top along left column (if left <= right), then left++

The guards on steps 3 and 4 prevent double-counting single rows or columns in the middle.

Code in Python, Java & JavaScript

Python 3 — Boundary Shrinking
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:
        # Left to right along top row
        for col in range(left, right + 1):
            result.append(matrix[top][col])
        top += 1

        # Top to bottom along right column
        for row in range(top, bottom + 1):
            result.append(matrix[row][right])
        right -= 1

        # Right to left along bottom row (guard against single row)
        if top <= bottom:
            for col in range(right, left - 1, -1):
                result.append(matrix[bottom][col])
            bottom -= 1

        # Bottom to top along left column (guard against single column)
        if left <= right:
            for row in range(bottom, top - 1, -1):
                result.append(matrix[row][left])
            left += 1

    return result
Java
class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        int top = 0, bottom = matrix.length - 1;
        int left = 0, right = matrix[0].length - 1;

        while (top <= bottom && left <= right) {
            for (int col = left; col <= right; col++)
                result.add(matrix[top][col]);
            top++;

            for (int row = top; row <= bottom; row++)
                result.add(matrix[row][right]);
            right--;

            if (top <= bottom) {
                for (int col = right; col >= left; col--)
                    result.add(matrix[bottom][col]);
                bottom--;
            }

            if (left <= right) {
                for (int row = bottom; row >= top; row--)
                    result.add(matrix[row][left]);
                left++;
            }
        }
        return result;
    }
}
JavaScript
var spiralOrder = function(matrix) {
    const result = [];
    let top = 0, bottom = matrix.length - 1;
    let left = 0, right = matrix[0].length - 1;

    while (top <= bottom && left <= right) {
        for (let col = left; col <= right; col++)
            result.push(matrix[top][col]);
        top++;

        for (let row = top; row <= bottom; row++)
            result.push(matrix[row][right]);
        right--;

        if (top <= bottom) {
            for (let col = right; col >= left; col--)
                result.push(matrix[bottom][col]);
            bottom--;
        }

        if (left <= right) {
            for (let row = bottom; row >= top; row--)
                result.push(matrix[row][left]);
            left++;
        }
    }
    return result;
};

Complexity Analysis

šŸ“Š Complexity

Matrix Simulation Family

ProblemTechnique
LC #54 Spiral Matrix (read)Boundary shrinking or direction vector
LC #59 Spiral Matrix II (generate)Same boundaries, fill values 1..n² instead of reading
LC #48 Rotate ImageTranspose + reverse rows in-place
LC #73 Set Matrix ZeroesUse first row/col as markers
LC #289 Game of LifeEncode two states in one cell

How to Actually Remember This

āœ… Spaced Repetition Schedule

  1. Today: Solve LC #54. Then immediately solve LC #59 (Spiral Matrix II) — same code, just write 1..n² instead of reading.
  2. Day 3: Solve LC #48 (Rotate Image) — matrix in-place rotation.
  3. Day 7: Solve LC #73 (Set Matrix Zeroes) — matrix marking with O(1) space trick.

Tag on DSAPrep.dev under Matrix and Simulation.

Track on DSAPrep.dev →