Problem overview
The method rotate receives a square matrix, an inout [[Int]] with n rows of n numbers, and turns it a quarter turn clockwise. It returns nothing: after the call, the caller's matrix holds the rotated numbers. The statement asks for O(n²) time and O(1) extra space, so building a second matrix is not allowed.
For the matrix with rows [1, 2, 3], [4, 5, 6] and [7, 8, 9], the result is:
[[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
Copying into a new matrix is easy: the number at row i, column j goes to row j, column n - 1 - i. That needs O(n²) extra space, which the statement rules out. Rotating cell by cell in groups of four also works, but it takes careful index arithmetic.
The lesson uses a simpler observation: a clockwise quarter turn is the same as two simple flips.
- Transpose the matrix: flip it over its main diagonal, so each row becomes the column with the same number.
- Reverse every row.
On the example, the transpose gives [[1, 4, 7], [2, 5, 8], [3, 6, 9]]. Row 0 is now 1, 4, 7, which is the left column of the original read from the top. A clockwise turn needs it read from the bottom, so reversing the row gives 7, 4, 1, the top row of the answer. Both flips only swap numbers that are already inside the matrix, so no extra space is needed.
Step by step
- Store the size.
matrix.countgoes into aletnamedn. The matrix is square, so it is both the number of rows and the number of columns. - Loop over the rows with
ifrom 0 up ton - 1. This starts the transpose. - Loop over the columns to the right of the diagonal with
jfromi + 1. The diagonal cells (row equals column) stay where they are, and each pair of mirror cells above and below it should be swapped once. Startingjat 0 would visit every pair twice, and the second swap would undo the first. - Swap
matrix[i][j]andmatrix[j][i]in one line, using a tuple on each side of the=. - Loop over the rows again to reverse them.
- Call
reverse()onmatrix[i], which reverses the row in place.
The solution in Swift
class Solution {
func rotate(_ matrix: inout [[Int]]) {
let n = matrix.count
for i in 0..<n {
for j in i + 1..<n {
(matrix[i][j], matrix[j][i]) = (matrix[j][i], matrix[i][j])
}
}
for i in 0..<n {
matrix[i].reverse()
}
}
}
Swift details worth knowing:
inout. Arrays are value types, so a normal parameter is a read-only copy. Marking the parameterinoutlets the method change the caller's array, and the caller passes it with&, for examplesolution.rotate(&grid). The variable being passed must be avar.- The tuple swap.
(matrix[i][j], matrix[j][i]) = (matrix[j][i], matrix[i][j])first builds a tuple from both current values, then assigns it to the two cells. No temporary variable is needed. i + 1..<nis the range fromi + 1up ton - 1. In the last row,i + 1equalsn, and the range is simply empty. It is not an error, because the range's start is not above its end.reverse()againstreversed().reverse()changes the array it is called on.reversed()doesn't change anything: it returns a new sequence, so calling it on a row would leave the matrix as it was.- Nested arrays.
matrix[i].reverse()changes the row stored insidematrix, because the subscript gives write access to that row.
Complexity
Time: O(n²). The transpose visits about half of the n² cells, and the reversal touches every cell once, so the total is a constant times n².
Space: O(1) extra. The method only keeps n and the loop variables. The swaps and the reversals happen inside the matrix.
Edge cases and common mistakes
- A single cell.
[[42]]stays[[42]]. The inner range1..<1is empty, and reversing a row of one number changes nothing. - Transposing the whole square. If the inner loop runs
jover0..<n, every pair is swapped twice. On the 3 by 3 example the matrix comes back as[[1, 2, 3], [4, 5, 6], [7, 8, 9]], unchanged. - Reversing before transposing. The order matters. Reversing the rows first and then transposing turns the matrix counterclockwise instead.
- Using
reversed(). It builds a new sequence and the row stays unchanged, so the second loop does nothing useful. - Even sizes. The method makes no distinction between odd and even
n. In the 4 by 4 example, the corners move as the statement says: 5 goes to the top-right, 11 to the bottom-right, 16 to the bottom-left and 15 to the top-left. - Four turns. Applying the method four times returns the original matrix, a handy check for your own tests.
Testing
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]becomes[[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]]becomes[[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]].[[1, 2], [3, 4]]becomes[[3, 1], [4, 2]].[[42]]stays[[42]].
