Layer-by-Layer Matrix Traversal Without Extra Storage
Arrays & HashingAuto-graded · 24 test casesLast updated
Tests boundary-tracking traversal under strict space and immutability constraints, requiring careful handling of single-row and single-column edge cases.
You are given an m x n matrix of integers. Extract all elements by traversing the matrix in a clockwise spiral pattern, starting from the top-left corner and moving inward layer by layer.
The traversal proceeds as follows: begin by moving right across the top edge, then down along the right edge, then left across the bottom edge, then up along the left edge. This completes one rectangular layer. Continue spiraling inward, repeating this pattern on successively smaller rectangles until every cell has been collected exactly once.
You must satisfy two additional constraints:
- Constant extra space: Beyond the output list, use only O(1) additional memory. You cannot allocate a visited matrix or a set to track which cells have been processed.
- Read-only input: The original matrix must remain unchanged. You cannot modify cells, even temporarily, to mark them as visited.
Function Signature
def collect_spiral(matrix: list[list[int]]) -> list[int]:
Rules
- Every cell is included in the output exactly once.
- When the remaining unvisited region forms a single row, read it from left to right.
- When the remaining unvisited region forms a single column, read it from top to bottom.
- The input matrix must be identical before and after the function call.
Constraints
1 <= m <= 100(number of rows)1 <= n <= 100(number of columns per row)-1000 <= matrix[i][j] <= 1000
Examples
Example 1
Input: collect_spiral([[7, 1, 4], [3, 9, 2], [6, 5, 8]])
Output: [7, 1, 4, 2, 8, 5, 6, 3, 9]
Example 2
Input: collect_spiral([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]])
Output: [1, 2, 3, 4, 5, 10, 15, 14, 13, 12, 11, 6, 7, 8, 9]
Example 3
Input: collect_spiral([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
Output: [1, 2, 3, 6, 9, 12, 11, 10, 7, 4, 5, 8]
Hints
Hint 1
Track four boundaries (top, bottom, left, right) that define the current unvisited rectangle and shrink them inward after processing each layer.
Hint 2
Before processing a full rectangular ring, check whether the remaining region has collapsed to a single row or single column to avoid reading cells twice.
Hint 3
Assign each corner cell to exactly one of the four directional sweeps to prevent duplication—for instance, let the top sweep own both top corners, and let subsequent sweeps exclude corners already taken.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to maintain four integer boundaries that define the currently unvisited rectangular region: top, bot, left, and right. Each iteration processes one complete rectangular ring by sweeping along its four edges in clockwise order, then shrinks all boundaries inward by one step.
Four-Edge Sweep
Each ring consists of four directional segments:
- Top edge: Move left to right from
(top, left)to(top, right), collecting both corner cells. - Right edge: Move downward from
(top+1, right)to(bot, right). This excludes the top-right corner (already collected) and includes the bottom-right corner. - Bottom edge: Move right to left from
(bot, right-1)to(bot, left). This excludes the bottom-right corner (already collected) and includes the bottom-left corner. - Left edge: Move upward from
(bot-1, left)to(top+1, left). This excludes both corners (already collected).
By assigning corners carefully, each cell on the ring is collected exactly once.
Handling Degenerate Cases
Before processing the four-segment ring, check whether the remaining region has collapsed:
- If
top == bot, only a single row remains. Collect it left to right and terminate. - If
left == right, only a single column remains. Collect it top to bottom and terminate.
Without these checks, a single row would be traversed once left-to-right by segment 1, then again right-to-left by segment 3, duplicating cells.
Why It Works
For a rectangle of height h and width w (where h ≥ 2 and w ≥ 2), the four segments contain w, h-1, w-1, and h-2 cells respectively, totaling 2w + 2h - 4—exactly the perimeter cell count. The segments cover disjoint index ranges, so every border cell is emitted once.
After each iteration, the boundaries are tightened by 1 on all sides, preserving the invariant that they describe precisely the unvisited rectangle. The loop terminates when top > bot or left > right, meaning all cells have been processed.
The algorithm never writes to the input matrix—it only reads cell values—satisfying the immutability constraint. Aside from the output list, only four boundary variables and loop indices are used, achieving O(1) extra space.
Complexity
- Time: O(m·n). Every cell is visited exactly once with constant work per cell.
- Space: O(1) extra space beyond the output list. Only boundary indices and loop counters are maintained.
Full Solution
def collect_spiral(matrix: list[list[int]]) -> list[int]:
m, n = len(matrix), len(matrix[0])
top, bot, left, right = 0, m - 1, 0, n - 1
result = []
while top <= bot and left <= right:
# Degenerate case: single row remaining
if top == bot:
for col in range(left, right + 1):
result.append(matrix[top][col])
break
# Degenerate case: single column remaining
if left == right:
for row in range(top, bot + 1):
result.append(matrix[row][left])
break
# Traverse top edge (left to right, including both corners)
for col in range(left, right + 1):
result.append(matrix[top][col])
# Traverse right edge (top to bottom, excluding top corner)
for row in range(top + 1, bot + 1):
result.append(matrix[row][right])
# Traverse bottom edge (right to left, excluding right corner)
for col in range(right - 1, left - 1, -1):
result.append(matrix[bot][col])
# Traverse left edge (bottom to top, excluding both corners)
for row in range(bot - 1, top, -1):
result.append(matrix[row][left])
# Shrink boundaries inward
top += 1
bot -= 1
left += 1
right -= 1
return result