Peel a Grid Layer by Layer in a Clockwise Spiral
Arrays & HashingAuto-graded · 22 test casesLast updated
Flatten a rectangular grid into a list by walking its perimeter clockwise inward, using shrinking boundaries and guards so single leftover rows or columns are not read twice.
Peel a Grid Layer by Layer in a Clockwise Spiral
You are given a rectangular grid of integers, stored as a list of rows. Produce a flat list of all its values in the order you would meet them when walking a clockwise spiral inward.
Task
Write a function spiral_flatten(grid) that returns the values in this order:
- Start at the top-left cell and move right along the top row until the last column.
- Turn clockwise: go down the last column, then left along the bottom row, then up the first column.
- Having completed one full loop around the outside, continue the same pattern on the unvisited inner portion of the grid.
- Stop once every cell has been output exactly once.
If the grid is empty, return an empty list. The grid must not be modified.
Details
- Each cell appears exactly once in the output, including when the unvisited region shrinks to a single row or a single column. In that case the walk must not go back over cells it has just output.
- A grid with no rows, or whose rows contain no columns, gives
[]. - All rows have the same length.
Constraints
0 <= rows, columns <= 200(the total number of cells is at most40000)- Cell values are integers that fit in a normal Python
int. - Aim for
O(rows * columns)time and extra space beyond the returned list that does not grow with the grid dimensions (no separate "visited" grid). - Do not modify the input.
Examples
Example 1
Input: spiral_flatten([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
Example 2
Input: spiral_flatten([[1, 2, 3, 4]])
Output: [1, 2, 3, 4]
Example 3
Input: spiral_flatten([[1], [2], [3], [4]])
Output: [1, 2, 3, 4]
Example 4
Input: spiral_flatten([[1, 2], [3, 4], [5, 6]])
Output: [1, 2, 4, 6, 5, 3]
Hints
Hint 1
Keep four inclusive boundaries (top, bottom, left, right) describing the part of the grid you have not yet output. Each side you walk lets you move one boundary inward.
Hint 2
One loop iteration walks the four sides in order: top row, right column, bottom row, left column. After the first two sides the remaining region may have collapsed.
Hint 3
Before walking the bottom row, check that a row is still left (top <= bottom). Before walking the left column, check that a column is still left (left <= right). These checks prevent duplicates for single-row and single-column leftovers. Also handle `[]` and `[[]]` up front.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the not-yet-output part of the grid as a rectangle described by four inclusive boundaries: top, bottom, left, right. Each pass of the main loop removes one outer layer of that rectangle, walking its sides clockwise:
- Top row from
lefttoright, thentop += 1. - Right column from
toptobottom, thenright -= 1. - Bottom row from
righttoleft, thenbottom -= 1, but only iftop <= bottom. - Left column from
bottomtotop, thenleft += 1, but only ifleft <= right.
The loop continues while top <= bottom and left <= right, i.e. while at least one unvisited cell remains. The boundaries take the place of a visited matrix, so extra space stays constant.
Why it is correct
Invariant: at the start of each iteration, the cells already output are exactly those outside the rectangle [top..bottom] x [left..right], and they were output in spiral order. Each side walked outputs exactly one edge of the current rectangle and then moves the matching boundary past it, so the invariant is preserved.
The guards matter once the rectangle collapses:
- If the top row was the last remaining row, then after step 1 we have
top > bottom. Without the guard on step 3, the bottom row would be walked again in reverse, duplicating values. - If the right column was the last remaining column, then after step 2 we have
left > right. Without the guard on step 4, that column would be walked again upward.
Step 2 needs no explicit guard, because range(top, bottom + 1) is empty when no rows remain. The loops in steps 3 and 4 are also empty in their other degenerate case. The loop terminates because top and right move inward every iteration, so the rectangle strictly shrinks and each cell is output exactly once.
Empty grids ([] or [[]]) are handled by an early return.
Complexity
- Time:
O(rows * columns), since each cell is appended once. - Space:
O(1)auxiliary (four boundary integers and loop variables), excluding the returned list.
Reference solution
from typing import List
def spiral_flatten(grid: List[List[int]]) -> List[int]:
if not grid or not grid[0]:
return []
top, bottom = 0, len(grid) - 1
left, right = 0, len(grid[0]) - 1
out = []
while top <= bottom and left <= right:
# Top side, left to right
for c in range(left, right + 1):
out.append(grid[top][c])
top += 1
# Right side, top to bottom
for r in range(top, bottom + 1):
out.append(grid[r][right])
right -= 1
# Bottom side, right to left (only if a row remains)
if top <= bottom:
for c in range(right, left - 1, -1):
out.append(grid[bottom][c])
bottom -= 1
# Left side, bottom to top (only if a column remains)
if left <= right:
for r in range(bottom, top - 1, -1):
out.append(grid[r][left])
left += 1
return out