Browse curriculum

FAANGPrep Sprint

Spiral Matrix (LeetCode 54)

Spiral Matrix (LeetCode 54): 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};

Spiral Matrix in Python, Java, C++, TypeScript and C

Spiral Matrix in Python
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        result = []
        if not matrix: return result
        
        top, bottom = 0, len(matrix) - 1
        left, right = 0, len(matrix[0]) - 1
        
        while top <= bottom and left <= right:
            # Move Right
            for i in range(left, right + 1):
                result.append(matrix[top][i])
            top += 1
            
            # Move Down
            for i in range(top, bottom + 1):
                result.append(matrix[i][right])
            right -= 1
            
            if top <= bottom:
                # Move Left
                for i in range(right, left - 1, -1):
                    result.append(matrix[bottom][i])
                bottom -= 1
            
            if left <= right:
                # Move Up
                for i in range(bottom, top - 1, -1):
                    result.append(matrix[i][left])
                left += 1
                
        return result
Spiral Matrix in Java
class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        if (matrix.length == 0) return result;
        
        int top = 0, bottom = matrix.length - 1;
        int left = 0, right = matrix[0].length - 1;
        
        while (top <= bottom && left <= right) {
            for(int i=left; i<=right; i++) result.add(matrix[top][i]);
            top++;
            
            for(int i=top; i<=bottom; i++) result.add(matrix[i][right]);
            right--;
            
            if(top <= bottom) {
                for(int i=right; i>=left; i--) result.add(matrix[bottom][i]);
                bottom--;
            }
            
            if(left <= right) {
                for(int i=bottom; i>=top; i--) result.add(matrix[i][left]);
                left++;
            }
        }
        return result;
    }
}
Spiral Matrix in C++
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> result;
        if (matrix.empty()) return result;
        
        int top = 0, bottom = matrix.size() - 1;
        int left = 0, right = matrix[0].size() - 1;
        
        while (top <= bottom && left <= right) {
            for(int i=left; i<=right; i++) result.push_back(matrix[top][i]);
            top++;
            
            for(int i=top; i<=bottom; i++) result.push_back(matrix[i][right]);
            right--;
            
            if(top <= bottom) {
                for(int i=right; i>=left; i--) result.push_back(matrix[bottom][i]);
                bottom--;
            }
            
            if(left <= right) {
                for(int i=bottom; i>=top; i--) result.push_back(matrix[i][left]);
                left++;
            }
        }
        return result;
    }
};
Spiral Matrix in TypeScript
function spiralOrder(matrix: number[][]): number[] {
    const result: number[] = [];
    if (!matrix.length) return result;
    
    let top = 0, bottom = matrix.length - 1;
    let left = 0, right = matrix[0].length - 1;
    
    while (top <= bottom && left <= right) {
        for(let i=left; i<=right; i++) result.push(matrix[top][i]);
        top++;
        
        for(let i=top; i<=bottom; i++) result.push(matrix[i][right]);
        right--;
        
        if(top <= bottom) {
            for(let i=right; i>=left; i--) result.push(matrix[bottom][i]);
            bottom--;
        }
        
        if(left <= right) {
            for(let i=bottom; i>=top; i--) result.push(matrix[i][left]);
            left++;
        }
    }
    return result;
};
Spiral Matrix in C
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize) {
    int rows = matrixSize;
    int cols = matrixColSize[0];
    int size = rows * cols;
    int* result = (int*)malloc(size * sizeof(int));
    *returnSize = size;
    
    int top = 0, bottom = rows - 1;
    int left = 0, right = cols - 1;
    int idx = 0;
    
    while (top <= bottom && left <= right) {
        for(int i=left; i<=right; i++) result[idx++] = matrix[top][i];
        top++;
        
        for(int i=top; i<=bottom; i++) result[idx++] = matrix[i][right];
        right--;
        
        if(top <= bottom) {
            for(int i=right; i>=left; i--) result[idx++] = matrix[bottom][i];
            bottom--;
        }
        
        if(left <= right) {
            for(int i=bottom; i>=top; i--) result[idx++] = matrix[i][left];
            left++;
        }
    }
    return result;
}