Matrix Spiral TraversalLoading saved progress…

Matrix Spiral Traversal

You're given an m × n matrix — a grid of numbers with m rows and n columns. Return every element in clockwise spiral order: start at the top-left, walk right across the top row, down the right column, left across the bottom row, up the left column, then spiral inward one ring at a time until every cell is visited. Think of peeling an onion layer by layer, or a camera panning around the outer edge of a photo and then tightening toward the center.

Signature

// matrix: number[][] — an m×n grid. Rows all have the same length n.
//   The values can be anything; the tests use numbers.
// returns: number[] — every element, in clockwise spiral order,
//   starting from matrix[0][0].
function matrixSpiralTraversal(matrix: number[][]): number[];

Examples

// 3×3 — full clockwise loop, then the single center cell.
matrixSpiralTraversal([
  [1, 2, 3],
  [8, 9, 4],
  [7, 6, 5],
]);
// → [1, 2, 3, 4, 5, 6, 7, 8, 9]
// 3×4 wide rectangle — the outer ring, then the inner [11, 12] strip.
matrixSpiralTraversal([
  [1, 2, 3, 4],
  [10, 11, 12, 5],
  [9, 8, 7, 6],
]);
// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Notes

  • Any m × n shape is allowed — square, wide, or tall. The output length always equals m × n (every cell is visited exactly once).
  • Direction is fixed: clockwise, starting top-left. Right along the top, down the right side, left along the bottom, up the left side, then inward.
  • Empty input returns []. Both [] (no rows) and [[]] (one row with no columns) produce an empty array.
  • Single row and single column are valid. A 1 × n matrix is just its row left-to-right; an m × 1 matrix is just its column top-to-bottom. The tricky part is making sure these aren't visited twice.
  • Don't mutate the input. Return a new array; leave matrix untouched.
  • Don't worry about ragged rows (rows of differing lengths), counter-clockwise order, or starting from a corner other than the top-left — all out of scope.
Loading editor…