- Interview Questions
- /
- Problems
- /
- Spiral Matrix
Spiral Matrix
Read every value of a grid in clockwise spiral order, starting from the top-left corner. A pure index-bookkeeping problem that rewards tracking four shrinking boundaries. Solve it below in Python or JavaScript, then read the walkthrough.
Problem
You're given an m × n grid of integers matrix. Return all of its values in clockwise spiral order: start at the top-left cell, go right along the top row, down the right column, left along the bottom row, up the left column, and keep circling inward until every cell has been visited exactly once.
The grid doesn't have to be square.
Example 1
- Input
- matrix = [[7, 1, 4], [9, 2, 8]]
- Output
- [7, 1, 4, 8, 2, 9]
Right across the top (7, 1, 4), down to 8, then left along the bottom (2, 9). Every cell is used after one lap.
Example 2
- Input
- matrix = [[3, 6], [5, 0], [2, 8]]
- Output
- [3, 6, 0, 8, 2, 5]
Top row 3, 6; down the right column 0, 8; bottom row leftward 2; up the left column 5.
Example 3
- Input
- matrix = [[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21], [22, 23, 24, 25]]
- Output
- [10, 11, 12, 13, 17, 21, 25, 24, 23, 22, 18, 14, 15, 16, 20, 19]
The outer ring takes 12 values, then the inner 2 × 2 ring takes the last four.
Constraints
- 1 ≤ m, n ≤ 10
- -100 ≤ matrix[i][j] ≤ 100
Practice
Runs 11 tests in your browser. Python loads on the first run (about 6 MB, then cached). Press ⌘/Ctrl + Enter to run.
Get asked Spiral Matrix in a real interview?
Interview Solver gives you a working solution live, during your actual coding interview. Invisible to screensharing.
How to solve Spiral Matrix
Pattern: Shrinking boundaries
There's no clever algorithm here; the whole problem is keeping indices straight. The cleanest way to do that is to stop thinking about "where am I" and think about which rows and columns are still unread.
Track four boundaries: top, bottom, left, right. One lap reads the top row and moves top down, reads the right column and moves right in, reads the bottom row and moves bottom up, reads the left column and moves left in. The only subtle part is that after the first two sides, the grid may have run out of rows or columns, so the bottom and left passes need a check that there is still something between the boundaries. That check is what stops a single leftover row or column from being read twice.
Approach 1: Simulate with a direction and a visited grid
Walk cell by cell with a current direction (right, down, left, up). When the next cell is out of bounds or already visited, turn clockwise. Easy to get right, but it needs an m × n visited array.
Time O(m·n) · Space O(m·n)
Approach 2: Peel layer by layer with four boundaries
Set top = 0, bottom = m - 1, left = 0, right = n - 1. While top ≤ bottom and left ≤ right:
- Read
toprow fromlefttoright, thentop += 1. - Read
rightcolumn fromtoptobottom, thenright -= 1. - If
top ≤ bottom, readbottomrow fromrightdown toleft, thenbottom -= 1. - If
left ≤ right, readleftcolumn frombottomup totop, thenleft += 1.
The output list is the only extra memory.
Time O(m·n) · Space O(1) besides the output
| Approach | Time | Space |
|---|---|---|
| Simulate with a direction and a visited grid | O(m·n) | O(m·n) |
| Peel layer by layer with four boundaries | O(m·n) | O(1) besides the output |
Solution code
Try the practice editor first. Both solutions pass every test above.
Spiral Matrix solution in Python
def spiral_order(matrix: list[list[int]]) -> list[int]:
out = []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
while top <= bottom and left <= right:
for c in range(left, right + 1):
out.append(matrix[top][c])
top += 1
for r in range(top, bottom + 1):
out.append(matrix[r][right])
right -= 1
if top <= bottom:
for c in range(right, left - 1, -1):
out.append(matrix[bottom][c])
bottom -= 1
if left <= right:
for r in range(bottom, top - 1, -1):
out.append(matrix[r][left])
left += 1
return outSpiral Matrix solution in JavaScript
function spiralOrder(matrix) {
const out = [];
let top = 0;
let bottom = matrix.length - 1;
let left = 0;
let right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (let c = left; c <= right; c++) out.push(matrix[top][c]);
top++;
for (let r = top; r <= bottom; r++) out.push(matrix[r][right]);
right--;
if (top <= bottom) {
for (let c = right; c >= left; c--) out.push(matrix[bottom][c]);
bottom--;
}
if (left <= right) {
for (let r = bottom; r >= top; r--) out.push(matrix[r][left]);
left++;
}
}
return out;
}Common mistakes
- Skipping the `top ≤ bottom` and `left ≤ right` checks before the third and fourth passes. A single middle row or column then gets read forward and backward.
- Only testing square grids. Wide and tall rectangles are where the leftover-row and leftover-column cases appear.
- Updating a boundary before the loop that reads it, which shifts the whole side by one.
- Using the visited-grid approach and then marking cells by overwriting values with a sentinel that could also be a real value.
What interviewers look for
Say up front that the challenge is bookkeeping, then name your four boundaries and what each loop does. Writing the four passes as four tiny loops that each move one boundary keeps the code easy to check line by line.
Before you finish, trace a 1 × n row, an n × 1 column, and a 3 × 5 rectangle. Interviewers expect at least one of those to come up, and showing that you thought of them unprompted counts.
Follow-up questions
How would you fill an n × n grid with 1 to n² in spiral order?
Use the same four boundaries, but write a counter into each cell instead of reading it. The structure of the loops is identical.
What about counterclockwise order?
Swap the order of the passes: go down the left column first, then along the bottom row to the right, up the right column, and leftward along the top row, moving each boundary after its pass.
Can you produce the order without storing it all, for example as a generator?
Yes. The boundary version only needs the four integers as state, so you can yield each value as you reach it and use O(1) memory beyond the input.
Companies that ask Spiral Matrix
Spiral Matrix is tagged by 143 companies in our interview dataset. The score shows how often it comes up at each company.
- Chan Zuckerberg Initiative100%
- Goat Group100%
- Mitsubishi100%
- Hopper100%
- Pine Labs100%
- Broadcom100%
- Dataart100%
- Ntt Data100%
- Rbc100%
- Zoho97.8%
- Trimble96%
- Motional95%
- Siriusxm95%
- Chamberlain Group94%
- Epic Systems93.9%
- Intellia Therapeutics93%
- Thumbtack92%
- Check Point Software Technologies90%
- Ebay89.3%
- Capital One88.4%
- Zimmer Biomet88%
- Wissen Technology88%
- Pornhub86.5%
- Gartner86%
and 119 more.
Practice next
Get live help in the real interview
Working solutions in real time during your actual interview. Invisible to screensharing.
Start Free TrialNo credit card required