Skip to main content

18. Spiral Matrix

mediumAsked at Klarna

Return all elements of a matrix traversed in spiral order.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given an m x n matrix, return all elements of the matrix in spiral order starting from the top-left and moving right, then down, then left, then up, and inward.

Constraints

  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

Examples

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]

Approaches

1. Visited matrix

Walk with direction vectors and a parallel boolean matrix marking visited cells.

Time
O(m*n)
Space
O(m*n)
function spiralOrder(M) {
  const m = M.length, n = M[0].length;
  const seen = Array.from({length: m}, () => Array(n).fill(false));
  const out = [];
  const dirs = [[0,1],[1,0],[0,-1],[-1,0]];
  let r = 0, c = 0, d = 0;
  for (let i = 0; i < m*n; i++) {
    out.push(M[r][c]);
    seen[r][c] = true;
    const nr = r + dirs[d][0], nc = c + dirs[d][1];
    if (nr < 0 || nr >= m || nc < 0 || nc >= n || seen[nr][nc]) d = (d+1) % 4;
    r += dirs[d][0];
    c += dirs[d][1];
  }
  return out;
}

Tradeoff:

2. Shrinking boundaries

Track top/bottom/left/right walls and walk each side, then close that wall inward. No auxiliary matrix.

Time
O(m*n)
Space
O(1)
function spiralOrder(M) {
  const out = [];
  let top = 0, bot = M.length - 1, left = 0, right = M[0].length - 1;
  while (top <= bot && left <= right) {
    for (let c = left; c <= right; c++) out.push(M[top][c]);
    top++;
    for (let r = top; r <= bot; r++) out.push(M[r][right]);
    right--;
    if (top <= bot) { for (let c = right; c >= left; c--) out.push(M[bot][c]); bot--; }
    if (left <= right) { for (let r = bot; r >= top; r--) out.push(M[r][left]); left++; }
  }
  return out;
}

Tradeoff:

Klarna-specific tips

Klarna's installment-ledger team uses this exact wall-shrink pattern when iterating dunning-cycle grids, so they grade hard on whether your odd-dimension edge cases come out clean.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Spiral Matrix and other Klarna interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →