Problem overview
The method rotate receives a square matrix, matrix, an array of n rows with n numbers each. It must turn the matrix a quarter turn clockwise, in place: the numbers move inside matrix itself, nothing is returned, and no second matrix is built. The time budget is O(n²), which is the number of cells, with O(1) extra space.
For this input:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
the matrix afterwards 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 simple flips make a turn
Building a rotated copy is easy: the number at row i, column j goes to row j, column n - 1 - i. But the lesson wants the move done inside the same matrix, and rotating cell by cell in place means juggling four cells at a time.
A quarter turn clockwise is the same as two flips, one after the other:
- Transpose: mirror the matrix over its main diagonal, the line from the top-left corner to the bottom-right. The number at row
i, columnjswaps places with the one at rowj, columni. Rowibecomes what columniwas. - Reverse every row.
On the example, the transpose gives rows [1, 4, 7], [2, 5, 8], [3, 6, 9]. After the transpose, row i holds the old column i from top to bottom, but a clockwise turn needs it from bottom to top. Reversing each row gives [7, 4, 1], [8, 5, 2], [9, 6, 3], which is the answer. Both flips only swap numbers inside the matrix, so the extra space stays constant.
Step by step
- Store the size
matrix.lengthinn. The matrix is square, so it is both the row count and the column count. - Loop over the rows with
ifrom 0 ton - 1to start the transpose. - Loop over the columns to the right of the diagonal:
jstarts ati + 1. Each pair of mirrored cells is visited once. Ifjstarted at 0, every pair would be swapped twice, and the second swap would undo the first. - Swap
matrix[i][j]andmatrix[j][i]with array destructuring, which needs no temporary variable. - Loop over the rows again for the second flip.
- Call
reverse()onmatrix[i]. It reverses the array where it is, so the row insidematrixchanges.
The solution in TypeScript
class Solution {
rotate(matrix: number[][]): void {
let n = matrix.length;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
[matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
}
}
for (let i = 0; i < n; i++) {
matrix[i].reverse();
}
}
}
Some TypeScript details:
- The destructuring swap. The right side,
[matrix[j][i], matrix[i][j]], is evaluated first and creates a small array holding both old values. The left side then unpacks that array into the two cells in the other order. A temporary array is created on each swap, but it is a constant-size detail, not storage that grows with the matrix. - The semicolon before the swap matters in general. A line that starts with
[can be read as a continuation of the previous line. Here the previous line ends with{, so it is safe, but after an expression statement without a semicolon the line would be parsed as an index access. voidand in-place work. The return typevoidsays the method gives back nothing. The caller sees the result through the samematrixarray, because arrays are passed by reference: the method changes the caller's rows, not a copy.reverse()mutates. Unlikemaporslice, which return new arrays,reverse()reverses the array it is called on and also returns it. Here the returned value is ignored.
Complexity
Time: O(n²). The transpose visits about half of the n² cells, and the row reversals touch each cell once more. Both are proportional to the number of cells.
Space: O(1) extra. Only n, the loop counters and the tiny array of each swap are used. The matrix itself is rearranged.
Edge cases and common mistakes
- Inner loop starting at 0. Every pair gets swapped twice and the matrix is unchanged by the transpose. For
[[1, 2], [3, 4]]the matrix comes out as[[1, 2], [3, 4]]after this double swap. - Doing the flips in the wrong combination. Transpose then reverse each row is a clockwise turn. Reversing the order of the rows after a transpose would turn the matrix counterclockwise instead.
- The smallest matrix. A 1 by 1 matrix has no pair to swap and reversing a one-element row changes nothing, so
[[7]]stays[[7]]. - Building a new matrix. Assigning a freshly built array to the parameter, such as
matrix = ..., changes only the local variable and leaves the caller's matrix untouched. - Even and odd sizes. The two-flip method handles both without special cases, including the center cell of an odd matrix, which the diagonal loop never moves.
Testing
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]becomes[[7, 4, 1], [8, 5, 2], [9, 6, 3]].[[1, 2], [3, 4]]becomes[[3, 1], [4, 2]].[[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]].
