Spiral Matrix in Coding Interviews: A Clean Boundary Approach

Spiral Matrix in Coding Interviews: A Clean Boundary Approach

"Return all elements of an m x n matrix in spiral order" looks like a simple loop problem, but it is one of the most common places candidates lose points to off-by-one bugs. Here is a pattern that stays correct under pressure.

Keep four boundaries

Track top, bottom, left and right. Each pass walks one side and then shrinks that boundary:

  1. Walk left to right along top, then top += 1.
  2. Walk top to bottom along right, then right -= 1.
  3. If top <= bottom, walk right to left along bottom, then bottom -= 1.
  4. If left <= right, walk bottom to top along left, then left += 1.

The two if checks are the whole trick. Without them a single remaining row or column gets printed twice.

def spiral(m):
    res = []
    if not m: return res
    top, bottom, left, right = 0, len(m) - 1, 0, len(m[0]) - 1
    while top <= bottom and left <= right:
        for c in range(left, right + 1): res.append(m[top][c])
        top += 1
        for r in range(top, bottom + 1): res.append(m[r][right])
        right -= 1
        if top <= bottom:
            for c in range(right, left - 1, -1): res.append(m[bottom][c])
            bottom -= 1
        if left <= right:
            for r in range(bottom, top - 1, -1): res.append(m[r][left])
            left += 1
    return res

Test cases to say out loud

  • A 1 x n row and an n x 1 column (catches the double-print bug).
  • A 3 x 3 square (odd center element).
  • An empty matrix.

Follow-ups interviewers like

Spiral Matrix II asks you to fill 1..n^2 in spiral order: the same four-boundary loop works, writing instead of reading. Rotating an image by 90 degrees is the other classic matrix question; transpose then reverse each row, all in place.

Time is O(m*n) and extra space is O(1) beyond the output. Say both before you are asked.

If you want to rehearse problems like this with feedback while you talk through them, I work on Linkjob, an AI interview assistant (disclosure: I'm on the team).

Public Last updated: 2026-11-02 05:20:37 AM