Browse curriculum

Spiral Matrix

Return all elements of the matrix in spiral order.

Problem Understanding

Read every element of an m x n matrix by walking its outer ring and then each inner ring in turn, clockwise (Right -> Down -> Left -> Up), and return them in that order.

Interactive Visualization

READY

0

1

2

3

0

1
2
3
4

1

5
6
7
8

2

9
10
11
12

Top

0

Bottom

2

Left

0

Right

3

Output

Nothing appended yet

 

Boundaries start at the edges: top = 0, bottom = 2, left = 0, right = 3

Next

Right along row 0: append matrix[0][0] = 1

Matrix

Legend & Complexity

Cell being appended to the output

Time

O(m·n)

Extra space

O(1)

Watch the path as we peel the matrix layer by layer.

Strategy

We can simulate the spiral movement by defining boundaries (top, bottom, left, right):

  1. Move Right: Traverse from left to right. Increment top.
  2. Move Down: Traverse from top to bottom. Decrement right.
  3. Move Left: Traverse from right to left. Decrement bottom. (Check top <= bottom first)
  4. Move Up: Traverse from bottom to top. Increment left. (Check left <= right first)
  • Initialize top=0, bottom=rows-1, left=0, right=cols-1.

  • Loop while top <= bottom and left <= right.

Dry Run

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

Step Action Output After Step Boundaries Update
1 Right [1, 2, 3] top becomes 1
2 Down [..., 6, 9] right becomes 1
3 Left [..., 8, 7] bottom becomes 1
4 Up [..., 4] left becomes 1
5 Right [..., 5] top becomes 2. Loop Ends.

Edge Cases & Common Mistakes

Watch out for:

  • Single Row/Column: Ensure the inner loops (left check, top check) prevent double-counting.

  • Empty Matrix: Handle gracefully.

  • Non-Square Matrix: Logic must hold for m != n.

Solution

Simulation with boundaries.

Spiral Matrix Code
1var spiralOrder = function(matrix) {
2 const result = [];
3 if (!matrix.length) return result;
4
5 let top = 0, bottom = matrix.length - 1;
6 let left = 0, right = matrix[0].length - 1;
7
8 while (top <= bottom && left <= right) {
9 for(let i=left; i<=right; i++) result.push(matrix[top][i]);
10 top++;
11
12 for(let i=top; i<=bottom; i++) result.push(matrix[i][right]);
13 right--;
14
15 if(top <= bottom) {
16 for(let i=right; i>=left; i--) result.push(matrix[bottom][i]);
17 bottom--;
18 }
19
20 if(left <= right) {
21 for(let i=bottom; i>=top; i--) result.push(matrix[i][left]);
22 left++;
23 }
24 }
25 return result;
26};

The approach, step by step

  1. Set the boundaries

    Start with top = 0, bottom = rows - 1, left = 0 and right = cols - 1.

  2. Walk right, then down

    Append the top row from left to right and move top down; append the right column from top to bottom and move right in.

  3. Walk left, then up, if anything remains

    If top <= bottom, append the bottom row from right to left and move bottom up. If left <= right, append the left column from bottom to top and move left in.

  4. Repeat until the boundaries cross

    Continue while top <= bottom and left <= right; the output is then in spiral order.

Frequently asked questions

How does the Spiral Matrix algorithm work?

It keeps four boundaries: top, bottom, left and right. Each lap walks right along the top row, down the right column, left along the bottom row and up the left column, moving the matching boundary inward after each pass, until the boundaries cross.


Why does the loop check top <= bottom and left <= right before the left and up passes?

After the right and down passes move top and right inward, what remains can be a single row or a single column. Without those two checks the left or up pass would walk back over cells that were already appended.


What is the time and space complexity of Spiral Matrix?

O(m × n) time, because every cell is appended exactly once. Apart from the output list the walk only keeps four boundary variables, so the extra space is O(1).

Applying for software engineering roles? Free, no sign-up:

AI resume checker — match your resume to the job description