↓Skip to main content
  1. LeetCode/

LeetCode 59: Spiral Matrix II

·2 mins· ·
LeetCode Medium Array Matrix Simulation
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-22

  • Submissions: Runtime Error → Wrong Answer → Runtime Error → Accepted ×2

Approach
#

Use the same four boundaries as LC 54 (Matrix Template 4) and write 1, 2, ..., n² along right, down, left and up. Each ring of a square is complete, but the single center cell for odd n still relies on the boundary checks.

My Attempts
#

I used a trick that builds from the largest numbers backwards: prepend a new range row and rotate what was built so far clockwise. The first tries had wrong starting values (attempt 2 returned only [[1]]) and type errors before the right start passed. It is short but not intuitive; the boundary simulation above is easier to explain.

Solution
#

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

Complexity
#

Time O(n²), space O(1) excluding output.

Mistakes to Avoid
#

  • [[0] * n] * n makes every row the same list.

Interview Explanation
#

As in Spiral Matrix, I keep four boundaries and fill numbers right, down, left and up, shrinking each boundary after its side. Time O(n²).

Related

LeetCode 54: Spiral Matrix
·2 mins
LeetCode Medium Array Matrix Simulation
LeetCode 54 note: keep four boundaries and walk right, down, left and up, shrinking a boundary after each side
LeetCode 36: Valid Sudoku
·2 mins
LeetCode Medium Array Hash-Table Matrix
LeetCode 36 note: each digit may appear once per row, column and 3 × 3 box; put (digit, row), (digit, column) and (digit, box) keys into one set
LeetCode 867: Transpose Matrix
·1 min
LeetCode Easy Array Matrix Simulation
LeetCode 867 note: the transpose is n × m with res[j][i] = matrix[i][j]; in Python, zip(*matrix)
LeetCode 566: Reshape the Matrix
·2 mins
LeetCode Easy Array Matrix Simulation
LeetCode 566 note: return the original if the element counts differ; otherwise element k goes to (k // c, k % c)
LeetCode 47: Permutations II
·2 mins
LeetCode Medium Array Backtracking Sorting
LeetCode 47 note: sort first, and within a level skip a value equal to the previous one when the previous one is unused
LeetCode 49: Group Anagrams
·2 mins
LeetCode Medium Array Hash-Table String Sorting
LeetCode 49 note: use each string’s sorted form as a key; strings sharing a key form one anagram group