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:
- 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, columnjmoves to rowj, columni, so each row becomes the column with the same number. - 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
- Store the size
len(matrix)inn. The matrix is square, so it is both the row count and the column count. - Loop over the rows
ifrom 0 ton - 1for the transpose. - Loop over the columns to the right of the diagonal:
jfromi + 1ton - 1. Each pair of mirrored cells is visited exactly once. - Swap
matrix[i][j]withmatrix[j][i]in one assignment line. - Loop over the rows again to reverse each one.
- Loop over the first half of the row:
jfrom 0 whilej < n/2. Each cell trades places with its mirror from the other end. Going further would swap every pair back. - Swap
matrix[i][j]withmatrix[i][n-1-j], the same way as in the transpose. The expressionn-1-jcountsjfrom the right end: 0 pairs withn - 1, 1 withn - 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 asmatrix[i][j]too. - The function changes the caller's matrix. A
[][]intis 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. Writingmatrix[i][j]therefore reaches the caller's data. Aftery := xandrotate(y), printingxshows 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
matrixinside the function would not affect the caller, because the parameter is only a copy of the header. n/2is integer division. It rounds down, so for oddnthe 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 := 0leaves the matrix as[[1 2 3] [4 5 6] [7 8 9]]. Starting ati + 1visits each pair once. - Reversing the whole row. If the second inner loop runs to
ninstead ofn/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]].
