Spiral Matrix

35 min · spiralOrder()

Imagine tracing the edge of a photo, then tracing the smaller photo left inside it.

Given an m x n integer matrix, return every value in spiral order. Start at the top-left cell, move right across the top, down the right side, left across the bottom, and up the left side. Keep turning inward until every cell appears exactly once.

Your result is one flat array. The same movement rules apply to square, wide, tall, single-row, and single-column matrices.

Constraints

  • 1 <= m, n <= 100
  • matrix has exactly m rows, and every row has exactly n values.
  • -1_000 <= matrix[i][j] <= 1_000

Hints

Simulate the walk

Track visited cells and keep one of four directions: right, down, left, up. Turn clockwise whenever the next cell is outside the matrix or already visited.

Peel one ring at a time

The unvisited rectangle has four edges: top, right, bottom, and left. Traverse those edges in order, then move every edge one step inward.

Guard the thin leftovers

After crossing the top and right edges, check that a bottom row or left column still remains before traversing it. Those guards prevent duplicates in a single row or single column.

Follow-up

Can you produce the order with O(1) extra working space beyond the returned array?

Visible cases

Examples

Example 1

ready
Input
matrix = [
  [
    1,
    2,
    3
  ],
  [
    4,
    5,
    6
  ],
  [
    7,
    8,
    9
  ]
]
Expected
[
  1,
  2,
  3,
  6,
  9,
  8,
  7,
  4,
  5
]
Why
the outer ring comes first, followed by the center

Example 2

ready
Input
matrix = [
  [
    1,
    2,
    3,
    4
  ],
  [
    5,
    6,
    7,
    8
  ],
  [
    9,
    10,
    11,
    12
  ]
]
Expected
[
  1,
  2,
  3,
  4,
  8,
  12,
  11,
  10,
  9,
  5,
  6,
  7
]
Why
the same clockwise turns work on a wide rectangle

Example 3

ready
Input
matrix = [
  [
    5,
    6
  ],
  [
    7,
    8
  ]
]
Expected
[
  5,
  6,
  8,
  7
]
Why
a 2×2 matrix is one complete outer ring

Interview signal

Asked at

AmazonGoogleMicrosoft
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite