Skip to content
AI360Xpert
Beta
Difficulty: MediumMath & Geometry

Spiral Matrix

Problem in Plain English

Collect every element of an m x n matrix in clockwise spiral order, starting at the top-left corner and winding inward layer by layer.

Problem Statement

Given an m x n matrix, return all of its elements in spiral order: start at the top-left corner, walk right across the top row, down the right column, left across the bottom row, and up the left column, then repeat one layer deeper until every cell is collected.

Single rows, single columns, and non-square shapes all spiral the same way; the walk simply stops when the boundaries cross.

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]

Walk right through [1, 2, 3], down through [6, 9], left through [8, 7], and up through [4]. The only unvisited cell is the center 5, which completes the result.

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]

The outer lap collects ten cells, leaving the inner row segment [6, 7].

Example 3

Input
matrix = [[-100, 0, 100]]
Output
[-100, 0, 100]

There is only one row, so the initial rightward pass collects every cell. The bottom-row pass must be skipped instead of appending the same values again. Values do not determine when the walk turns.

Example 4

Input
matrix = [[1], [2], [3]]
Output
[1, 2, 3]

The top-row pass collects 1, then the right-column pass collects 2 and 3. There is no separate left column left to visit, so the upward pass is skipped.

Intuition

A spiral peels the outside of a rectangle before entering the next rectangle. In Example 1, the perimeter gives [1, 2, 3, 6, 9, 8, 7, 4], then the center gives 5. You can remember each visited position and turn right when the next cell is blocked. Because the remaining cells always form an inner rectangle, four boundary indices can replace that entire visited grid. Shrink each boundary after walking its side, and guard the return sides when a thin rectangle has already been consumed.

Approaches

Visited Simulation

Solution Details

Reveal Visited Simulation: intuition, complexity, and code

Hints

Hint 1
Trace Example 1 by hand and mark when the walk turns: each turn happens at an edge or an already collected cell.
Hint 2
Simulate with a facing direction plus a visited grid, or fence the unvisited rectangle with four walls and walk it lap by lap.
Hint 3
After each side, pull its wall inward, and re-check that the walls have not crossed before walking the bottom row or left column: single rows and columns skip those sides.

Edge Cases

  • A 1 by 1 matrix returns its one value; the simulation stops before trying another move.
  • A single row such as Example 3 is collected entirely by the top pass. The right and left ranges are empty, and the bottom guard fails.
  • A single column such as Example 4 is collected by the top and right passes. The bottom range is empty, and the left guard fails.
  • A non-square inner layer can be a row segment, as in Example 2, or a column segment such as a 4 by 3 matrix. Crossing guards apply on every lap.
  • Duplicate values, zeros, negatives and extrema are ordinary data. Track positions rather than using values as visited markers.

Common Mistakes and Interview Tips

  • Walking bottom and left unconditionally duplicates positions when an inner layer is a single row or column. Re-check the corresponding bounds after the earlier sides shrink.
  • Moving a boundary before traversing its own side skips that side. Shrink it after collection but before walking the adjacent side.
  • Using strict inequalities for inclusive wall ranges skips endpoints. Use inclusive traversal bounds and both non-crossed pairs for the outer while condition.
  • Using a shared visited row, such as Python [[False] * n] * m or JavaScript fill(new Array(n)), aliases flags across rows. Allocate each visited row separately.
  • Treating repeated values as already visited loses cells. The simulation stores coordinate flags and marks each cell immediately after appending.
  • Interview tip: distinguish O(1) auxiliary boundary storage from the mandatory O(m times n) output. Explain the two crossing guards using both one-row and one-column examples.

Key Takeaway

Fencing the unvisited region with moving walls turns fiddly grid walks into four straight loops plus crossing checks.