Browse curriculum

FAANGPrep Sprint

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};