Problem overview
The function rotate receives matrix, a &mut Vec<Vec<i32>> holding a square grid of n rows and n columns. It must turn the grid a quarter turn clockwise, in place, and return nothing: the caller sees the rotated numbers in its own matrix. The time budget is O(n²) and the extra space O(1), so building a second matrix is not allowed.
For the grid [[1, 2, 3], [4, 5, 6], [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 (1, 2, 3) becomes the right column.
Approach: two simple flips make a rotation
Rotating directly means moving numbers in cycles of four: the top-left corner goes to the top-right, that one to the bottom-right, and so on. That works, but the index arithmetic is easy to get wrong.
The lesson uses a cleaner decomposition. First transpose the matrix: mirror it over its main diagonal, so the number at row i, column j moves to row j, column i. Then reverse every row. Together the two flips equal one clockwise quarter turn, and both only swap numbers inside the matrix.
On the example, the transpose gives [[1, 4, 7], [2, 5, 8], [3, 6, 9]]. Each row is the old column with the same number, read from top to bottom. A clockwise turn needs each of those columns read from bottom to top, so reversing every row finishes the job: the first row [1, 4, 7] becomes [7, 4, 1].
Step by step
- Store the size
matrix.len()inn. The matrix is square, so it is both the row count and the column count. - Loop over the rows with
igoing over0..n, to start the transpose. - Loop over the columns to the right of the diagonal with
jgoing overi + 1..n. Each pair of mirror cells is visited exactly once. - Save
matrix[i][j]intemp, because the next line overwrites that cell. - Finish the swap: copy
matrix[j][i]intomatrix[i][j], then puttempintomatrix[j][i]. - Start a second loop over the rows,
0..n, for the reversal. - Reverse the row
matrix[i]in place with itsreverse()method.
The solution in Rust
impl Solution {
fn rotate(matrix: &mut Vec<Vec<i32>>) {
let n = matrix.len();
for i in 0..n {
for j in i + 1..n {
let temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
for i in 0..n {
matrix[i].reverse();
}
}
}
The Rust details worth a closer look:
&mutis a mutable borrow. The function doesn't own the matrix; it borrows it and may change it. Writing tomatrix[i][j]changes the caller's data, which is why nothing needs to be returned.- The manual swap. The three lines with
tempcopy ani32, which is a cheap, copyable value. Rust's borrow rules also explain why the swap is written this way:std::mem::swap(&mut matrix[i][j], &mut matrix[j][i])would need two mutable borrows ofmatrixat the same time, and the compiler rejects that. i + 1..nparses as(i + 1)..n. Wheni + 1equalsnthe range is empty and the inner loop simply doesn't run.reverse()is a method of slices thatVeccan call. It reverses the elements where they are, without allocating, and it works here becausematrix[i]is reached through a mutable reference.- Row-first indexing.
matrix[i][j]is rowi, columnj: the outer vector holds rows, and each row is an inner vector.
Complexity
Time: O(n²). The transpose visits about half of the n² cells, one swap per pair. The reversal touches every cell once. Both are proportional to n².
Space: O(1) extra. The code uses n, the loop counters and one temp. Every number moves inside the existing matrix.
Edge cases and common mistakes
- A 1 by 1 matrix. The inner loop never runs and reversing a single element changes nothing, so
[[-5]]stays[[-5]]. - Starting the inner loop at 0. Then every pair is swapped twice, and the second swap undoes the first. On the 3 by 3 example the matrix comes back unchanged:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]. - The order of the flips. Transpose first, then reverse the rows, gives a clockwise turn. Reversing the rows first and transposing afterwards would turn the matrix the other way, counterclockwise.
- Reversing columns instead of rows. After the transpose, it is the rows that must be read backwards. Reversing the columns gives a different arrangement.
- Building a new matrix. Copying into a fresh
Vec<Vec<i32>>and assigning it back would be correct but usesO(n²)space, which the lesson rules out. - Even and odd sizes. The two-flip method needs no special case for the center cell of an odd-sized matrix: it sits on the diagonal and is never swapped.
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]].- Calling
rotatefour times on[[1, 2], [3, 4]]gives[[1, 2], [3, 4]]again: four quarter turns make a full circle.
