Spiral Matrix
A medium Matrix problem included in Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.
- Topic
- Matrix
- Sheets
- 2
- Core for
- 10 roles
- Platform
- LeetCode
The problem
Given an m-by-n matrix filled with integers, return all elements of the matrix in a clockwise spiral order starting from the top-left corner.
Example 1
- Input
- matrix = [[1,2,3],[4,5,6],[7,8,9]]
- Output
- [1,2,3,6,9,8,7,4,5]
- Why
- Starting from the top-left, traverse right across the top row, then down the right column, then left across the bottom row, then up the left column, repeating inward.
Example 2
- Input
- matrix = [[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]
Constraints
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 10
- -100 <= matrix[i][j] <= 100
How to think about it
Updated 2026-09-09The matrix is not a path to trace. It is a set of concentric rectangles. Reading clockwise means peeling the outermost rectangle, then the next one inward, and so on. Four boundary pointers are all the state needed; nothing else varies.
Approaches, worst first
Direction simulation with visited set
time O(m*n) · space O(m*n)
Walk in the current direction until hitting a boundary or a visited cell, then turn clockwise. Mark every cell visited so no cell is stepped on twice. Correct but pays O(m*n) memory for the set.
Boundary pointers peeling layersWrite this one
time O(m*n) · space O(1)
Maintain top, bottom, left, right. Read the top row left to right, the right column top to bottom, the bottom row right to left, and the left column bottom to top. Shrink all four inward and repeat. The matrix is read one rectangular layer at a time.
Where people lose marks · 3
- After reading the top row and incrementing top, failing to check top <= bottom before reading the bottom row causes a single-row matrix to be emitted twice.
- The four sides share corner cells and each corner must be emitted exactly once. The loop structure must guarantee this by reading sides in the fixed clockwise order with boundary checks between each.
- Reading the left column requires checking left <= right first; without this check the left column pass re-visits cells already emitted in the top row.
Full solution
Boundary pointers peeling layers: four edges shrink inward after each side is read, so every cell is emitted exactly once with O(1) extra space and no visited set; the two guards stop a leftover single row or column from being read twice.
Python
def spiral_order(matrix: list[list[int]]) -> list[int]:
out: list[int] = []
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
# a single remaining row/column has already been read above
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 out
JavaScript
function spiralOrder(matrix) {
const out = [];
let top = 0, bottom = matrix.length - 1;
let left = 0, 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--;
// a single remaining row/column has already been read above
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;
}
The theory behind it
Matrix — the ground this problem stands on. All Matrix problems
What Matrix is
A matrix is a flat grid of cells laid out in rows and columns, like a checkerboard or a spreadsheet. Each cell has an address made of two numbers: its row index going down and its column index going across. Because computer memory stores these rows one after another or as arrays of arrays, jumping straight to any individual cell takes the same tiny fraction of time no matter where it sits on the board.
When to reach for it
Reach for matrix techniques when the input is a two-dimensional grid, board, or map. Common prompts include walking through a maze, finding connected islands of land in water, rotating an image ninety degrees in place, or reading numbers in a spiral. Words like rows, columns, neighbors, adjacent squares, or diagonal lines are clear signs. It also appears in grid planning where each cell depends on the values above and to the left.
How the pattern works
Think of navigating the grid using directional coordinate offsets. Define row and column step arrays for moving up, down, left, and right. Always check that new row and column indices stay strictly between zero and the board boundaries before reading cell values. For spiral scans, track four boundary lines for top, bottom, left, and right, shrinking them inward after reading each side. When searching connected regions, mark visited cells directly or write a marker value into the cell to avoid looping.
What each operation costs
| Operation | Time |
|---|---|
| read or write cell by row and column | O(1) |
| visit every cell across m rows and n columns | O(m * n) |
| rotate square matrix in place | O(n^2) |
What usually goes wrong with Matrix
- Flipping row and column dimensions by mixing up grid height with grid width, causing index out of bounds crashes on rectangular grids where row and column counts differ.
- Reading neighbor cells without first confirming that the row and column coordinates are within valid bounds between zero and the board edges.
- Forgetting to update inner boundary limits during spiral traversal, which causes single-row or single-column matrices to print duplicate entries.
Which roles need this problem
Matrix is a core topic for these 10 roles — if you're targeting one of them, this problem is early in your path, not optional.
Secondary for 7 more roles, including Frontend Engineer, Full-Stack Developer, Android Developer.
Track this in your role's order
Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.
Start freeMore Matrix problems
Problem set and role mapping as of .