Skip to main content

16. Spiral Matrix

mediumAsked at Revolut

Walk a 2D matrix in spiral order with bounded pointers, a Revolut screen that mirrors traversing a partitioned ledger grid row-by-row without revisiting cells.

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, going right, then down, then left, then up, repeatedly.

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 + direction array

Maintain a visited grid and dx/dy arrays, turning whenever blocked.

Time
O(m*n)
Space
O(m*n)
// classic visited[][] + dx=[0,1,0,-1] dy=[1,0,-1,0]

Tradeoff:

2. Four-bound pointer shrink

Track top/bottom/left/right and shrink after each side. Linear time, constant extra space.

Time
O(m*n)
Space
O(1)
function spiralOrder(matrix){
  const res = [];
  let t = 0, b = matrix.length - 1, l = 0, r = matrix[0].length - 1;
  while (t <= b && l <= r){
    for (let i = l; i <= r; i++) res.push(matrix[t][i]); t++;
    for (let i = t; i <= b; i++) res.push(matrix[i][r]); r--;
    if (t <= b) { for (let i = r; i >= l; i--) res.push(matrix[b][i]); b--; }
    if (l <= r) { for (let i = b; i >= t; i--) res.push(matrix[i][l]); l++; }
  }
  return res;
}

Tradeoff:

Revolut-specific tips

Revolut graders care that you guard the last two passes with `t <= b` and `l <= r` — they'll deliberately test on a non-square ledger grid to catch off-by-one.

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 Revolut interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →