Bird
Raised Fist0
DSA Pythonprogramming

Spiral Matrix Traversal in DSA Python

Choose your learning style10 modes available
Mental Model
We walk around the edges of the matrix in a circle, then move inward layer by layer until all elements are visited.
Analogy: Imagine peeling an onion layer by layer, starting from the outer skin and moving towards the center, collecting all the layers as you go.
1 -> 2 -> 3 -> 4
↓           ↑
5           6
↓           ↑
7 ← 8 ← 9 ← 10

We start at top-left, move right, then down, then left, then up, shrinking the boundaries each time.
Dry Run Walkthrough
Input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Goal: Traverse the matrix in spiral order and collect elements in that sequence.
Step 1: Traverse top row from left to right
Visited: 1 -> 2 -> 3
Remaining matrix edges to traverse
Why: Start from the top row to begin the outer layer traversal
Step 2: Traverse right column from top to bottom (excluding already visited top row)
Visited: 1 -> 2 -> 3 -> 6 -> 9
Remaining edges: bottom row and left column
Why: Move down the right edge to continue the spiral
Step 3: Traverse bottom row from right to left (excluding already visited right column)
Visited: 1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7
Remaining edge: left column
Why: Move left along the bottom edge to complete the outer layer
Step 4: Traverse left column from bottom to top (excluding already visited bottom and top rows)
Visited: 1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4
Remaining center element
Why: Move up the left edge to finish the outer layer
Step 5: Move inward and traverse the remaining center element
Visited: 1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4 -> 5
Why: All outer layers done, now visit the center
Result:
1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4 -> 5
Annotated Code
DSA Python
from typing import List

class SpiralMatrix:
    def spiral_order(self, matrix: List[List[int]]) -> List[int]:
        result = []
        if not matrix or not matrix[0]:
            return result

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

        while left <= right and top <= bottom:
            # Traverse from left to right on the top row
            for col in range(left, right + 1):
                result.append(matrix[top][col])
            top += 1  # move top boundary down

            # Traverse from top to bottom on the right column
            for row in range(top, bottom + 1):
                result.append(matrix[row][right])
            right -= 1  # move right boundary left

            if top <= bottom:
                # Traverse from right to left on the bottom row
                for col in range(right, left - 1, -1):
                    result.append(matrix[bottom][col])
                bottom -= 1  # move bottom boundary up

            if left <= right:
                # Traverse from bottom to top on the left column
                for row in range(bottom, top - 1, -1):
                    result.append(matrix[row][left])
                left += 1  # move left boundary right

        return result

if __name__ == "__main__":
    matrix = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]
    spiral = SpiralMatrix()
    result = spiral.spiral_order(matrix)
    print(" -> ".join(map(str, result)))
while left <= right and top <= bottom:
continue spiral traversal while boundaries are valid
for col in range(left, right + 1): result.append(matrix[top][col])
traverse top row from left to right
top += 1
shrink top boundary down after traversal
for row in range(top, bottom + 1): result.append(matrix[row][right])
traverse right column from top to bottom
right -= 1
shrink right boundary left after traversal
if top <= bottom: for col in range(right, left - 1, -1): result.append(matrix[bottom][col])
traverse bottom row from right to left if still valid
bottom -= 1
shrink bottom boundary up after traversal
if left <= right: for row in range(bottom, top - 1, -1): result.append(matrix[row][left])
traverse left column from bottom to top if still valid
left += 1
shrink left boundary right after traversal
OutputSuccess
1 -> 2 -> 3 -> 6 -> 9 -> 8 -> 7 -> 4 -> 5
Complexity Analysis
Time: O(m*n) because every element in the m by n matrix is visited exactly once
Space: O(m*n) for the output list that stores all elements of the matrix
vs Alternative: Compared to naive repeated scanning, this approach visits each element once without revisiting, making it efficient
Edge Cases
Empty matrix
Returns empty list immediately
DSA Python
if not matrix or not matrix[0]:
    return result
Single row matrix
Traverses left to right only
DSA Python
while left <= right and top <= bottom:
Single column matrix
Traverses top to bottom only
DSA Python
while left <= right and top <= bottom:
When to Use This Pattern
When you need to visit all elements of a matrix in a circular, inward pattern, use spiral traversal to systematically peel layers.
Common Mistakes
Mistake: Not updating boundaries correctly causing infinite loops or repeated elements
Fix: After each edge traversal, update the corresponding boundary (top, bottom, left, right) to move inward
Mistake: Not checking boundary conditions before traversing bottom row or left column
Fix: Add checks like if top <= bottom and if left <= right before those traversals
Summary
It collects matrix elements in a spiral order starting from the outer layer moving inward.
Use it when you want to read or print matrix elements in a circular pattern.
The key is to keep track of four boundaries and move them inward after each edge traversal.

Practice

(1/5)
1. What is the main idea behind Spiral Matrix Traversal?
easy
A. Traverse the matrix in a spiral order starting from the top-left corner
B. Traverse the matrix row by row from left to right only
C. Traverse the matrix column by column from top to bottom only
D. Traverse the matrix diagonally from top-left to bottom-right

Solution

  1. Step 1: Understand traversal pattern

    Spiral traversal means moving around the matrix edges and gradually moving inward in a circular pattern.
  2. Step 2: Identify starting point and direction

    It starts at the top-left corner and moves right, then down, then left, then up, repeating until all elements are visited.
  3. Final Answer:

    Traverse the matrix in a spiral order starting from the top-left corner -> Option A
  4. Quick Check:

    Spiral traversal = circular edge-wise movement [OK]
Hint: Think of peeling an onion layer by layer in a circle [OK]
Common Mistakes:
  • Confusing spiral with row-wise or column-wise traversal
  • Starting traversal from the wrong corner
  • Ignoring direction changes after each edge
2. Which of the following Python code snippets correctly initializes the boundaries for spiral traversal of a matrix named matrix?
easy
A. top = 1; bottom = len(matrix); left = 1; right = len(matrix[0])
B. top = 0; bottom = len(matrix) - 1; left = 0; right = len(matrix[0]) - 1
C. top = 0; bottom = len(matrix); left = 0; right = len(matrix[0])
D. top = 1; bottom = len(matrix) - 1; left = 1; right = len(matrix[0]) - 1

Solution

  1. Step 1: Understand matrix boundaries

    For a matrix, top and left start at 0, bottom is last row index (length - 1), right is last column index (length - 1).
  2. Step 2: Check each option

    top = 0; bottom = len(matrix) - 1; left = 0; right = len(matrix[0]) - 1 correctly sets top=0, bottom=len(matrix)-1, left=0, right=len(matrix[0])-1 which matches the matrix indices.
  3. Final Answer:

    top = 0; bottom = len(matrix) - 1; left = 0; right = len(matrix[0]) - 1 -> Option B
  4. Quick Check:

    Boundary indices start at 0 and end at length-1 [OK]
Hint: Remember Python indexing starts at 0, so subtract 1 for last index [OK]
Common Mistakes:
  • Using length instead of length - 1 for bottom and right
  • Starting top or left at 1 instead of 0
  • Mixing row and column lengths
3. What is the output of the following Python code?
matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]
result = []
top, bottom = 0, 2
left, right = 0, 2
while top <= bottom and left <= right:
    for i in range(left, right + 1):
        result.append(matrix[top][i])
    top += 1
    for i in range(top, bottom + 1):
        result.append(matrix[i][right])
    right -= 1
    for i in range(right, left - 1, -1):
        result.append(matrix[bottom][i])
    bottom -= 1
    for i in range(bottom, top - 1, -1):
        result.append(matrix[i][left])
    left += 1
print(result)
medium
A. [1, 2, 3, 6, 9, 8, 7, 4, 5]
B. [1, 2, 3, 6, 9, 8, 7, 5, 4]
C. [1, 2, 3, 6, 9, 7, 8, 4, 5]
D. [1, 2, 3, 6, 9, 8, 7, 4]

Solution

  1. Step 1: Traverse top row left to right

    Elements: 1, 2, 3 added to result.
  2. Step 2: Traverse right column top to bottom

    Elements: 6, 9 added to result.
  3. Step 3: Traverse bottom row right to left

    Elements: 8, 7 added to result.
  4. Step 4: Traverse left column bottom to top

    Element: 4 added to result.
  5. Step 5: Inner layer traversal

    Only element 5 remains, added last.
  6. Final Answer:

    [1, 2, 3, 6, 9, 8, 7, 4, 5] -> Option A
  7. Quick Check:

    Spiral order = [1,2,3,6,9,8,7,4,5] [OK]
Hint: Follow edges clockwise, then move inward layer by layer [OK]
Common Mistakes:
  • Skipping the last inner element
  • Repeating elements or missing elements
  • Wrong direction in bottom or left traversal
4. The following code attempts spiral traversal but produces an error. What is the main bug?
matrix = [[1,2,3],[4,5,6],[7,8,9]]
top, bottom = 0, 2
left, right = 0, 2
result = []
while top <= bottom and left <= right:
    for i in range(left, right + 1):
        result.append(matrix[top][i])
    top += 1
    for i in range(top, bottom + 1):
        result.append(matrix[i][right])
    right -= 1
    for i in range(right, left - 1, -1):
        result.append(matrix[bottom][i])
    bottom -= 1
    for i in range(bottom, top - 1, -1):
        result.append(matrix[i][left])
    left += 1
print(result)
medium
A. The code uses incorrect range in the first for loop
B. The code uses wrong indices for left and right boundaries
C. The code does not check if top <= bottom before traversing bottom row
D. The code misses incrementing the left boundary

Solution

  1. Step 1: Analyze loop conditions

    The while loop checks top <= bottom and left <= right before each full cycle.
  2. Step 2: Identify missing checks inside loop

    After updating top and right, the code traverses bottom row and left column without checking if top <= bottom or left <= right again, causing index errors when boundaries cross.
  3. Final Answer:

    The code does not check if top <= bottom before traversing bottom row -> Option C
  4. Quick Check:

    Boundary checks needed before each edge traversal [OK]
Hint: Check boundaries before each edge traversal inside the loop [OK]
Common Mistakes:
  • Assuming one boundary check per loop is enough
  • Not updating boundaries correctly
  • Ignoring empty or single-row/column matrices
5. Given a rectangular matrix of size 3x4:
matrix = [
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9, 10, 11, 12]
]

What is the spiral traversal output?
hard
A. [1, 2, 3, 4, 8, 12, 11, 10, 9, 6, 5, 7]
B. [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 7, 6]
C. ]6 ,7 ,5 ,9 ,01 ,11 ,21 ,8 ,4 ,3 ,2 ,1[
D. [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]

Solution

  1. Step 1: Traverse top row left to right

    Elements: 1, 2, 3, 4 added.
  2. Step 2: Traverse right column top to bottom

    Elements: 8, 12 added.
  3. Step 3: Traverse bottom row right to left

    Elements: 11, 10, 9 added.
  4. Step 4: Traverse left column bottom to top

    Element: 5 added.
  5. Step 5: Traverse inner row left to right

    Elements: 6, 7 added.
  6. Final Answer:

    [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7] -> Option D
  7. Quick Check:

    Spiral order covers all elements layer by layer [OK]
Hint: Follow edges clockwise, then move inward carefully for rectangular matrices [OK]
Common Mistakes:
  • Mixing order of inner elements
  • Skipping or repeating elements in inner layers
  • Confusing left column traversal direction
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard