KatInterview

Layer-by-Layer Matrix Traversal Without Extra Storage

Arrays & HashingAuto-graded · 24 test cases
MediumAuto-gradedArrays & Hashingmatrixtraversalconstant-space

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

  1. 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.
  2. 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.