Spiral Matrix
On this page
Problem statement
Given an m × n matrix, return all of its elements in spiral order: start at the top-left corner, go right along the top row, down the right column, left along the bottom row, up the left column, and keep going inward ring by ring until every element has been visited once.
A matrix-traversal question where the idea is easy and the difficulty is in the bounds: non-square matrices, a single row or column, and the last ring in the middle. Original problem: LeetCode 54.
Example

Input: [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]]
Output: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
Input: [[1], [2], [3]] -> [1, 2, 3] # one column
Input: [[1, 2], [3, 4]] -> [1, 2, 4, 3]
Constraints (assumed)
- 1 ≤ m, n ≤ 10; the matrix is rectangular.
What this question tests
- Keeping four boundaries consistent while they move.
- Handling the last ring, which may be a single row or a single column.
- Writing loops whose ranges you can explain, not patch by trial and error.
Questions to ask first
- Is the matrix always rectangular? (Here: yes.)
- Can it be empty? (Here: at least 1 × 1; returning an empty list for an empty matrix is cheap anyway.)
- Clockwise from the top-left? (Here: yes. Other directions are a common variant.)
- May I modify the matrix (for example, to mark visited cells)?
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.