📖 2 min read
Last updated on

Spiral Matrix — Coding Interview Walkthrough


You’re in a coding interview. The interviewer says: “Traverse an m × n matrix in spiral order.” There’s no clever algorithm — just careful boundary management. You shrink your traversal window after each pass (right, down, left, up) and stop when the boundaries cross.


The Problem

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

Example

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]

Already comfortable with the solution? Practice it in a mock interview →

3×3 matrix with spiral traversal numbered 1-9: right across top, down right column, left across bottom, up left column, center last.

What Interviewers Are Actually Testing

SkillWhat Interviewers Observe
Boundary trackingDo you track top, bottom, left, right and shrink them?
Loop terminationDo you check boundaries before left/up passes?
Non-square matrixDoes your solution handle m ≠ n, single row, single column?

Step 1: The Key Insight

Maintain four boundaries: top, bottom, left, right. After traversing each edge, shrink the corresponding boundary inward. Check boundaries before the left and up passes to handle single-row or single-column remainders.


Python Implementation

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 result

Time & Space Complexity

AspectComplexity
TimeO(m × n) — every cell visited once
SpaceO(1) extra (not counting output)

Common Interview Mistakes

  1. Not checking boundaries before left/up passes. If only one row remains after the right pass, the left pass duplicates cells.
  2. Off-by-one in ranges. range(left, right + 1) for right, range(right, left - 1, -1) for left.
  3. Hardcoding for square matrices. Must handle m ≠ n. Test with 1×4 and 4×1.

What a Strong Candidate Sounds Like

“Four boundary variables: top, bottom, left, right. Each iteration traverses one layer: right, down, left, up. After each pass I shrink the boundary. I guard left/up passes with boundary checks for single-row/column cases. O(m×n) time, O(1) extra space.”



Practice This in a Mock Interview

Start a mock interview for Spiral Matrix on Intervu.


Further reading:

Practice Like It's the Real Interview

Get instant feedback on your approach, communication, and code — powered by AI.

Start a Mock Interview →