Skip to content
mlmentorship

Spiral Matrix

Return matrix values in spiral order.

Published · 9 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Spiral Matrix

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A rectangular integer matrix, possibly with an empty dimension. Output. Return a flat list of all cell values in clockwise spiral order. Rules. Begin at the top-left and initially move right, following successive outer boundaries inward. Visit every cell exactly once, including repeated or negative values. Leave the matrix unchanged. Empty dimensions return []; ragged rows are outside the contract. Example. [[1, 2, 3], [4, 5, 6], [7, 8, 9]] returns [1, 2, 3, 6, 9, 8, 7, 4, 5]. A one-row matrix [[1, 2, 3]] returns [1, 2, 3] without repeated cells.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Read one side of the current rectangle at a time, shrink that boundary, and guard sides that may have disappeared.

Problem trace

Recheck the remaining boundaries before traversing another edge

Input and goalReturn matrix values in spiral order.
Initialize the outer rectangleBounds are top=0, bottom=2, left=0, right=3. The answer starts empty.
1read cursor23456789101112
boundariestop=0 bottom=2 left=0 right=3answer[]
read cursor
(0, 0)
boundaries
top=0 bottom=2 left=0 right=3
answer
[]

Recognize it
Use boundary peeling when a rectangular grid must be traversed layer by layer around its perimeter in directional order.
Keep true
At each while-loop entry, every cell outside top..bottom and left..right has been emitted exactly once, and every unvisited cell lies inside that closed rectangle.
Reuse it
For perimeter traversals, represent remaining work as explicit inclusive bounds, consume one edge, shrink it immediately, and guard later edges because earlier moves may collapse the region.
Bounds are top=0, bottom=2, left=0, right=3. The answer starts empty. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why must the bottom-edge check be skipped after the last inner top row is consumed?
Full interview answer 9 min read
Reading depth

List every matrix cell in clockwise spiral order, beginning at the top-left corner.

Problem

Input. A rectangular integer matrix, possibly with an empty dimension.

Output. Return a flat list of all cell values in clockwise spiral order.

Rules. Begin at the top-left and initially move right, following successive outer boundaries inward. Visit every cell exactly once, including repeated or negative values. Leave the matrix unchanged. Empty dimensions return []; ragged rows are outside the contract.

Example. [[1, 2, 3], [4, 5, 6], [7, 8, 9]] returns [1, 2, 3, 6, 9, 8, 7, 4, 5]. A one-row matrix [[1, 2, 3]] returns [1, 2, 3] without repeated cells.

Picture

For [[1,2,3], [4,5,6]], read top 1,2,3, right 6, then bottom 5,4. The unread bounds have crossed, so stop.

Problem trace

Separate one-row remainder: no second sweep after the rectangle disappears

Worked example: a crossed boundary prevents revisiting a one-row remainderFor a single row (1,2,3), the top traversal consumes every cell. The bottom traversal must be skipped after top passes bottom.The top sweep already consumes theone-row remainderEmit one, two, three across the top123Bottom stays at row zero.Top advances to row one, beyond thatbottom.Top has passed bottom; no cellsremain to sweep.
Read it this way: For a single row (1,2,3), the top traversal consumes every cell. The bottom traversal must be skipped after top passes bottom. Which already-emitted values would be duplicated if the bottom sweep ignored top exceeding bottom?
Reference drawing

Problem trace

Recheck the remaining boundaries before traversing another edge

Worked example: a crossed boundary prevents revisiting a one-row remainderFor a single row (1,2,3), the top traversal consumes every cell. The bottom traversal must be skipped after top passes bottom.The top sweep already consumes theone-row remainderEmit one, two, three across the top123Bottom stays at row zero.Top advances to row one, beyond thatbottom.Top has passed bottom; no cellsremain to sweep.
Execution trace
Input and goalReturn matrix values in spiral order.
Initialize the outer rectangleBounds are top=0, bottom=2, left=0, right=3. The answer starts empty.
1read cursor23456789101112
boundariestop=0 bottom=2 left=0 right=3answer[]
read cursor
(0, 0)
boundaries
top=0 bottom=2 left=0 right=3
answer
[]

Recognize it
Use boundary peeling when a rectangular grid must be traversed layer by layer around its perimeter in directional order.
Keep true
At each while-loop entry, every cell outside top..bottom and left..right has been emitted exactly once, and every unvisited cell lies inside that closed rectangle.
Reuse it
For perimeter traversals, represent remaining work as explicit inclusive bounds, consume one edge, shrink it immediately, and guard later edges because earlier moves may collapse the region.
Bounds are top=0, bottom=2, left=0, right=3. The answer starts empty. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why must the bottom-edge check be skipped after the last inner top row is consumed?
Read it this way: For a single row (1,2,3), the top traversal consumes every cell. The bottom traversal must be skipped after top passes bottom. Which already-emitted values would be duplicated if the bottom sweep ignored top exceeding bottom?

Each completed side is removed from the unread rectangle before another side is visited. The bottom and left guards prevent revisiting cells after a thin rectangle disappears.

Code

def spiral_order(matrix: list[list[int]]) -> list[int]:
   if not matrix or not matrix[0]:
      return []

   answer = []
   top, bottom = 0, len(matrix) - 1
   left, right = 0, len(matrix[0]) - 1

   while top <= bottom and left <= right:
      answer.extend(matrix[top][left : right + 1])
      top += 1

      for row in range(top, bottom + 1):
         answer.append(matrix[row][right])
      right -= 1

      if top <= bottom:
         answer.extend(reversed(matrix[bottom][left : right + 1]))
         bottom -= 1
      if left <= right:
         for row in range(bottom, top - 1, -1):
            answer.append(matrix[row][left])
         left += 1

   return answer

Cost: cell visits and output storage, plus temporary slicing space. The four bounds themselves use constant state.

Change the Requirement

Stream Coordinates Without Slices

New task: Yield positions lazily using constant auxiliary state.

Picture and change: Keep the rectangle but replace copied rows with indexed visits.

Code: Nonnegative integer dimensions are required.

def spiral_positions(rows: int, cols: int):
   if rows < 0 or cols < 0:
      raise ValueError("dimensions must be nonnegative")
   top, bottom, left, right = 0, rows - 1, 0, cols - 1
   while top <= bottom and left <= right:
      for col in range(left, right + 1):
         yield top, col
      top += 1
      for row in range(top, bottom + 1):
         yield row, right
      right -= 1
      if top <= bottom:
         for col in range(right, left - 1, -1):
            yield bottom, col
         bottom -= 1
      if left <= right:
         for row in range(bottom, top - 1, -1):
            yield row, left
         left += 1

Check: list(spiral_positions(1, 3)) returns [(0,0), (0,1), (0,2)] once each.

Use when: Consumers need positions incrementally. Exhaustion costs time; storing yielded positions is the consumer’s choice.

Reverse Traversal Orientation

New task: Visit counterclockwise, still starting at top-left.

Picture and change: Transposition exchanges horizontal and vertical movements, reversing orientation.

Code: Reuse the complete reference on a transposed copy.

def spiral_counterclockwise(matrix: list[list[int]]) -> list[int]:
   if not matrix or not matrix[0]:
      return []
   transposed = [
      [matrix[row][col] for row in range(len(matrix))]
      for col in range(len(matrix[0]))
   ]
   return spiral_order(transposed)

Check: [[1,2,3], [4,5,6]] produces [1,4,5,6,3,2].

Use when: The initial direction is down rather than right. The copy adds workspace.

Reconstruct

What happens without the bottom-side guard?

Reasoned answer

For [[1,2,3]], consuming the top row leaves top > bottom. Reading the bottom anyway would append previously visited cells. The guard checks that a side still belongs to the unread rectangle.