#54
Spiral Matrix
MediumArrayMatrixSimulationTwo PointersSimulation
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 is essentially the same as the brute force but can be optimized in terms of clarity and efficiency by using a single loop to manage the boundaries. This reduces the number of checks and makes the code cleaner.
⚙️
Algorithm
3 steps- 1Step 1: Initialize boundaries: top, bottom, left, right.
- 2Step 2: Use a while loop to iterate until all boundaries converge.
- 3Step 3: In each iteration, traverse the top row, right column, bottom row, and left column, adjusting boundaries accordingly.
solution.py22 lines
1# Full working Python code
2
3def spiralOrder(matrix):
4 if not matrix:
5 return []
6 result = []
7 top, bottom, left, right = 0, len(matrix) - 1, 0, len(matrix[0]) - 1
8 while top <= bottom and left <= right:
9 result.extend(matrix[top][left:right + 1])
10 top += 1
11 for i in range(top, bottom + 1):
12 result.append(matrix[i][right])
13 right -= 1
14 if top <= bottom:
15 result.extend(matrix[bottom][left:right + 1][::-1])
16 bottom -= 1
17 if left <= right:
18 for i in range(bottom, top - 1, -1):
19 result.append(matrix[i][left])
20 left += 1
21 return result
22ℹ
Complexity note: The time complexity remains O(n²) as we still visit each element once. The space complexity is O(n) because we store the result in a separate list.
- 1Spiral traversal can be visualized as layers of an onion being peeled away.
- 2Managing boundaries is crucial to avoid revisiting elements.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.