Command Palette

Search for a command to run...

Problem 2.6 · ArraysMedium

Spiral Matrix

What it teaches: The four-boundary technique for walking a matrix layer by layer without revisiting cells.

Practise it on judges as “Spiral Matrix”.

The problem

Given an m × n matrix, return all its elements in spiral order: across the top, down the right side, back along the bottom, up the left side, then repeat inwards.

Example 1

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

Pattern clues in the wording

  • → 2D grid walked in a fixed geometric order
  • → Layers that shrink as you go

These clues point to Matrix Traversal: Walk a 2D grid in a controlled order (rows, columns, spiral, diagonals) using boundaries or direction arrays.

Stuck? Take one hint at a time

Solution.java · starter
import java.util.*;

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> out = new ArrayList<>();
        int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
        return out;
    }
}

Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.

Test cases

#InputExpected
1
matrix = [[1,2,3],[4,5,6],[7,8,9]]
[1,2,3,6,9,8,7,4,5]
2
matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
[1,2,3,4,8,12,11,10,9,5,6,7]
3
matrix = [[1],[2],[3]]
One column
[1,2,3]

+ 1 hidden test the code runner will check

From slow to fast

Approaches

1

Optimal: shrink four boundaries

Time O(m × n) Space O(1) extra (besides the output list)

Walk the top row left to right, then top++. Walk the right column top to bottom, then right--. If rows remain, walk the bottom row right to left, then bottom--. If columns remain, walk the left column bottom to top, then left++. Repeat while top <= bottom and left <= right.

Approach 1
import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> out = 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++) out.add(matrix[top][c]);
            top++;
            for (int r = top; r <= bottom; r++) out.add(matrix[r][right]);
            right--;
            if (top <= bottom) {
                for (int c = right; c >= left; c--) out.add(matrix[bottom][c]);
                bottom--;
            }
            if (left <= right) {
                for (int r = bottom; r >= top; r--) out.add(matrix[r][left]);
                left++;
            }
        }
        return out;
    }
}

Verdict: Every cell is visited exactly once.

Before you submit

Edge cases and common mistakes

Test these inputs

  • A single row
  • A single column
  • A 1 × 1 matrix
  • More rows than columns and vice versa

Mistakes people make

  • Skipping the top <= bottom / left <= right checks, which re-reads a row or column in non-square matrices.
  • Mixing up matrix.length (rows) and matrix[0].length (columns).

Interview

Follow-up questions

How would you fill an n × n matrix with 1..n² in spiral order?

Can you do it with a direction array instead of boundaries?