#54 Spiral Matrix
frequently reported atByteDance / TikTokOracleAppleMicrosoftAmazonUber
the problem
In plain words
Return all elements of an m × n matrix in spiral order: right along the top, down the right side, left along the bottom, up the left side, then repeat inwards.
in matrix = [[1,2,3],[4,5,6],[7,8,9]]
out [1,2,3,6,9,8,7,4,5]
in matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
out [1,2,3,4,8,12,11,10,9,5,6,7]
- 1 ≤ m, n ≤ 10
- -100 ≤ matrix[i][j] ≤ 100
your turn
Try it before you peek
Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.
Solve it in the browser
LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.
Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.
Marking the problem solved, or opening every hint, also shows it.
the aha
Key insight
patternMatrix traversal & in-place transformsSimulation
Keep four walls — top, bottom, left, right. Walk one side, then push that wall inwards. Stop when the walls cross.
solutions
From brute force to optimal
Move in the current direction; turn clockwise when you'd leave the grid or hit a visited cell.
- Directions right, down, left, up.
- Visit m·n cells; turn when blocked.
Each cell is visited once.
The visited grid.
class Solution { public List<Integer> spiralOrder(int[][] matrix) { int rows = matrix.length, cols = matrix[0].length; int[] dr = {0, 1, 0, -1}, dc = {1, 0, -1, 0}; // right, down, left, up boolean[][] seen = new boolean[rows][cols]; List<Integer> out = new ArrayList<>(); int r = 0, c = 0, d = 0; for (int k = 0; k < rows * cols; k++) { out.add(matrix[r][c]); seen[r][c] = true; int nr = r + dr[d], nc = c + dc[d]; if (nr < 0 || nr >= rows || nc < 0 || nc >= cols || seen[nr][nc]) { d = (d + 1) % 4; // blocked: turn clockwise nr = r + dr[d]; nc = c + dc[d]; } r = nr; c = nc; } return out; }}Traverse the outer ring using the four walls, then shrink them.
- top→ row left..right, then top++.
- right column top..bottom, then right--.
- If top ≤ bottom: bottom row right..left, then bottom--.
- If left ≤ right: left column bottom..top, then left++.
Each cell is added exactly once.
Four integers besides the output list.
class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> out = new ArrayList<>(); int top = 0, bottom = matrix.length - 1; int left = 0, right = matrix[0].length - 1; while (top <= bottom && left <= right) { for (int c = left; c <= right; c++) out.add(matrix[top][c]); top++; for (int r = top; r <= bottom; r++) out.add(matrix[r][right]); right--; if (top <= bottom) { // a row is still left for (int c = right; c >= left; c--) out.add(matrix[bottom][c]); bottom--; } if (left <= right) { // a column is still left for (int r = bottom; r >= top; r--) out.add(matrix[r][left]); left++; } } return out; }}Dry run
in the room
How to say it in the interview
talk track
- Draw a 3×4, not just a square — rectangles are where the bugs hide.
- Explain the two
ifguards: after the top row and right column, a single remaining row or column must not be walked twice.
traps
- Missing the
top ≤ bottom/left ≤ rightchecks — a single row gets added forwards and then backwards.
what they ask next
Follow-ups
Spiral Matrix II (LC 59): fill 1..n² in spiral order?
Same boundary walk, writing a counter instead of reading.
before you submit
Edge cases to test
- One row ([[1,2,3]]) — must not be added twice.
- One column ([[1],[2],[3]]).
- Rectangles (3×4, 4×3), not only squares.
- 1×1 → just that value.
practise next
Similar problems
- #48Rotate ImageMediumin Matrices
- #6Zigzag ConversionMediumin Matrices
- #74Search a 2D MatrixMediumin Binary Search