Spiral Matrix
Medium
Topics
Given an m x n matrix, return all elements in spiral order (clockwise starting from the top-left).
Example 1
The figure shades the walk order, lighter for the first half and darker for the second: right along the top row, down the right column, back along the bottom, up the left, then repeat on the ring inside. The answer is the values in that order.
2D grid — one row per line.
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,3,6,9,8,7,4,5]
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
- 1 <= m, n <= 10
- -100 <= matrix[i][j] <= 100
Editorial — intuition, approach, complexity and pitfalls
Intuition
Peel the matrix like an onion: walk the top row, right column, bottom row, left column, then shrink the boundaries inward and repeat.
Approach
- Track four boundaries: top, bottom, left, right.
- Traverse top row left-to-right, right column top-to-bottom, bottom row right-to-left, left column bottom-to-top.
- After each edge, move the corresponding boundary inward; stop when boundaries cross.
Dry Run
matrix 1 2 3 4
5 6 7 8
9 10 11 12
Four shrinking bounds, one layer per outer iteration.
pass 1 top row 1 2 3 4 top -> 1
right col 8 12 right -> 2
bottom row 11 10 9 bottom -> 1
left col 5 left -> 1
pass 2 top row 6 7 top -> 2
right col (empty) right -> 1
bottom row SKIPPED, top 2 is now past bottom 1
left col (empty) left -> 2
loop exits: top 2 > bottom 1
answer 1 2 3 4 8 12 11 10 9 5 6 7
The two mid-loop re-checks are what the pitfall is about, and pass 2 shows one
firing. By the time the bottom row would be read, `top` has already advanced past
`bottom` -- the middle row was consumed as a top row, and reading it again as a
bottom row would emit it twice.
It is easiest to see on a degenerate shape. Without the re-checks, the single row
[[1,2,3]] comes back as 1 2 3 2 1, and the single column [[1],[2],[3]] as
1 2 3 2 -- the leftover line gets walked back the other way.
Nothing is marked visited and no extra space is used. The bounds alone encode
which cells remain, which is why each of the four inner loops must also update
its own bound immediately after running.Complexity
- Time — O(m*n): each element is appended exactly once.
- Space — O(1): aside from the output, only boundary counters.
Common Pitfalls
- Re-check top <= bottom and left <= right before the bottom row and left column to avoid double-visiting on non-square matrices.
Full Solution — all languages
class Solution:
def spiralOrder(self, matrix):
res=[]
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): res.append(matrix[top][c])
top+=1
for r in range(top,bottom+1): res.append(matrix[r][right])
right-=1
if top<=bottom:
for c in range(right,left-1,-1): res.append(matrix[bottom][c])
bottom-=1
if left<=right:
for r in range(bottom,top-1,-1): res.append(matrix[r][left])
left+=1
return resimport java.util.*;
class Solution {
public java.util.List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res=new ArrayList<>();
int top=0,bottom=matrix.length-1,left=0,right=matrix[0].length-1;
while(top<=bottom&&left<=right) {
for(int c=left;c<=right;c++)res.add(matrix[top][c]);
top++;
for(int r=top;r<=bottom;r++)res.add(matrix[r][right]);
right--;
if(top<=bottom) {
for(int c=right;c>=left;c--)res.add(matrix[bottom][c]);
bottom--;
}
if(left<=right) {
for(int r=bottom;r>=top;r--)res.add(matrix[r][left]);
left++;
}
}
return res;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
int top=0,bottom=matrix.size()-1,left=0,right=matrix[0].size()-1;
while(top<=bottom&&left<=right) {
for(int c=left;c<=right;c++)res.push_back(matrix[top][c]);
top++;
for(int r=top;r<=bottom;r++)res.push_back(matrix[r][right]);
right--;
if(top<=bottom) {
for(int c=right;c>=left;c--)res.push_back(matrix[bottom][c]);
bottom--;
}
if(left<=right) {
for(int r=bottom;r>=top;r--)res.push_back(matrix[r][left]);
left++;
}
}
return res;
}
};/**
* @param {number[][]} matrix
* @return {number[]}
*/ var spiralOrder = function(matrix) {
const res=[];
let top=0,bottom=matrix.length-1,left=0,right=matrix[0].length-1;
while(top<=bottom&&left<=right) {
for(let c=left;c<=right;c++)res.push(matrix[top][c]);
top++;
for(let r=top;r<=bottom;r++)res.push(matrix[r][right]);
right--;
if(top<=bottom) {
for(let c=right;c>=left;c--)res.push(matrix[bottom][c]);
bottom--;
}
if(left<=right) {
for(let r=bottom;r>=top;r--)res.push(matrix[r][left]);
left++;
}
}
return res;
};