SDE & MLE Prep

59. Spiral Matrix II

Problem

Return an n×n matrix filled with 1…n² in clockwise spiral order, starting at the top-left.

Example: n = 3 → [[1,2,3],[8,9,4],[7,6,5]]

Same four boundaries as Spiral Matrix, but write 1..n² instead of reading.

Complexity: O(n²).

class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        m = [[0] * n for _ in range(n)]
        top, bottom, left, right, k = 0, n - 1, 0, n - 1, 1
        while top <= bottom:
            for c in range(left, right + 1):
                m[top][c] = k; k += 1
            for r in range(top + 1, bottom + 1):
                m[r][right] = k; k += 1
            for c in range(right - 1, left - 1, -1):
                if top < bottom:
                    m[bottom][c] = k; k += 1
            for r in range(bottom - 1, top, -1):
                if left < right:
                    m[r][left] = k; k += 1
            top, bottom, left, right = top + 1, bottom - 1, left + 1, right - 1
        return m