Start learning free

LESSON 50 OF 321 · MATRIX

Spiral Matrix in Python: Walking Four Shrinking Boundaries

Practice O(m*n) Read the full explanation

You get a grid matrix of integers, with m rows and n columns.

Return a list of its values in spiral order.

matrix is a list of rows. Each row is a list of integers. Row 0 is the top row. Column 0 is the leftmost column.

The spiral starts at the top-left value and goes clockwise around the edge. It goes right along the top row, then down the right column. Then it goes left along the bottom row and up the left column.

Next, it does the same with the smaller grid inside, and so on. It takes each value exactly once.

 

Example 1:

Input: matrix = [
  [5, 1, 8],
  [0, 3, 2],
  [9, 7, 4]
]
Output: [5, 1, 8, 2, 4, 7, 9, 0, 3]
Explanation: The spiral first goes around the edge:
5, 1 and 8 across the top,
2 and 4 down the right side,
7 and 9 back along the bottom,
0 up the left side.
3 is left in the middle.

Example 2:

Input: matrix = [
  [3, -1, 7],
  [6, 0, 2],
  [1, 5, 9],
  [8, 8, 4]
]
Output: [3, -1, 7, 2, 9, 4, 8, 8, 1, 6, 0, 5]
Explanation: The spiral first goes around the edge:
3, -1 and 7 across the top,
2, 9 and 4 down the right side,
8 and 8 back along the bottom,
1 and 6 up the left side.
Inside, one column is left.
It gives 0, then the 5 below it.

Example 3:

Input: matrix = [
  [-4, 0, 4]
]
Output: [-4, 0, 4]
Explanation: There is only one row.
The spiral goes right along it and stops.
No value is taken twice.

 

Constraints:

  • m and n are each from 1 to 500.
  • Each value is an integer from -1000 to 1000.
  • Negative values and repeats are allowed.

Note:

Your algorithm should run in O(m * n) time: it visits every element once.

STEP 1 OF 19
    Ctrl + Enter to check

    PYTHON · MATRIX

    Spiral Matrix in Python, explained

    Problem overview

    The method spiralOrder receives a matrix with m rows and n columns, a list of rows of integers, and returns a list with every element in spiral order. The spiral starts at the top-left corner and goes clockwise around the outside: along the top row, down the right column, back along the bottom row and up the left column. Then it repeats on what is left inside, until every element has been visited exactly once.

    For this matrix:

    [1, 2, 3]
    [4, 5, 6]
    [7, 8, 9]
    

    the result is [1, 2, 3, 6, 9, 8, 7, 4, 5]. The outer ring gives 1, 2, 3, 6, 9, 8, 7, 4, and only 5 remains in the middle. The required time is O(m * n), since each element is visited once.

    Approach: four boundaries that move inward

    Tracking the direction and turning at the edges is one way to do it, but it needs a record of which cells were visited. A simpler idea is to track the part of the matrix that has not been visited yet with four numbers: top and bottom (the first and last unvisited rows) and left and right (the first and last unvisited columns).

    Each lap of a while loop walks once around that rectangle. After each side is read, the boundary beside it moves one step inward: after the top row, top goes down by one; after the right column, right goes left by one; and so on. When the boundaries cross, nothing is left.

    The only delicate point is a rectangle that is thinner than a full ring. If a single row is left, the walk along the top already read it, and walking back along the bottom would read it a second time. The same holds for a single column. That is why the bottom row and the left column are guarded by an if.

    On the 3 by 4 example, the first lap reads 1, 2, 3, 4, then 8, 12, then 11, 10, 9, then 5. What is left is a single row, 6 and 7. The second lap reads it from left to right, and the guards stop it from reading it again on the way back.

    Step by step

    1. Start an empty list, result, to collect the elements in the order they are visited.
    2. Set the row boundaries: top is 0 and bottom is the last row's index, len(matrix) - 1.
    3. Set the column boundaries: left is 0 and right is len(matrix[0]) - 1. Every row has the same length, so the first row tells how many columns there are.
    4. Loop while both pairs of boundaries have not crossed: top <= bottom and left <= right.
    5. Walk the top row from left to right with range(left, right + 1), appending matrix[top][col].
    6. Move top down. This also stops the top-right corner from being read again by the next walk.
    7. Walk the right column from the new top to bottom, appending matrix[row][right].
    8. Move right one column left.
    9. Check top <= bottom before the bottom row. If the top walk used up the last row, top has passed bottom and there is no bottom row left to read.
    10. Walk the bottom row backwards with range(right, left - 1, -1) and move bottom up. The stop value is left out, so left - 1 makes left the last column read.
    11. Check left <= right before the left column. A single column leaves right below left after its walk down.
    12. Walk the left column upwards with range(bottom, top - 1, -1) and move left one column right. That ends the lap, and the loop condition decides whether another one is needed.
    13. Return result.

    The solution in Python

    class Solution:
        def spiralOrder(self, 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 col in range(left, right + 1):
                    result.append(matrix[top][col])
                top += 1
                for row in range(top, bottom + 1):
                    result.append(matrix[row][right])
                right -= 1
                if top <= bottom:
                    for col in range(right, left - 1, -1):
                        result.append(matrix[bottom][col])
                    bottom -= 1
                if left <= right:
                    for row in range(bottom, top - 1, -1):
                        result.append(matrix[row][left])
                    left += 1
            return result
    

    The Python details that matter here:

    • Tuple assignment such as top, bottom = 0, len(matrix) - 1 sets two variables in one line.
    • range excludes its stop value. That is why the forward walks end at right + 1 and bottom + 1, and the backward walks end at left - 1 and top - 1.
    • A range can be empty, and the loop then runs zero times. When top moves past bottom, range(top, bottom + 1) is empty, so the right-column walk is safely skipped. The two if checks are needed for the backward walks, since a backward range that is not empty would still produce elements.
    • Indexing is matrix[row][column]. The row comes first, so the top walk uses matrix[top][col] and the right walk uses matrix[row][right].

    Complexity

    Time: O(m * n). Each element is appended exactly once, and the loops do constant work per element, apart from a few boundary updates per lap.

    Space: O(1) beyond the output. The method keeps four boundary numbers and loop variables. The returned list holds m * n elements.

    Edge cases and common mistakes

    • A single column. [[3], [2], [1]] gives [3, 2, 1]. The top walk reads 3, the right walk reads 2 and 1, and the guards skip the bottom row and the left column.
    • A single row. [[1, 2, 3]] gives [1, 2, 3]. The top walk reads everything, and the top <= bottom guard keeps the backward walk from repeating it.
    • A 2 by 2 matrix. [[1, 2], [3, 4]] gives [1, 2, 4, 3]: one lap reads everything.
    • Missing guards. Without the two if checks, a leftover row or column is read twice, so the result is longer than m * n.
    • Moving a boundary too late. If top is not moved before the right-column walk, the top-right corner is read twice.
    • Mixing up the stop values. A forward range needs + 1 on its end, and a backward one needs - 1. Forgetting either one skips the last element of that side.

    Testing

    • [[1, 2, 3], [4, 5, 6], [7, 8, 9]] gives [1, 2, 3, 6, 9, 8, 7, 4, 5].
    • [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] gives [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7].
    • [[3], [2], [1]] gives [3, 2, 1].
    • [[1, 2, 3]] gives [1, 2, 3].
    • [[1, 2], [3, 4]] gives [1, 2, 4, 3].
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free