Skip to problem
←

Spiral Matrix

Medium 0 attempts

You're given a matrix with m rows and n columns. Traverse it in a spiral: start at the top-left cell and move right along the top row, drop down the rightmost column, sweep left along the bottom row, climb the leftmost column, then keep spiraling inward until every cell has been visited. Return the values in the order you visited them.

Edge cases: Matrices with just one row or one column. An empty matrix should return [].

Function contract

Implement spiralOrder(matrix).

Output: Return an array containing each cell value exactly once in clockwise spiral order, starting at the top-left. A matrix with no cells returns [].

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]]
Output
[1,2,3]
Visual Aid
Clockwise, then inward
123456789

Follow 1 → 2 → 3 → 6 → 9 → 8 → 7 → 4 → 5. The center is visited only once.

Constraints
  • 0 <= matrix.length <= 10
  • All rows have the same length, at most 10.
  • -100 <= matrix[i][j] <= 100

Approach: Layer-by-Layer Boundaries

Track four boundaries — top, bottom, left, right — and peel off one layer of the spiral per iteration. After each direction traversal, shrink the corresponding boundary and check whether you've crossed over.

javascript
function spiralOrder(matrix) {
  const result = [];
  if (!matrix.length) return result;
  let top = 0, bottom = matrix.length - 1;
  let left = 0, right = matrix[0].length - 1;

  while (top <= bottom && left <= right) {
    for (let i = left; i <= right; i++) result.push(matrix[top][i]);
    top++;
    for (let i = top; i <= bottom; i++) result.push(matrix[i][right]);
    right--;
    if (top <= bottom) {
      for (let i = right; i >= left; i--) result.push(matrix[bottom][i]);
      bottom--;
    }
    if (left <= right) {
      for (let i = bottom; i >= top; i--) result.push(matrix[i][left]);
      left++;
    }
  }
  return result;
}

Time Complexity: O(m × n) — every element is visited once

Space Complexity: O(1) extra space (excluding the output array)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript