medium +20 pts

Spiral Matrix Traversal

Given a 2D matrix, return all elements in spiral order (clockwise from top-left).

Write a function `spiral_traverse(matrix)` that accepts a rectangular 2D list of integers and returns a list of all its elements in clockwise spiral order, starting from the top-left corner and moving right, then down, then left, then up, and repeating this pattern until every element has been visited. - The matrix is guaranteed to be rectangular: every row has the same length, and the matrix may be empty (length 0). - If the matrix is empty, return an empty list. - The function should NOT modify the input matrix. Your implementation must be efficient enough to handle matrices with up to 200 rows and 200 columns.

Constraints

0 <= len(matrix) <= 200 0 <= len(matrix[i]) <= 200 (for all rows; all rows have same length) Elements are integers between -10^6 and 10^6. Time complexity O(n) where n is total number of elements. Space complexity O(n) for output.

Example

>>> spiral_traverse([[1,2,3],[4,5,6],[7,8,9]])
[1, 2, 3, 6, 9, 8, 7, 4, 5]
>>> spiral_traverse([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
>>> spiral_traverse([])
[]
20 points ~25 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Think of maintaining four boundaries: top, bottom, left, right.
Loop while top <= bottom and left <= right, in each iteration traverse four edges.
After each edge, adjust the corresponding boundary inward.
Be careful when only one row or one column remains to avoid duplicate traversal.
Empty matrix must return an empty list.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.