Spiral Matrix – Solution & Complexity

Solution Walkthrough

  1. Step 1: Understand the Spiral Fill

    • Create an n x n matrix and place values from 1 to n².
    • The direction starts moving right, then turns down, left, and up.
    • After each side is filled, the active boundary moves inward.
  2. Step 2: Track Four Boundaries

    • Keep top, bottom, left, and right boundaries for the unfilled rectangle.
    • Fill the top row left-to-right, then move top down.
    • Fill the right column top-to-bottom, then move right left, and continue around.
    top, bottom = 0, n - 1
    left, right = 0, n - 1
    value = 1
  3. Step 3: Fill One Ring at a Time

    • One loop iteration fills the outer ring of the current rectangle.
    • After a ring is finished, the boundaries describe the next inner ring.
    • Continue while top <= bottom and left <= right.
    while top <= bottom and left <= right:
        for col in range(left, right + 1):
            matrix[top][col] = value
            value += 1
        top += 1
  4. Step 4: Handle Center Cells and Input Type

    • Odd-sized matrices eventually have a single center cell, which the boundary loop fills naturally.
    • Some test inputs may provide n as a string after JSON parsing.
    • Convert n to an integer before creating the matrix.
  5. Step 5: Complete Solution and Complexity

    • The final solution fills each cell exactly once while shrinking the boundaries.
    • Time complexity is O(n²).
    • Space complexity is O(n²) for the returned matrix.
    def generate_spiral_matrix(n: int) -> list[list[int]]:
        n = int(n)
        if n <= 0:
            return []
    
        matrix = [[0 for _ in range(n)] for _ in range(n)]
        top, bottom = 0, n - 1
        left, right = 0, n - 1
        value = 1
    
        while top <= bottom and left <= right:
            for col in range(left, right + 1):
                matrix[top][col] = value
                value += 1
            top += 1
    
            for row in range(top, bottom + 1):
                matrix[row][right] = value
                value += 1
            right -= 1
    
            if top <= bottom:
                for col in range(right, left - 1, -1):
                    matrix[bottom][col] = value
                    value += 1
                bottom -= 1
    
            if left <= right:
                for row in range(bottom, top - 1, -1):
                    matrix[row][left] = value
                    value += 1
                left += 1
    
        return matrix

FAQ