Spiral Matrix solution explained
To read a matrix in spiral order, keep four boundaries (top, bottom, left, right) and peel one ring per loop: walk the top row left to right, the right column downward, the bottom row right to left, and the left column upward, moving each boundary inward after you use it. Check that rows and columns remain before the last two walks. The Spiral Matrix solution visits each cell once, O(m·n) time and O(1) extra space besides the output.
By Evin JohnPublished 7 min read
The task, restated
You get a rectangle of values, not necessarily square. Start at the top-left corner, move right along the top edge, turn down at the corner, then left along the bottom, then up, and keep turning inward until every value has been visited exactly once. Return the values in the order you visited them.
| Grid | Spiral order |
|---|---|
| [[3, 1, 4], [1, 5, 9], [2, 6, 5], [3, 5, 8]] | [3, 1, 4, 9, 5, 8, 5, 3, 2, 1, 5, 6] |
| [[1, 2], [3, 4], [5, 6]] | [1, 2, 4, 6, 5, 3] |
| [[10, 20, 30, 40, 50]] | [10, 20, 30, 40, 50] |
| [[6], [7], [8]] | [6, 7, 8] |
| [] or [[]] | [] |
Worth confirming: the direction (clockwise from the top-left is the usual version), whether the grid can be empty or contain empty rows, and whether every row has the same length.
How interviewers use it
Spiral Matrix has no clever trick. It tests whether you can keep four moving indexes straight under time pressure and whether you test the shapes that break naive code: one row, one column, and tall or wide rectangles. Interviewers watch how you choose loop bounds and whether you trace a non-square example before declaring victory.
- Fill an n by n grid with 1 to n² in spiral order. Same four boundaries, but write instead of read.
- Counterclockwise, or starting from another corner. Change the order of the four walks.
- Return the k-th value of the spiral without building the list. Skip whole rings by their size, then walk the last one.
- Spiral outward from a cell. Step lengths grow 1, 1, 2, 2, 3, 3 while you turn right; cells outside the grid are skipped.
Brute force: simulate with a visited grid
Walk like a robot. Keep a direction (right, down, left, up) and a grid of booleans marking visited cells. After each step, look at the next cell in the current direction. If it is off the grid or already visited, turn right. Stop after m·n cells. It runs in O(m·n) time but uses O(m·n) extra memory for the visited grid, and it is a reliable checker for the leaner version.
def spiral_visited(grid):
if not grid or not grid[0]:
return []
rows, cols = len(grid), len(grid[0])
seen = [[False] * cols for _ in range(rows)]
moves = [(0, 1), (1, 0), (0, -1), (-1, 0)]
r = c = d = 0
out = []
for _ in range(rows * cols):
out.append(grid[r][c])
seen[r][c] = True
nr, nc = r + moves[d][0], c + moves[d][1]
if not (0 <= nr < rows and 0 <= nc < cols) or seen[nr][nc]:
d = (d + 1) % 4
nr, nc = r + moves[d][0], c + moves[d][1]
r, c = nr, nc
return outThe efficient approach: shrink four boundaries
The visited grid only tells you where the edge of the unvisited area is, and four integers can track that edge directly. Keep top, bottom, left and right. Read the top row from left to right and move top down. Read the right column from top to bottom and move right inward. Then, only if a row is still left, read the bottom row backward and move bottom up. Only if a column is still left, read the left column upward and move left inward. Repeat while top is at most bottom and left is at most right.
Those two "only if" checks are the whole difficulty. Take a single row: after reading it left to right, top passes bottom. Without the check, the backward walk would read the same row again.
def spiral_order(grid):
out = []
if not grid or not grid[0]:
return out
top, bottom = 0, len(grid) - 1
left, right = 0, len(grid[0]) - 1
while top <= bottom and left <= right:
for c in range(left, right + 1):
out.append(grid[top][c])
top += 1
for r in range(top, bottom + 1):
out.append(grid[r][right])
right -= 1
if top <= bottom:
for c in range(right, left - 1, -1):
out.append(grid[bottom][c])
bottom -= 1
if left <= right:
for r in range(bottom, top - 1, -1):
out.append(grid[r][left])
left += 1
return outfunction spiralOrder(grid) {
const out = [];
if (grid.length === 0 || grid[0].length === 0) return out;
let top = 0, bottom = grid.length - 1;
let left = 0, right = grid[0].length - 1;
while (top <= bottom && left <= right) {
for (let c = left; c <= right; c++) out.push(grid[top][c]);
top++;
for (let r = top; r <= bottom; r++) out.push(grid[r][right]);
right--;
if (top <= bottom) {
for (let c = right; c >= left; c--) out.push(grid[bottom][c]);
bottom--;
}
if (left <= right) {
for (let r = bottom; r >= top; r--) out.push(grid[r][left]);
left++;
}
}
return out;
}Time and space
| Version | Time | Extra space (not counting the output) |
|---|---|---|
| Simulation with a visited grid | O(m·n) | O(m·n) |
| Shrinking boundaries | O(m·n) | O(1) |
Edge cases
- An empty list, or a list holding one empty row.
- A single row: only the first walk produces values.
- A single column: the first walk reads one value, the second reads the rest.
- Tall rectangles and wide rectangles, which end on a column and on a row respectively.
- A 1 by 1 grid.
- An odd square, where the last ring is a single center cell.
Mistakes to avoid
- Dropping the two guards, which double-reads the middle row or column of some rectangles.
- Testing only square grids, where the guards rarely matter.
- Mixing conventions, with right meaning the last index in one walk and one past it in another.
- Writing the reverse loops with an exclusive bound that stops one cell early.
- Assuming
grid[0]exists before checking that the grid has rows.
How to explain it out loud
Fictional example
- Candidate
- I will keep four walls: top, bottom, left and right. Each loop peels one ring: top row, right column, bottom row backward, left column upward, and each wall moves in after I use it.
- Candidate
- The risk is a ring that is only one row or one column thick, so I re-check top against bottom and left against right before the two return walks.
- Candidate
- Let me trace a 2 by 3 grid and a single row. Every cell is read once, so it is m times n time and constant extra space.
Related walkthroughs
Rotate Image moves the same rings this page reads, with four-way swaps. Set Matrix Zeroes is the grid problem where memory, not order, is the test. For a traversal that spreads in all four directions at once, see Number of Islands.
Where Natively fits
Practicing on Mac or Windows, you can let Natively read a spiral or grid-walk problem from a screenshot and suggest the boundary approach, then ask it which shapes to test. Its transcript of your mock round shows whether you explained the single-row guard or only coded it. The AI interview assistant page covers the rest.
Questions people ask
How do you traverse a matrix in spiral order?
Keep top, bottom, left and right boundaries. Read the top row, the right column, then the bottom row backward and the left column upward, moving each boundary inward after use.
Why does Spiral Matrix read some values twice?
Usually because the code reads the bottom row or left column after the boundaries have crossed. Check top against bottom and left against right before those two walks.
What is the time complexity of Spiral Matrix?
O(m times n), since each cell is read once. The boundary version needs O(1) extra space besides the output list.
Is a visited array needed for Spiral Matrix?
No. A visited grid works, but four boundary indexes carry the same information with constant memory.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
