#54

Spiral Matrix

MediumMatrixHas vizArrayMatrixSimulation

Problem

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

Example 1

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

Output: [1,2,3,6,9,8,7,4,5]

Clockwise spiral starting at top-left.

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]

3×4 spiral.

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100
Loading visualization…

Explanation

Spiral Matrix is a Medium interview problem tagged [Array, Matrix, Simulation]. The winning approach is typically **Matrix**.

Intuition

Indexing discipline prevents the majority of matrix bugs.

Approach

Treat cells as graph nodes or apply in-place layer/spiral transforms with careful bounds.

  1. Define directions.
  2. Mark visited or mutate carefully.
  3. Watch r/c swap mistakes.

Solution

Pattern-level skeleton only — not this problem’s exact answer. Adapt it to the statement.

Pattern templateMatrix

Edge cases

  • •Empty or single-element input
  • •Duplicates and ties
  • •Maximum constraints / overflow
  • •Disconnected or unreachable states (for graphs)

Complexity

Time: O(n log n) or O(n)

Space: O(n)

Before coding, restate the problem, name the pattern (Matrix), and write the invariant or DP state in one sentence.

Learn the topic

Got it?

Mark #54 Spiral Matrix as understood when the pattern clicks.