Start learning free

LESSON 50 OF 314 · MATRIX

Spiral Matrix in Swift: Four Moving Boundaries in O(m * n)

Practice O(m*n) Read the full explanation

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

Return an array of its values in spiral order.

matrix is an array of rows. Each row is an array 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

    SWIFT · MATRIX

    Spiral Matrix in Swift, explained

    Problem overview

    The method spiralOrder receives a matrix, an array of rows with m rows and n columns, and returns all its elements in spiral order. The walk starts at the top-left corner and goes clockwise around the outside: the top row from left to right, the right column from top to bottom, the bottom row from right to left, and the left column from bottom to top. Then it repeats on what is left inside, until every element has been visited exactly once.

    For the matrix with rows [1, 2, 3, 4], [5, 6, 7, 8] and [9, 10, 11, 12], the outside gives 1, 2, 3, 4, 8, 12, 11, 10, 9, 5. What remains is a single row, 6 and 7, so the answer is [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]. The statement expects O(m * n) time: each element is visited once.

    Approach: shrinking boundaries

    A first idea is to keep a row and column position plus a direction, and to turn whenever the next cell is outside the matrix or already visited. That needs a visited marker for every cell, or a rule for when to turn.

    The lesson tracks the unvisited part with four numbers instead: top and bottom are its first and last rows, and left and right are its first and last columns. One lap of the loop walks the four sides of that part, and each finished side moves its boundary one step inward. The loop ends when a pair of boundaries crosses, because then nothing is left.

    The delicate part is the end of the spiral. When one row or one column is left, the walk along the top (or right) side already visits everything, and the walk back along the opposite side would visit the same elements a second time. That is why the bottom row and the left column are each guarded by an if.

    Here are the boundaries after each lap on the 3 by 4 example:

    after lap 1: top=1 bottom=1 left=1 right=2
    after lap 2: top=2 bottom=1 left=2 right=1
    

    After the first lap the unvisited part is row 1, columns 1 to 2, which is the 6 and 7. The second lap walks the top side (6, 7). Both pairs then cross, so the if checks skip the bottom row and the left column, and the loop ends.

    Step by step

    1. Create result, an empty [Int] declared with var, to collect the elements in visiting order.
    2. Set the row boundaries: top is 0 and bottom is matrix.count - 1.
    3. Set the column boundaries: left is 0 and right is matrix[0].count - 1. Every row has the same length, so the first row tells how many columns there are.
    4. Loop while top <= bottom && left <= right. While neither pair has crossed, some elements are still unvisited.
    5. Walk the top row with col over left...right and append matrix[top][col]. The loop condition guarantees left <= right here, so the closed range is valid.
    6. Move top down. Doing it right away also keeps the top-right corner from being visited again by the next walk.
    7. Walk the right column from top to bottom and append matrix[row][right]. It is written with stride because top may already be past bottom (a one-row matrix), and stride then produces no values instead of failing.
    8. Move right one column left.
    9. Guard the bottom row with if top <= bottom. If only one row was left, it was just walked as the top row.
    10. Walk the bottom row backwards with stride(from: right, through: left, by: -1), then move bottom up.
    11. Guard the left column with if left <= right. If only one column was left, it was just walked as the right column.
    12. Walk the left column upwards from bottom to top, then move left to the right. That finishes the lap.
    13. Return result after the loop.

    The solution in Swift

    class Solution {
        func spiralOrder(_ matrix: [[Int]]) -> [Int] {
            var result = [Int]()
            var top = 0, bottom = matrix.count - 1
            var left = 0, right = matrix[0].count - 1
            while top <= bottom && left <= right {
                for col in left...right {
                    result.append(matrix[top][col])
                }
                top += 1
                for row in stride(from: top, through: bottom, by: 1) {
                    result.append(matrix[row][right])
                }
                right -= 1
                if top <= bottom {
                    for col in stride(from: right, through: left, by: -1) {
                        result.append(matrix[bottom][col])
                    }
                    bottom -= 1
                }
                if left <= right {
                    for row in stride(from: bottom, through: top, by: -1) {
                        result.append(matrix[row][left])
                    }
                    left += 1
                }
            }
            return result
        }
    }
    

    Swift details worth knowing:

    • left...right against stride. A closed range a...b needs a <= b, and Swift stops the program if it is not true. That is fine for the top row, where the loop condition guarantees it. For the other three walks the boundaries may have crossed, so the code uses stride, which is simply empty in that case. For example, stride(from: 2, through: 1, by: 1) gives no values.
    • stride(from:through:by:) includes the end value, and a negative step counts down.
    • Declaring two variables on one line. var top = 0, bottom = matrix.count - 1 declares two separate vars of type Int.
    • var result = [Int]() creates an empty array, and append adds one element at the end.
    • Empty input. matrix[0] would be an index error for an empty matrix, which the constraints rule out (m is at least 1).

    Complexity

    Time: O(m * n). Each element is appended exactly once, and the boundary checks add a constant amount of work per lap. There are at most about half of min(m, n) laps.

    Space: O(1) extra. Apart from the returned array, the method keeps four boundary variables and a loop variable.

    Edge cases and common mistakes

    • One row. [[1, 2, 3]] gives [1, 2, 3]. After the top walk, top is past bottom, so the right-column walk and the bottom-row guard produce nothing.
    • One column. [[3], [2], [1]] gives [3, 2, 1]. The right column holds 2 and 1, and the guard on the left column keeps 2 and 1 from being added again.
    • A single cell. [[7]] gives [7].
    • Not square. The 3 by 2 matrix with rows [1, 2], [3, 4] and [5, 6] gives [1, 2, 4, 6, 5, 3].
    • Leaving out an if guard. The matrix [[1, 2, 3]] would give [1, 2, 3, 2, 1] without the first guard, since the row that was just walked as the top row would be read again as the bottom row.
    • Moving a boundary at the wrong time. The lesson moves each boundary right after its side is done, so the next side starts at the correct corner. Moving them all at the end of the lap would visit the corners twice.
    • Using ... for the later walks. A matrix with one row would stop the program when top...bottom has top above bottom.

    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], [5, 6]] gives [1, 2, 4, 6, 5, 3].
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free