Start learning free

LESSON 50 OF 314 · MATRIX

Spiral Matrix in Go: O(m * n) with 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 slice 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

    GO · MATRIX

    Spiral Matrix in Go, explained

    Problem overview

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

    For the 3 by 3 matrix with rows [1, 2, 3], [4, 5, 6] and [7, 8, 9], the result is [1, 2, 3, 6, 9, 8, 7, 4, 5]. The outside ring gives 1, 2, 3, 6, 9, 8, 7, 4, and only 5 remains in the middle. The matrix doesn't have to be square: for three rows and four columns, the result is [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7], where the middle part is the single row 6, 7.

    Approach: walk lap by lap and move the boundaries in

    Tracking which cells were visited, say with a second matrix of booleans and a direction that turns when it hits a visited cell, works but costs O(m * n) extra space. There is a simpler way to see the problem.

    Keep four numbers that describe the part not visited yet: top and bottom are its first and last rows, left and right its first and last columns. Each lap of the loop walks once around that part, clockwise, and every side that is finished moves its boundary one step inward. When a pair of boundaries crosses, nothing is left.

    The tricky part is that the inner part can shrink to a single row or a single column. The four sides then overlap, and walking all four would visit some elements twice. Two checks, one before the bottom side and one before the left side, prevent it.

    Without those checks, the 3 by 4 example would return [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7, 6], with an extra 6 at the end. A single column [3], [2], [1] would return [3, 2, 1, 2].

    Step by step

    1. Start an empty result slice. It collects the elements in the order the spiral visits them.
    2. Declare the row boundaries: top is 0 and bottom is len(matrix)-1.
    3. Declare the column boundaries: left is 0 and right is len(matrix[0])-1. Every row has the same length, so the first row tells the column count.
    4. Loop while top <= bottom && left <= right. While neither pair has crossed, some elements are unvisited, and each pass walks around them.
    5. Walk the top row from left to right, both included, appending matrix[top][col] each time.
    6. Move top down by one. The top row is done. Moving it before the next side also keeps the top-right corner from being visited again.
    7. Walk the right column from the new top to bottom, appending matrix[row][right].
    8. Move right one column to the left.
    9. Check top <= bottom. If only one row was left, it was just walked as the top row, and top has passed bottom. Walking it back would add it twice.
    10. Inside the check, walk the bottom row from right down to left, appending matrix[bottom][col], then move bottom up by one.
    11. Check left <= right. If only one column was left, it was just walked as the right column, and right has passed left.
    12. Inside that check, walk the left column from bottom up to top, appending matrix[row][left], then move left one column to the right. That ends the lap.
    13. Return result after the outer loop.

    The solution in Go

    func spiralOrder(matrix [][]int) []int {
        result := []int{}
        top, bottom := 0, len(matrix)-1
        left, right := 0, len(matrix[0])-1
        for top <= bottom && left <= right {
            for col := left; col <= right; col++ {
                result = append(result, matrix[top][col])
            }
            top++
            for row := top; row <= bottom; row++ {
                result = append(result, matrix[row][right])
            }
            right--
            if top <= bottom {
                for col := right; col >= left; col-- {
                    result = append(result, matrix[bottom][col])
                }
                bottom--
            }
            if left <= right {
                for row := bottom; row >= top; row-- {
                    result = append(result, matrix[row][left])
                }
                left++
            }
        }
        return result
    }
    

    The Go details worth a closer look:

    • append returns the slice. It may have to allocate a bigger backing array, so its result is always assigned back: result = append(result, ...). Calling append and ignoring the return value would lose the new element. Because the loops add each element once, the slice grows in amortized constant time per element.
    • result := []int{} starts an empty slice of int with length 0, ready for append.
    • Multiple declaration. top, bottom := 0, len(matrix)-1 declares two variables in one statement.
    • Go's while loop. The outer for has only a condition. Go has no while keyword, and for condition { ... } plays its role.
    • Down-counting loops. col-- and row-- are fine because the variables are signed ints, and the condition col >= left stops them as soon as they drop below the boundary.
    • Indexing a missing row panics. matrix[0] needs at least one row. The constraints guarantee m and n are at least 1.

    Complexity

    Time: O(m * n). Each element is appended exactly once, and the loops do no other work beyond moving the boundaries.

    Space: O(1) extra, beyond the returned slice of m * n elements. The only variables are the four boundaries and the loop counters.

    Edge cases and common mistakes

    • A single row. [[1, 2, 3]] gives [1, 2, 3]. After the top row, top is 1 and bottom is 0, so the first check skips the bottom row.
    • A single column. [[3], [2], [1]] gives [3, 2, 1]. After the right column, right is -1 and left is 0, so the second check skips the left column.
    • A single element. [[7]] gives [7].
    • A 2 by 2 matrix. [[1, 2], [3, 4]] gives [1, 2, 4, 3]. Both checks pass, and the lap uses all four sides once.
    • Forgetting the two checks. The result then repeats elements whenever the inner part is one row or one column wide, as shown above.
    • Using < in the loops. Both ends of every side are elements to visit, so each side's loop uses <= or >=.
    • Moving the boundary too late. If top++ comes after the right-column loop, the top-right corner is appended twice.

    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].
    • [[7]] gives [7].
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free