Skip to main content

48. Spiral Matrix

mediumAsked at Datadog

Traverse an M x N matrix in spiral (clockwise) order. Datadog uses this as a 2D-traversal warmup to test boundary-management discipline — the same shape as iterating over a chunked time-series block with varying boundaries.

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

Source citations

Public interview reports confirming this problem appears in Datadog loops.

  • Glassdoor (2026-Q1)Datadog phone screen matrix question.

Problem

Given an m x n matrix, return all elements of the matrix in spiral order.

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 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. Direction-vector with visited matrix

Walk with (dx, dy); turn right when out of bounds or hitting visited cell.

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

Tradeoff: Works but allocates O(m*n) visited buffer. Datadog will push for O(1) extra space.

2. Four-boundary shrinking (optimal)

Maintain top/bottom/left/right boundaries. Traverse each side; shrink the boundary; turn.

Time
O(m * n)
Space
O(1)
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--;
    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;
}

Tradeoff: O(1) extra space. The two extra if-checks (top <= bottom, left <= right) handle non-square matrices. Datadog-canonical pattern.

Datadog-specific tips

Datadog grades on the two extra if-checks for non-square matrices. Without them, you double-traverse the middle row/column on rectangles. Articulate the four boundaries and shrink-after-traverse pattern before coding.

Common mistakes

  • Forgetting the if-checks after right-- and bottom-- — duplicates elements on non-square matrices.
  • Using strict < in the for loops instead of <= — drops the last element of each side.
  • Off-by-one in the boundary shrinks — top++ before the loop instead of after.

Follow-up questions

An interviewer at Datadog may pivot to one of these next:

  • Spiral Matrix II (LC 59) — generate spiral.
  • Spiral Matrix III (LC 885) — start from arbitrary cell.
  • Datadog-style: traverse a chunked metric block in row-major then column-major.

Solve it now

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

Output

Press Run or Cmd+Enter to execute

FAQ

Why need the two extra if-checks?

On a non-square matrix, after the top and right traversals, top might exceed bottom (single row left) or left might exceed right (single column). Without the check, you'd traverse what doesn't exist.

Can you do this without boundaries, using direction vectors?

Yes — see the first approach. Cleaner code but uses O(m*n) memory for the visited matrix.

Practice these live with InterviewChamp.AI

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

Practice these live with InterviewChamp.AI →