LeetCode 54: Spiral Matrix is a Medium matrix problem. This Python walkthrough develops a shrinking boundaries solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Matrix |
| Reusable pattern | shrinking boundaries |
| Complexity | O(mn) time and O(1) extra space excluding output |
Recognizing the pattern
Matrix problems become manageable when row, column, layer, or neighbor boundaries are explicit rather than inferred inside nested loops.
For this problem specifically, traverse top, right, bottom, and left boundaries, then shrink them while checking whether each boundary still exists. The invariant worth writing beside the code is: All cells outside the current boundaries have been emitted exactly once.
Step-by-step algorithm
- Identify the input state consumed by
spiralOrder(matrix)and initialize the data required by the shrinking boundaries pattern. - Traverse top, right, bottom, and left boundaries, then shrink them while checking whether each boundary still exists.
- After each update, verify the page’s central invariant: All cells outside the current boundaries have been emitted exactly once.
- Finish only after the boundary behavior is covered: Single remaining rows or columns must not be traversed twice.
Python solution
class Solution:
def spiralOrder(self, matrix):
if not matrix: return []
top, bottom, left, right, answer = 0, len(matrix) - 1, 0, len(matrix[0]) - 1, []
while top <= bottom and left <= right:
answer.extend(matrix[top][left:right + 1]); top += 1
for r in range(top, bottom + 1): answer.append(matrix[r][right])
right -= 1
if top <= bottom:
answer.extend(reversed(matrix[bottom][left:right + 1])); bottom -= 1
if left <= right:
for r in range(bottom, top - 1, -1): answer.append(matrix[r][left])
left += 1
return answerReading the implementation
The main entry point is spiralOrder(matrix). The named working state includes top, right, left; those variables make the shrinking boundaries state visible instead of hiding it in incidental control flow.
The implementation uses 3 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, traverse top, right, bottom, and left boundaries, then shrink them while checking whether each boundary still exists.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Traverse top, right, bottom, and left boundaries, then shrink them while checking whether each boundary still exists. Each update records the current item without invalidating earlier decisions; consequently, all cells outside the current boundaries have been emitted exactly once.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(mn) time and O(1) extra space excluding output. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
An auxiliary matrix can make reads and writes independent, while marker or boundary techniques trade that clarity for lower space use. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert Solution().spiralOrder([[1,2,3],[4,5,6],[7,8,9]]) == [1,2,3,6,9,8,7,4,5]Common mistakes and edge cases
- Problem-specific boundary: Single remaining rows or columns must not be traversed twice.
- Pattern-level pitfall: Rectangular inputs, one-row layers, and one-column layers expose off-by-one errors that square examples often hide.
- Invariant check: after every update, confirm that all cells outside the current boundaries have been emitted exactly once.
Interview review checklist
- Explain why shrinking boundaries matches the structure of this input.
- State the invariant in one sentence before tracing code: All cells outside the current boundaries have been emitted exactly once.
- Derive O(mn) time and O(1) extra space excluding output from how many times each element or state is visited.
- Test the boundary explicitly: Single remaining rows or columns must not be traversed twice.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 36. Valid Sudoku · Next: 48. Rotate Image