Spiral Matrix
Medium
MatrixArray
Problem
Given an m × n matrix, return all elements in spiral order — clockwise from the top-left, peeling off the outer layer at each step.
Example 1
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,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]
Constraints
- 1 ≤ m, n ≤ 10
Approach — Core Patterns
This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: see the walkthrough below.
Solution code
Python
class Solution:
def spiralOrder(self, matrix):
res = []
while matrix:
res += matrix.pop(0)
matrix = [list(r) for r in zip(*matrix)][::-1]
return res
Java
import java.util.*;
class Solution {
public List<Integer> spiralOrder(int[][] m) {
List<Integer> out = new ArrayList<>();
int top = 0, bot = m.length - 1, l = 0, r = m[0].length - 1;
while (top <= bot && l <= r) {
for (int j = l; j <= r; j++) out.add(m[top][j]);
top++;
for (int i = top; i <= bot; i++) out.add(m[i][r]);
r--;
if (top <= bot) { for (int j = r; j >= l; j--) out.add(m[bot][j]); bot--; }
if (l <= r) { for (int i = bot; i >= top; i--) out.add(m[i][l]); l++; }
}
return out;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Spiral Matrix interactively → ← All solutions