Problem overview
The method rotate receives a square int[][] matrix with n rows and n columns and turns it a quarter turn clockwise. It must work in place: the numbers move inside matrix itself, nothing is returned, and no second matrix is built. Time is O(n²) and extra space is O(1).
For the matrix [[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 flips make a rotation
The direct way is to compute where each number lands. A number at row i, column j moves to row j, column n - 1 - i. Copying every number into a new matrix with that rule is easy, but it uses O(n²) extra space. Doing it in place means moving four numbers around a cycle at once, and that is easy to get wrong.
There is a simpler route that splits the turn into two flips, each of which is a plain swap of pairs:
- Transpose the matrix: flip it over its main diagonal, the line from the top-left to the bottom-right corner. The number at row
i, columnjtrades places with the one at rowj, columni. Rowibecomes what columniwas. - Reverse every row. A clockwise turn needs each old column read from the bottom up, and after the transpose that column sits in a row from the top down, so each row is read backwards.
For the first example, the transpose gives [[1, 4, 7], [2, 5, 8], [3, 6, 9]]. Reversing each row then gives [[7, 4, 1], [8, 5, 2], [9, 6, 3]], the expected result.
Step by step
- Store the size.
int n = matrix.length;is both the number of rows and the number of columns, because the matrix is square. - Loop over the rows with
ifrom 0 ton - 1, for the transpose. - Loop over the columns right of the diagonal with
jfromi + 1ton - 1. This visits each pair of mirror cells once. Starting at 0 would visit each pair twice and the second swap would undo the first. - Save
matrix[i][j]intemp. The next line overwrites that cell, and its value must not be lost. - Finish the swap. Copy
matrix[j][i]intomatrix[i][j], then puttempintomatrix[j][i]. - Loop over the rows again to reverse each one.
- Loop
jfrom 0 whilej < n / 2. Java has no method that reverses anint[]in place, so the row is reversed by swapping its two ends and moving inward. Only the first half starts a swap. Going further would swap each pair back. - Swap
matrix[i][j]withmatrix[i][n - 1 - j], again throughtemp. Celln - 1 - jis the mirror of celljwithin the row.
The solution in Java
class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n / 2; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[i][n - 1 - j];
matrix[i][n - 1 - j] = temp;
}
}
}
}
The Java details worth a closer look:
- A 2D array is an array of arrays.
int[][]holds one reference per row, andmatrix[i][j]reads rowi, then columnjin it. Because the method changes the rows that the caller's array refers to, the caller sees the rotated numbers after the call, and nothing needs to be returned. - No swap helper. Java cannot swap two
intvariables through a method, so the three-line pattern withtempis written inline.Collections.reversewould not help: it works on aList, not on anint[]. - Odd sizes. When
nis odd,n / 2uses integer division and rounds down, so the middle cell of each row is not swapped with anything. That is correct, since it is its own mirror. - Same names, separate scopes. The variable
tempis declared inside each inner loop body, so each swap gets a fresh one.
Complexity
Time: O(n²). The transpose visits about half of the n² cells, and the row reversal visits another half of them. Each visit is a constant-time swap.
Space: O(1). Only n, i, j and temp are added, whatever the size of the matrix.
Edge cases and common mistakes
- A 1 by 1 matrix.
[[7]]stays[[7]]: the transpose loop has nothing right of the diagonal, andn / 2is 0, so the reversal does nothing. - Transposing from column 0. If the inner loop starts at
j = 0, every pair is swapped twice. On the 3 by 3 example, that leaves[[1, 2, 3], [4, 5, 6], [7, 8, 9]]unchanged, and the reversal then produces a wrong result. - Reversing the whole row. If the reversal loop runs while
j < n, every pair is swapped twice. After the transpose, the matrix comes out as[[1, 4, 7], [2, 5, 8], [3, 6, 9]]: only the transpose has taken effect. - Transpose without reversing. A transpose alone is a reflection, not a rotation. The reversal is what turns it into a clockwise quarter turn.
- Building a new matrix. Assigning
matrix = new int[n][n]inside the method changes only the local parameter. The caller's matrix stays as it was, which is why the lesson swaps numbers inside the existing rows.
Testing
[[1, 2], [3, 4]]becomes[[3, 1], [4, 2]].[[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]].[[7]]stays[[7]].
