Spiral Matrix
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Given an m x 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 spiraling inward.
Understand the problem
- The matrix has
mrows andncolumns. It doesn't have to be square. - You visit every cell exactly once, like peeling an onion from the outside in, going clockwise.
- Return the values in the order you visit them.
Example 1
Input: 1 2 3
4 5 6
7 8 9
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]Around the outside (1 2 3, 6 9, 8 7, 4), then the middle 5.
Example 2
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]The inner part left after the first loop is the single row 6 7.
Example 3
Input: 1
2
3
Output: [1, 2, 3]A single column: just go down.
Constraints
1 <= m, n <= 10-100 <= matrix[i][j] <= 100
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Keep four boundaries around the part not yet visited, walk along each side in turn (right, down, left, up), and move that boundary inward after each side, until the boundaries cross.
The key insight: four shrinking walls
Think of the unvisited part as a rectangle with four walls: top, bottom, left, right. One loop around the spiral is four sweeps, and after each sweep the wall you just walked along moves inward:
- Right along the
toprow, fromlefttoright. Thentop++. - Down the
rightcolumn, fromtoptobottom. Thenright--. - Left along the
bottomrow, fromrighttoleft. Thenbottom--. - Up the
leftcolumn, frombottomtotop. Thenleft++.
Repeat while top <= bottom and left <= right.
The trap: a single row or column left over
When what's left is a single row (or column), sweeps 1 and 2 already use it up. Without a check, sweep 3 would walk the same row backward and add its values twice.
So sweep 3 only runs if top <= bottom (a row is still left), and sweep 4 only runs if left <= right (a column is still left).
Step by step
The 3 × 4 matrix from Example 2. Start: top = 0, bottom = 2, left = 0, right = 3.
1 2 3 4
5 6 7 8
9 10 11 12| Sweep | Reads | Boundaries after |
|---|---|---|
| right along row 0 | 1, 2, 3, 4 | top = 1 |
| down column 3 (rows 1–2) | 8, 12 | right = 2 |
| left along row 2 (cols 2–0) | 11, 10, 9 | bottom = 1 |
| up column 0 (rows 1–1) | 5 | left = 1 |
| right along row 1 (cols 1–2) | 6, 7 | top = 2 |
| down column 2 (empty range) | (nothing) | right = 1 |
| left along the bottom? | skipped: top (2) > bottom (1) | |
| up column 1 (empty range) | (nothing) | left = 2 |
Now top > bottom, so the loop stops. Result: [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7].
Without the check, the skipped sweep would have walked row 1 again and added 6 a second time.
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Time: O(m · n). Every cell is read once.
- Memory: O(1) besides the output.
Common mistakes
- Missing the
top <= bottom/left <= rightchecks before the third and fourth sweeps, which duplicates the middle row or column. - Off-by-one in the loop bounds. Each sweep includes both ends (
<=/>=). - Assuming the matrix is square. Test with a single row, a single column, and a wide matrix.
Going deeper
- An alternative uses a direction array (
right, down, left, up) and turns whenever the next cell is outside the matrix or already visited. It needs avisitedgrid (or a marker value), so the boundary version is usually cleaner. - Spiral Matrix II asks the reverse: fill an
n x nmatrix with1, 2, 3, ...in spiral order. The same four walls work.
Reference solution
/**
* @param {number[][]} matrix
* @return {number[]}
*/
export default function spiralOrder(matrix) {
const result = []
// The four walls around the part we haven't visited yet.
let top = 0
let bottom = matrix.length - 1
let left = 0
let right = matrix[0].length - 1
while (top <= bottom && left <= right) {
// 1. Right along the top row, then that row is done.
for (let c = left; c <= right; c++) result.push(matrix[top][c])
top++
// 2. Down the right column.
for (let r = top; r <= bottom; r++) result.push(matrix[r][right])
right--
// 3. Left along the bottom row, but only if a row is still left
// (otherwise we'd read the last single row again, backward).
if (top <= bottom) {
for (let c = right; c >= left; c--) result.push(matrix[bottom][c])
bottom--
}
// 4. Up the left column, only if a column is still left.
if (left <= right) {
for (let r = bottom; r >= top; r--) result.push(matrix[r][left])
left++
}
}
return result
}export default function spiralOrder(matrix: number[][]): number[] {
const result: number[] = []
// The four walls around the part we haven't visited yet.
let top = 0
let bottom = matrix.length - 1
let left = 0
let right = matrix[0].length - 1
while (top <= bottom && left <= right) {
// 1. Right along the top row, then that row is done.
for (let c = left; c <= right; c++) result.push(matrix[top][c])
top++
// 2. Down the right column.
for (let r = top; r <= bottom; r++) result.push(matrix[r][right])
right--
// 3. Left along the bottom row, but only if a row is still left
// (otherwise we'd read the last single row again, backward).
if (top <= bottom) {
for (let c = right; c >= left; c--) result.push(matrix[bottom][c])
bottom--
}
// 4. Up the left column, only if a column is still left.
if (left <= right) {
for (let r = bottom; r >= top; r--) result.push(matrix[r][left])
left++
}
}
return result
}def spiral_order(matrix: list[list[int]]) -> list[int]:
result = []
# The four walls around the part we haven't visited yet.
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
while top <= bottom and left <= right:
# 1. Right along the top row, then that row is done.
result.extend(matrix[top][c] for c in range(left, right + 1))
top += 1
# 2. Down the right column.
result.extend(matrix[r][right] for r in range(top, bottom + 1))
right -= 1
# 3. Left along the bottom row, but only if a row is still left
# (otherwise we'd read the last single row again, backward).
if top <= bottom:
result.extend(matrix[bottom][c] for c in range(right, left - 1, -1))
bottom -= 1
# 4. Up the left column, only if a column is still left.
if left <= right:
result.extend(matrix[r][left] for r in range(bottom, top - 1, -1))
left += 1
return result