MEDIUM NC#137 Blind #47 Math & Geometry - Simulation
54. Spiral Matrix
📖 Problem
Given an m x n matrix, return all elements of the matrix in spiral order (clockwise, starting from top-left corner).
🧠 Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- •Array methods (`push`, `pop`, `shift`, `slice`)
- •Object/Map/Set usage patterns
- •Function parameter and return typing
Logical Thinking Concepts
- •Define invariants before coding
- •Check edge cases first (`[]`, single element, duplicates)
- •Estimate time/space before implementation
- •Apply Recursion reasoning pattern
💡 Approach
- → Use four pointers: top, bottom, left, right
- → Traverse in order: left→right (top), top→bottom (right),
- → After each traversal, move the corresponding pointer inward
- → Time: O(m * n), Space: O(1) excluding output
🛠️ Hints & Pitfalls
Hints
- •Use four pointers: top, bottom, left, right
- •Traverse in order: left→right (top), top→bottom (right),
- •After each traversal, move the corresponding pointer inward
Common Pitfalls
- •Time: O(m * n), Space: O(1) excluding output
🧪 Test Cases
Test Case 1
Not run Input:
spiralOrder([[1,2,3],[4,5,6],[7,8,9]]); Expected:
[1, 2, 3, 6, 9, 8, 7, 4, 5] Test Case 2
Not run Input:
spiralOrder([[1,2,3,4],[5,6,7,8],[9,10,11,12]]); Expected:
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7] Test Case 3
Not run Input:
spiralOrder(matrix: number[][]); Expected:
Computed from hidden reference 📝 Code Editor
📤 Output