Skip to content
BytePatterns

Spiral Order

Matrix & Grid: lesson 2 of 5

Four walls that close in after every pass.

Lesson 2 of 5 · 5 min

Spiral Order

Step 1 of 9

Four walls — top, bottom, left, right — hold the part of the board still unread.

The Idea

Do not chase a direction. Hold four walls — top, bottom, left, right — around the part still unread.

Walk the top wall left to right and push it down. Walk the right wall down and pull it in. Bottom back, left up, and repeat. The same four moves handle any rectangle; when the walls cross, you are done.

Real-World Example

Image processing walks tiles this way to keep a cache warm, and screen-capture tools scan outward in rings to find the changed region quickly. The pattern shows up in interviews because it rewards a clean invariant instead of clever index arithmetic.

The Code

def spiral(g):
    top, bottom, left, right = 0, len(g) - 1, 0, len(g[0]) - 1
    out = []
    while top <= bottom and left <= right:
        out += [g[top][c] for c in range(left, right + 1)]; top += 1
        out += [g[r][right] for r in range(top, bottom + 1)]; right -= 1
        if top <= bottom:                    # that row may already be spent
            out += [g[bottom][c] for c in range(right, left - 1, -1)]; bottom -= 1
        if left <= right:
            out += [g[r][left] for r in range(bottom, top - 1, -1)]; left += 1
    return out

print(spiral([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))   # [1, 2, 3, 6, 9, 8, 7, 4, 5]

Python

Your turn

What does this print?

print(spiral([[1, 2], [3, 4]]))

Mini quiz

1 / 3

What does the loop keep track of?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.