#2326
Spiral Matrix IV
MediumArrayLinked ListMatrixSimulationMatrix TraversalDirection Vectors
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a similar approach to the brute force but ensures that we efficiently navigate through the matrix using direction vectors. This reduces unnecessary checks and allows us to fill the matrix in a single pass.
⚙️
Algorithm
3 steps- 1Step 1: Initialize the matrix with -1.
- 2Step 2: Use a direction vector to control movement in the matrix.
- 3Step 3: Iterate through the linked list, placing values into the matrix while checking bounds and direction changes.
solution.py23 lines
1class ListNode:
2 def __init__(self, val=0, next=None):
3 self.val = val
4 self.next = next
5
6def spiralMatrix(m, n, head):
7 matrix = [[-1] * n for _ in range(m)]
8 directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
9 x, y, d = 0, 0, 0
10 current = head
11 for _ in range(m * n):
12 if current:
13 matrix[x][y] = current.val
14 current = current.next
15 x += directions[d][0]
16 y += directions[d][1]
17 if x < 0 or x >= m or y < 0 or y >= n or matrix[x][y] != -1:
18 x -= directions[d][0]
19 y -= directions[d][1]
20 d = (d + 1) % 4
21 x += directions[d][0]
22 y += directions[d][1]
23 return matrixℹ
Complexity note: The time complexity is O(n) since we fill the matrix in a single pass through the linked list. The space complexity is O(n) due to the storage of the matrix.
- 1Understanding how to navigate through a matrix using direction vectors is crucial for spiral traversal.
- 2Filling the matrix with default values (like -1) helps in managing unfilled spaces effectively.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.