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
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):
- Move Right: Traverse from
lefttoright. Incrementtop. - Move Down: Traverse from
toptobottom. Decrementright. - Move Left: Traverse from
righttoleft. Decrementbottom. (Checktop <= bottomfirst) - Move Up: Traverse from
bottomtotop. Incrementleft. (Checkleft <= rightfirst)
Initialize
top=0,bottom=rows-1,left=0,right=cols-1.Loop while
top <= bottomandleft <= 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 (
leftcheck,topcheck) 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;45 let top = 0, bottom = matrix.length - 1;6 let left = 0, right = matrix[0].length - 1;78 while (top <= bottom && left <= right) {9 for(let i=left; i<=right; i++) result.push(matrix[top][i]);10 top++;1112 for(let i=top; i<=bottom; i++) result.push(matrix[i][right]);13 right--;1415 if(top <= bottom) {16 for(let i=right; i>=left; i--) result.push(matrix[bottom][i]);17 bottom--;18 }1920 if(left <= right) {21 for(let i=bottom; i>=top; i--) result.push(matrix[i][left]);22 left++;23 }24 }25 return result;26};
