#59

Spiral Matrix II

Medium
ArrayMatrixSimulationLayered fillingMatrix traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(1)
💡

Intuition

Time O(n²)Space O(1)

The brute-force method is already quite efficient for this problem, as it directly fills the matrix in a spiral order. However, we can optimize the way we manage boundaries and the filling process to make the code cleaner and potentially faster.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an n x n matrix filled with zeros.
  2. 2Step 2: Use a single loop to fill the matrix in a spiral order by adjusting the boundaries dynamically.
  3. 3Step 3: Continue filling until all elements are placed.
solution.py18 lines
1def generateMatrix(n):
2    matrix = [[0] * n for _ in range(n)]
3    num = 1
4    layers = (n + 1) // 2
5    for layer in range(layers):
6        for i in range(layer, n - layer):
7            matrix[layer][i] = num
8            num += 1
9        for i in range(layer + 1, n - layer):
10            matrix[i][n - layer - 1] = num
11            num += 1
12        for i in range(n - layer - 1, layer - 1, -1):
13            matrix[n - layer - 1][i] = num
14            num += 1
15        for i in range(n - layer - 2, layer, -1):
16            matrix[i][layer] = num
17            num += 1
18    return matrix

Complexity note: The time complexity remains O(n²) as we still fill n² elements. The space complexity is O(1) since we are using the input matrix for storage.

  • 1Understanding how to manage boundaries is crucial for spiral filling.
  • 2Recognizing that filling in layers can simplify the logic.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.