Skip to main content

🟨 Spiral Matrix (#54)

📋 Problem Statement

Given an m x n matrix, return all elements of the matrix in spiral order.

💡 Examples

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]

🔑 Key Insights & Approach

Core Observation: Process layer by layer using four boundaries (top, right, bottom, left).

Why Layer by Layer?

  • O(m * n) time, O(1) extra space
  • Track and shrink boundaries
  • Process: right → down → left → up

Pattern: "Spiral Traversal" with boundary tracking.

🐍 Solution: Python

Approach: Boundary Tracking

Time Complexity: O(m * n) | Space Complexity: O(1)

from typing import List

class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
result = []
if not matrix:
return result

top, bottom = 0, len(matrix) - 1
left, right = 0, len(matrix[0]) - 1

while top <= bottom and left <= right:
# Right
for col in range(left, right + 1):
result.append(matrix[top][col])
top += 1

# Down
for row in range(top, bottom + 1):
result.append(matrix[row][right])
right -= 1

# Left (if still rows)
if top <= bottom:
for col in range(right, left - 1, -1):
result.append(matrix[bottom][col])
bottom -= 1

# Up (if still cols)
if left <= right:
for row in range(bottom, top - 1, -1):
result.append(matrix[row][left])
left += 1

return result

🔵 Solution: Golang

Approach: Boundary Tracking

Time Complexity: O(m * n) | Space Complexity: O(1)

func spiralOrder(matrix [][]int) []int {
if len(matrix) == 0 {
return []int{}
}

result := []int{}
top, bottom := 0, len(matrix)-1
left, right := 0, len(matrix[0])-1

for top <= bottom && left <= right {
for col := left; col <= right; col++ {
result = append(result, matrix[top][col])
}
top++

for row := top; row <= bottom; row++ {
result = append(result, matrix[row][right])
}
right--

if top <= bottom {
for col := right; col >= left; col-- {
result = append(result, matrix[bottom][col])
}
bottom--
}

if left <= right {
for row := bottom; row >= top; row-- {
result = append(result, matrix[row][left])
}
left++
}
}

return result
}

📚 References