KatInterview

59. Spiral Matrix II

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to generate an n x n square matrix and fill it with numbers from 1 to n² in a clockwise spiral pattern. This is a simulation problem where we need to trace the spiral path and place numbers sequentially.

Solution

Spiral Matrix II in Python

class Solution:
    def generateMatrix(self, n: int) -> list[list[int]]:
        # Initialize an n x n matrix with zeros.
        matrix = [[0] * n for _ in range(n)]
        
        # Initialize boundaries and the number to be filled.
        top, bottom = 0, n - 1
        left, right = 0, n - 1
        num = 1
        
        # Loop until the boundaries cross.
        while top <= bottom and left <= right:
            # 1. Fill the top row from left to right.
            for i in range(left, right + 1):
                matrix[top][i] = num
                num += 1
            top += 1 # Move the top boundary down.
            
            # 2. Fill the right column from top to bottom.
            for i in range(top, bottom + 1):
                matrix[i][right] = num
                num += 1
            right -= 1 # Move the right boundary left.
            
            # This check is important for odd-sized matrices.
            # If the boundaries have crossed, we are done.
            if not (top <= bottom and left <= right):
                break
                
            # 3. Fill the bottom row from right to left.
            for i in range(right, left - 1, -1):
                matrix[bottom][i] = num
                num += 1
            bottom -= 1 # Move the bottom boundary up.
            
            # 4. Fill the left column from bottom to top.
            for i in range(bottom, top - 1, -1):
                matrix[i][left] = num
                num += 1
            left += 1 # Move the left boundary right.
            
        return matrix

Spiral Matrix II in Java

class Solution {
    public int[][] generateMatrix(int n) {
        // Initialize an n x n matrix. It defaults to zeros.
        int[][] matrix = new int[n][n];
        
        // Initialize boundaries and the number to be filled.
        int top = 0, bottom = n - 1;
        int left = 0, right = n - 1;
        int num = 1;
        
        // Loop until the boundaries cross.
        while (top <= bottom && left <= right) {
            // 1. Fill the top row from left to right.
            for (int i = left; i <= right; i++) {
                matrix[top][i] = num++;
            }
            top++; // Move the top boundary down.
            
            // 2. Fill the right column from top to bottom.
            for (int i = top; i <= bottom; i++) {
                matrix[i][right] = num++;
            }
            right--; // Move the right boundary left.
            
            // This check is important for odd-sized matrices.
            // If the boundaries have crossed, we are done.
            if (top > bottom || left > right) {
                break;
            }
            
            // 3. Fill the bottom row from right to left.
            for (int i = right; i >= left; i--) {
                matrix[bottom][i] = num++;
            }
            bottom--; // Move the bottom boundary up.
            
            // 4. Fill the left column from bottom to top.
            for (int i = bottom; i >= top; i--) {
                matrix[i][left] = num++;
            }
            left++; // Move the left boundary right.
        }
        
        return matrix;
    }
}

Spiral Matrix II in C++

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        // Initialize an n x n matrix with zeros.
        vector<vector<int>> matrix(n, vector<int>(n, 0));
        
        // Initialize boundaries and the number to be filled.
        int top = 0, bottom = n - 1;
        int left = 0, right = n - 1;
        int num = 1;
        
        // Loop until the boundaries cross.
        while (top <= bottom && left <= right) {
            // 1. Fill the top row from left to right.
            for (int i = left; i <= right; ++i) {
                matrix[top][i] = num++;
            }
            top++; // Move the top boundary down.
            
            // 2. Fill the right column from top to bottom.
            for (int i = top; i <= bottom; ++i) {
                matrix[i][right] = num++;
            }
            right--; // Move the right boundary left.
            
            // This check is important for odd-sized matrices.
            // If the boundaries have crossed, we are done.
            if (top > bottom || left > right) {
                break;
            }
            
            // 3. Fill the bottom row from right to left.
            for (int i = right; i >= left; --i) {
                matrix[bottom][i] = num++;
            }
            bottom--; // Move the bottom boundary up.
            
            // 4. Fill the left column from bottom to top.
            for (int i = bottom; i >= top; --i) {
                matrix[i][left] = num++;
            }
            left++; // Move the left boundary right.
        }
        
        return matrix;
    }
};

Spiral Matrix II in TypeScript

function generateMatrix(n: number): number[][] {
    // Initialize an n x n matrix with zeros.
    const matrix: number[][] = Array(n).fill(0).map(() => Array(n).fill(0));
    
    // Initialize boundaries and the number to be filled.
    let top = 0, bottom = n - 1;
    let left = 0, right = n - 1;
    let num = 1;

    // Loop until the boundaries cross.
    while (top <= bottom && left <= right) {
        // 1. Fill the top row from left to right.
        for (let i = left; i <= right; i++) {
            matrix[top][i] = num++;
        }
        top++; // Move the top boundary down.

        // 2. Fill the right column from top to bottom.
        for (let i = top; i <= bottom; i++) {
            matrix[i][right] = num++;
        }
        right--; // Move the right boundary left.

        // This check is important for odd-sized matrices.
        // If the boundaries have crossed, we are done.
        if (top > bottom || left > right) {
            break;
        }

        // 3. Fill the bottom row from right to left.
        for (let i = right; i >= left; i--) {
            matrix[bottom][i] = num++;
        }
        bottom--; // Move the bottom boundary up.

        // 4. Fill the left column from bottom to top.
        for (let i = bottom; i >= top; i--) {
            matrix[i][left] = num++;
        }
        left++; // Move the left boundary right.
    }

    return matrix;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.