DSA Tracker

Problem

Medium

Spiral Matrix

A medium Matrix interview guide. Task statement, worked examples, intuition, and step-by-step solutions.

Topic
Matrix
Sheets
2
Core for
10 roles

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 = [[2,4,6],[8,10,12],[14,16,18]]
Output
[2,4,6,12,18,16,14,8,10]
Why
Right along the top (2,4,6), down the right side (12,18), left along the bottom (16,14), up to 8, then the centre 10.

Example 2

Input
matrix = [[5,1,7,3],[9,2,8,6],[4,11,10,12]]
Output
[5,1,7,3,6,12,10,11,4,9,2,8]

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-29

The 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

  1. 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. Marking every cell visited so none is stepped on twice costs O(m*n) memory for that set.

  2. 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;
}
Try it in the editor

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.

More Matrix problems

Track in your role's order

Pick your target role and all 370 problems resequence to what that interview actually asks.

Start free

Problem set and role mapping as of .