← Whiteboard questions

Spiral Matrix

Read a table from the outside in, ring by ring

DSA, Medium, Math & Geometry

Which structure or algorithm, and what does it cost.

A table table holds whole numbers in rows and columns. Write spiral_order(table) to read it like a snail shell. Start at the top-left cell and go right along the top row. Then go down the last column, left along the bottom row, and up the first column. Then repeat on the cells inside. Return the numbers in the order you read them, and read every cell once.

Examples

Input table = [[4, 9, 1, 6], [2, 8, 3, 7], [5, 0, 2, 1]]
Output [4, 9, 1, 6, 7, 1, 2, 0, 5, 2, 8, 3]
Why the outer ring reads 4, 9, 1, 6, 7, 1, 2, 0, 5, 2. Then the walk turns inward and reads 8, 3.
Input table = [[2], [7], [1], [8]]
Output [2, 7, 1, 8]
Why a single column has one cell on the top row, then the walk goes down. No cell is read twice.
Input table = [[3, 5, 8, 1, 6, 2], [9, 4, 7, 3, 0, 5]]
Output [3, 5, 8, 1, 6, 2, 5, 0, 3, 7, 4, 9]
Why with two rows, the walk goes along the top and straight back along the bottom. Nothing is left inside.

Constraints

Your answer must contain

Target Aim for O(r * c) time, where r and c are the numbers of rows and columns, and O(1) extra memory besides the result.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Look at one full ring of the table. Which four runs of cells does it have, and where does each run stop?

Hint 2 the approach

After you read a run, the area still unread gets smaller. Think of four edges that move inward as you go.

Hint 3 the key step

Keep four edges: top, bottom, left, right. Read the top run, then move the top edge down. Repeat for each side, but check that cells remain before the last two.

Walkthrough

Full walkthrough brute force to best

Brute force

Keep a second grid that marks the cells already read. Start at the top-left cell, facing right. Read the cell, mark it, and step ahead. When the next cell is off the table or already marked, turn right. Stop after r * c reads. This is O(r * c) time, but it needs O(r * c) extra memory for the marks, and the turning rule is easy to get wrong.

Best method

Keep four edges, top, bottom, left and right, around the cells not yet read. Read the top row from left to right, then move top down by one. Read the right column from top to bottom, then move right in by one. If any rows remain, read the bottom row from right to left and move bottom up. If any columns remain, read the left column from bottom to top and move left in. Repeat while both edge pairs still have cells between them. The two checks matter on a single row or column, where the last two runs would read the same cells again. Every cell is read exactly once, because each run leaves the unread area as soon as it is read.

Hand trace

Run on [[4, 9, 1, 6], [2, 8, 3, 7], [5, 0, 2, 1]]. The edges are top 0, bottom 2, left 0, right 3. Top row: 4, 9, 1, 6, and top becomes 1. Right column, rows 1 to 2: 7, 1, and right becomes 2. Rows remain, so read the bottom row from column 2 back to 0: 2, 0, 5, and bottom becomes 1. Columns remain, so read the left column at row 1: 2, and left becomes 1. Second round, with top 1, bottom 1, left 1, right 2: top row 8, 3, and top becomes 2. The right column is empty, and right becomes 1. No rows remain, so skip the bottom row. The left column has no rows left, and left becomes 2. The edges have crossed, so stop. The result is [4, 9, 1, 6, 7, 1, 2, 0, 5, 2, 8, 3].

Code

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

Time and memory

O(r * c) time, because each cell is read once and each run costs O(1) to set up. O(1) extra memory beyond the result list, because only four edge numbers are kept.

Common mistakes

  • Skipping the two checks before the bottom row and the left column. On the single column [[2], [7], [1], [8]] the walk then reads two cells twice.
  • Moving an edge before the run next to it is read. The run starts one cell late, and a row or column is skipped.
  • Mixing up the row count and the column count on a table that is not square. Test with 2 rows and 6 columns.

Related problems

More Math & Geometry problems
Spiral Matrix: hints, walkthrough and Python solution