The Spiral Harvest
A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- medium
- Seniority
- L4
- Asked in
- Citadel
Problem
Given a 2D matrix, return all elements in spiral order starting top-left, going clockwise (right, down, left, up), layer by layer.
The snail reads the grid in its own special order.
Example 1
Input:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output:
[1,2,3,6,9,8,7,4,5]
Example 2
Input:
matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output:
[1,2,3,4,8,12,11,10,9,5,6,7]
Worked solution and explanation
Why this problem exists in real interviews
This tests boundary tracking and direction cycling in a 2D matrix. Spiral traversal requires careful management of four boundaries (top, bottom, left, right) and is a common probe for attention to detail in index manipulation.
Break down the requirements
Step 1: Initialize four boundary pointers
Set top = 0, bottom = rows - 1, left = 0, right = cols - 1. These shrink inward as layers are consumed.
Step 2: Traverse right, then down, then left, then up
After completing each direction, shrink the corresponding boundary inward by one.
Step 3: Stop when boundaries cross
The loop ends when top > bottom or left > right.
The solution
def spiral_order(matrix: list) -> list:
if not matrix or not matrix[0]:
return []
result = []
top = 0
bottom = len(matrix) - 1
left = 0
right = len(matrix[0]) - 1
while top <= bottom and left <= right:
for col in range(left, right + 1):
result.append(matrix[top][col])
top += 1
for row in range(top, bottom + 1):
result.append(matrix[row][right])
right -= 1
if top <= bottom:
for col in range(right, left - 1, -1):
result.append(matrix[bottom][col])
bottom -= 1
if left <= right:
for row in range(bottom, top - 1, -1):
result.append(matrix[row][left])
left += 1
return resultCommon follow-up questions
- How would you generate a spiral matrix instead of reading one? (Tests filling an empty matrix with values 1 to m*n in spiral order.)
- What if the matrix is 1xN or Nx1? (Tests that single-row and single-column edge cases are handled by the boundary checks.)
- How would you traverse in counter-clockwise spiral order? (Tests reversing the direction cycle: down, right, up, left.)