KatInterview

Peel a Grid Layer by Layer in a Clockwise Spiral

Arrays & HashingAuto-graded · 22 test cases
MediumAuto-gradedArrays & Hashingmatrixsimulationtwo-pointers

Last 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:

  1. Start at the top-left cell and move right along the top row until the last column.
  2. Turn clockwise: go down the last column, then left along the bottom row, then up the first column.
  3. Having completed one full loop around the outside, continue the same pattern on the unvisited inner portion of the grid.
  4. 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 most 40000)
  • 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.