PracticeNeetCode ↗LeetCode ↗
Given an m × n matrix, return all of its elements in spiral order — starting at the top-left, moving right, then spiraling inward.
top, bottom, left, right.top = 0, bottom = rows - 1, left = 0, right = cols - 1.top <= bottom and left <= right: walk left→right along row top, then increment top.right, then decrement right.top <= bottom, walk right→left along row bottom, then decrement bottom.left <= right, walk bottom→top along column left, then increment left. Repeat until the boundaries cross.Time: O(m · n) — Space: O(1) extra, excluding the output
def spiralOrder(matrix: list[list[int]]) -> list[int]:
result = []
top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1
while top <= bottom and left <= right:
for c in range(left, right + 1):
result.append(matrix[top][c])
top += 1
for r in range(top, bottom + 1):
result.append(matrix[r][right])
right -= 1
if top <= bottom:
for c in range(right, left - 1, -1):
result.append(matrix[bottom][c])
bottom -= 1
if left <= right:
for r in range(bottom, top - 1, -1):
result.append(matrix[r][left])
left += 1
return resultHow the solution above works, piece by piece.
top, bottom, left, right.top down. Walk the right column top → bottom, then move right left.top <= bottom, left <= right). Without these checks a single leftover row or column would be read twice.Running it on matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]: