KatInterview

921. Spiral Matrix III

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 coordinates of a grid in the order they are visited by a clockwise spiral walk. The walk starts at a given cell (rStart, cStart) and initially moves east. A key feature is that the walk can go outside the grid boundaries, but we only record the coordinates when the walk is inside the grid. We need to collect a total of rows * cols coordinates.

Solution

Spiral Matrix III in Python

class Solution:
    def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> list[list[int]]:
        # Initialize the result list with the starting position
        result = [[rStart, cStart]]
        
        # Current position
        r, c = rStart, cStart
        
        total_cells = rows * cols
        if len(result) == total_cells:
            return result

        # Length of the current segment of the spiral
        length = 0
        # Direction: 0:East, 1:South, 2:West, 3:North
        direction = 0 
        # Direction vectors for row and column changes
        dr = [0, 1, 0, -1]
        dc = [1, 0, -1, 0]
        
        # Loop until all grid cells are visited
        while len(result) < total_cells:
            # The length of the spiral arm increases every two turns (before East and West moves)
            if direction == 0 or direction == 2:
                length += 1
            
            # Move 'length' steps in the current direction
            for _ in range(length):
                r += dr[direction]
                c += dc[direction]
                
                # If the position is within the grid, add it to the result
                if 0 <= r < rows and 0 <= c < cols:
                    result.append([r, c])
                    # If we have found all cells, return immediately
                    if len(result) == total_cells:
                        return result
            
            # Turn right for the next segment
            direction = (direction + 1) % 4
            
        return result # Should be unreachable due to the inner return

Spiral Matrix III in Java

class Solution {
    public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
        int[][] result = new int[rows * cols][2];
        int count = 0;
        
        int r = rStart;
        int c = cStart;
        
        result[count++] = new int[]{r, c};
        if (count == rows * cols) {
            return result;
        }

        int len = 0; // Length of the current segment
        int d = 0;   // 0: East, 1: South, 2: West, 3: North
        int[] dr = {0, 1, 0, -1};
        int[] dc = {1, 0, -1, 0};

        while (count < rows * cols) {
            // For East and West segments, we increase the length of the side
            if (d == 0 || d == 2) {
                len++;
            }
            
            // Walk for 'len' steps in the current direction
            for (int k = 0; k < len; k++) {
                r += dr[d];
                c += dc[d];
                
                // Check if the current position is within the grid boundaries
                if (r >= 0 && r < rows && c >= 0 && c < cols) {
                    result[count++] = new int[]{r, c};
                    // If we have collected all coordinates, return immediately
                    if (count == rows * cols) {
                        return result;
                    }
                }
            }
            
            // Turn right to the next direction
            d = (d + 1) % 4;
        }
        
        return result; // Should be unreachable given problem constraints
    }
}

Spiral Matrix III in C++

class Solution {
public:
    vector<vector<int>> spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
        vector<vector<int>> result;
        result.reserve(rows * cols); // Pre-allocate memory for efficiency

        int r = rStart;
        int c = cStart;
        
        result.push_back({r, c});
        if (result.size() == rows * cols) {
            return result;
        }

        int len = 0; // Length of the current segment
        int d = 0;   // 0: East, 1: South, 2: West, 3: North
        int dr[] = {0, 1, 0, -1};
        int dc[] = {1, 0, -1, 0};
        
        while (true) { // Loop will be broken by an internal return
            // For East and West segments, we increase the length of the side
            if (d == 0 || d == 2) {
                len++;
            }
            
            // Walk for 'len' steps in the current direction
            for (int k = 0; k < len; ++k) {
                r += dr[d];
                c += dc[d];
                
                // Check if the current position is within the grid boundaries
                if (r >= 0 && r < rows && c >= 0 && c < cols) {
                    result.push_back({r, c});
                    // If we have collected all coordinates, return immediately
                    if (result.size() == rows * cols) {
                        return result;
                    }
                }
            }
            
            // Turn right to the next direction
            d = (d + 1) % 4;
        }
        
        return result; // Should be unreachable
    }
};

Spiral Matrix III in TypeScript

function spiralMatrixIII(rows: number, cols: number, rStart: number, cStart: number): number[][] {
    const result: number[][] = [];
    result.push([rStart, cStart]);
    
    const totalCells = rows * cols;
    if (result.length === totalCells) {
        return result;
    }

    let r = rStart, c = cStart;
    let len = 0; // Length of the current segment
    let d = 0;   // 0: East, 1: South, 2: West, 3: North
    const dr = [0, 1, 0, -1];
    const dc = [1, 0, -1, 0];

    while (result.length < totalCells) {
        // For East and West segments, we increase the length of the side
        if (d === 0 || d === 2) {
            len++;
        }
        
        // Walk for 'len' steps in the current direction
        for (let k = 0; k < len; k++) {
            r += dr[d];
            c += dc[d];
            
            // Check if the current position is within the grid boundaries
            if (r >= 0 && r < rows && c >= 0 && c < cols) {
                result.push([r, c]);
                // If we have collected all coordinates, return immediately
                if (result.length === totalCells) {
                    return result;
                }
            }
        }
        
        // Turn right to the next direction
        d = (d + 1) % 4;
    }
    
    return result; // Should be unreachable given problem constraints
};

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.