Start learning free

LESSON 49 OF 314 · MATRIX

Rotate Image in Go: In-Place Transpose and Reverse

Practice O(n^2) Read the full explanation

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

Rotate it a quarter turn clockwise, like turning a photo onto its right side.

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.

Work in place. Change the numbers inside matrix itself, and don't fill a new grid.

Your function returns nothing. Each example's output shows matrix after the function runs.

 

Example 1:

Input: matrix = [
  [4, 9, 2],
  [3, 5, 7],
  [8, 1, 6]
]
Output: [
  [8, 3, 4],
  [1, 5, 9],
  [6, 7, 2]
]
Explanation: The left column, read from the bottom up, is now the top row.
The top row is now the right column.
The 5 in the center stays where it is.

Example 2:

Input: matrix = [
  [-3, 8],
  [8, 0]
]
Output: [
  [8, -3],
  [0, 8]
]
Explanation: Each number moves to the next corner clockwise:
-3 goes to the top right,
the top-right 8 goes to the bottom right,
0 goes to the bottom left,
the bottom-left 8 goes to the top left.

Example 3:

Input: matrix = [
  [7]
]
Output: [
  [7]
]
Explanation: A single number has nowhere to move.

 

Constraints:

  • n is 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(n2) time and use O(1) extra space: it only moves numbers around inside matrix.

STEP 1 OF 7
    Ctrl + Enter to check

    GO · MATRIX

    Rotate Image in Go, explained

    Problem overview

    The function rotate receives a square matrix, matrix, with n rows and n columns, and turns it a quarter turn clockwise. It works in place and returns nothing: after the call, the caller's matrix holds the rotated numbers. The time budget is O(n²) and the extra space O(1).

    For this input:

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

    the matrix becomes:

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

    The left column read from the bottom up (7, 4, 1) becomes the top row, and the top row becomes the right column.

    Approach: two flips make a turn

    Building a second matrix and copying each number to its new place would be easy, but it uses O(n²) extra space, and the task asks for a rotation inside matrix itself. Moving numbers one cycle of four cells at a time is possible, but fiddly to index.

    A cleaner way uses two simple flips:

    1. Transpose the matrix: flip it over its main diagonal, the cells from the top-left to the bottom-right corner. The number at row i, column j moves to row j, column i, so each row becomes the column with the same number.
    2. Reverse every row.

    After the transpose, row i holds what was column i, read from top to bottom. A clockwise turn needs that column from bottom to top, so reversing the rows finishes the job. Both flips only swap numbers inside matrix.

    On the 3 by 3 example, the transpose gives this, and reversing each row then gives the answer above:

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

    Step by step

    1. Store the size len(matrix) in n. The matrix is square, so it is both the row count and the column count.
    2. Loop over the rows i from 0 to n - 1 for the transpose.
    3. Loop over the columns to the right of the diagonal: j from i + 1 to n - 1. Each pair of mirrored cells is visited exactly once.
    4. Swap matrix[i][j] with matrix[j][i] in one assignment line.
    5. Loop over the rows again to reverse each one.
    6. Loop over the first half of the row: j from 0 while j < n/2. Each cell trades places with its mirror from the other end. Going further would swap every pair back.
    7. Swap matrix[i][j] with matrix[i][n-1-j], the same way as in the transpose. The expression n-1-j counts j from the right end: 0 pairs with n - 1, 1 with n - 2.

    The solution in Go

    func rotate(matrix [][]int) {
        n := len(matrix)
        for i := 0; i < n; i++ {
            for j := i + 1; j < n; j++ {
                matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
            }
        }
        for i := 0; i < n; i++ {
            for j := 0; j < n/2; j++ {
                matrix[i][j], matrix[i][n-1-j] = matrix[i][n-1-j], matrix[i][j]
            }
        }
    }
    

    The Go details worth a closer look:

    • Tuple assignment swaps. In a, b = b, a, Go evaluates the whole right side before it assigns anything, so both old values are read before either cell changes. No temporary variable is needed. This works for index expressions such as matrix[i][j] too.
    • The function changes the caller's matrix. A [][]int is a slice of slices. The parameter is a copy of the slice header, but it points at the same rows, and each row points at the same numbers. Writing matrix[i][j] therefore reaches the caller's data. After y := x and rotate(y), printing x shows the rotated numbers too.
    • No return value. Since the numbers move inside the shared rows, there is nothing to return. Assigning a new slice to matrix inside the function would not affect the caller, because the parameter is only a copy of the header.
    • n/2 is integer division. It rounds down, so for odd n the middle cell is left out, which is right: it is its own mirror.

    Complexity

    Time: O(n²). The transpose visits about half of the n² cells, and the reversal swaps n/2 pairs in each of n rows. Both are proportional to n².

    Space: O(1). The only extra variables are n and the loop counters. The swaps need no temporary storage.

    Edge cases and common mistakes

    • A 1 by 1 matrix. [[7]] stays [[7]]. Both inner loops do nothing.
    • A 2 by 2 matrix. [[1, 2], [3, 4]] becomes [[3, 1], [4, 2]].
    • Starting the transpose's inner loop at 0. Every pair would be swapped twice, and the second swap undoes the first. On the 3 by 3 example, a loop with j := 0 leaves the matrix as [[1 2 3] [4 5 6] [7 8 9]]. Starting at i + 1 visits each pair once.
    • Reversing the whole row. If the second inner loop runs to n instead of n/2, each pair is swapped twice and the row comes back unchanged. For row [1, 2, 3] the result is [1, 2, 3].
    • Transposing only. The transpose alone mirrors the matrix instead of turning it: the 3 by 3 example would stay as the grid with 1, 4, 7 in its top row. The reversal turns the mirror into a rotation.
    • Odd sizes. The centre cell of a 3 by 3 or 5 by 5 matrix never moves. The loops leave it alone without a special case.

    Testing

    • [[1, 2], [3, 4]] gives [[3, 1], [4, 2]].
    • [[1, 2, 3], [4, 5, 6], [7, 8, 9]] gives [[7, 4, 1], [8, 5, 2], [9, 6, 3]].
    • [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]] gives [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]].
    • [[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