CodeArchon

mediumMath & GeometryMicrosoftGoogle

Spiral Reader

A field surveyor walks a rectangular garden in a spiral from the top-left and records what they pass.

Given an m×n matrix, return all elements in spiral order.

Choose approach

1
2
3
4
5
6
7
8
9
1/2
Narrationstep 1 of 2

Peeled ring; order so far: [1,2,3,6,9,8,7,4].

1def spiralOrder(matrix):
2 res = []
3 top, bot = 0, len(matrix) - 1
4 left, right = 0, len(matrix[0]) - 1
5 while top <= bot and left <= right:
6 for c in range(left, right + 1): res.append(matrix[top][c])
7 top += 1
8 for r in range(top, bot + 1): res.append(matrix[r][right])
9 right -= 1
10 if top <= bot:
11 for c in range(right, left - 1, -1): res.append(matrix[bot][c])
12 bot -= 1
13 if left <= right:
14 for r in range(bot, top - 1, -1): res.append(matrix[r][left])
15 left += 1
16 return res
Variables
top=1
bot=1
left=1
right=1

How to think about it

  1. Guard the two middle passes when a single row or column remains.
  2. 4 passes per ring.

Edge cases to catch in interview

  • Single row -> left to right.
  • Single column -> top to bottom.

Examples

Example 1[1,2,3,4,8,12,11,10,9,5,6,7]
{"grid":[[1,2,3,4],[5,6,7,8],[9,10,11,12]]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed