Problem overview
The method rotate(matrix) receives a square matrix: an array of n rows, each an array of n integers. It must turn the matrix a quarter turn clockwise, like turning a picture to the right. It returns nothing. The rotation happens inside matrix itself, with no second matrix, and the statement asks for O(n²) time and O(1) extra space.
For the 3 by 3 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, becomes the top row, and the top row becomes the right column.
Approach: two flips make a turn
The easy way to rotate is to build a new matrix and copy every number to its new place: the value at row i, column j goes to row j, column n - 1 - i. That takes O(n²) extra space, which the statement rules out. Moving each cell directly in four-cell cycles also works, but the index arithmetic is easy to get wrong.
A simpler way combines two easy flips:
- Transpose the matrix: flip it over its main diagonal, the line from the top-left corner to the bottom-right one. The number in row
i, columnjtrades places with the number in rowj, columni. Every row becomes the column with the same number. - Reverse every row. After the transpose, row
iholds the old columnifrom top to bottom. A clockwise turn needs it from bottom to top, so each row is read backwards.
Both flips only swap numbers inside the matrix, so no extra space is needed beyond a few variables. On the 3 by 3 example, the transpose gives [[1, 4, 7], [2, 5, 8], [3, 6, 9]], and reversing each row gives the answer [[7, 4, 1], [8, 5, 2], [9, 6, 3]].
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 - 1for 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, now to reverse each one.
- Reverse
matrix[i]in place withreverse().
The solution in JavaScript
class Solution {
rotate(matrix) {
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 JavaScript details worth knowing:
- Destructuring swap. The right-hand side
[matrix[j][i], matrix[i][j]]is evaluated first, building a new two-element array from both old values. The left-hand side then unpacks it into the two cells. Because the old values are already copied, no temporary variable is needed. A line before it that doesn't end in a semicolon could make JavaScript read the[as an index into the previous expression, so end the previous statement with;. reverse()works in place. It changes the array it is called on and also returns that same array (r.reverse() === ristrue). Since each row is an object insidematrix, reversing it changesmatrix. Nothing needs to be returned or assigned back.- Rows are references. A matrix in JavaScript is an array of arrays, so
matrix[i]is the row object itself. That is why an in-place function sees its changes reflected in the caller's matrix. Assigning a new array to the parameter, such asmatrix = [[9]]inside the function, only changes the local variable, and the caller's matrix stays as it was. - No return value.
rotatehas noreturnstatement, so a call evaluates toundefined. The lesson's tests checkmatrixafter the call.
Complexity
Time: O(n²). The transpose visits about half of the n² cells, and the row reversals touch every cell once. Both are proportional to n², the number of values in the matrix, so no solution can do better than O(n²).
Space: O(1) extra. The swaps use no new arrays beyond the temporary pair that destructuring creates, which is a constant size. The matrix is changed where it stands.
Edge cases and common mistakes
- A 1 by 1 matrix.
[[7]]stays[[7]]: the inner loop never runs, and reversing a single-element row changes nothing. - Swapping every pair twice. With
jstarting at 0, the loops visit both(i, j)and(j, i), and the second swap undoes the first. For[[1, 2], [3, 4]]the matrix ends up unchanged after the transpose step. - Reversing the wrong thing. Transpose then reverse each row turns the matrix clockwise. Reversing the order of the rows instead of each row's contents would give a counterclockwise turn.
- Building a new matrix and returning it. The lesson's tests look at
matrixitself, so a new array that you return would be ignored. - Creating rows with
fill. If you build a matrix yourself withnew Array(2).fill([0, 0]), every row is the same array. Settingsh[0][0] = 5then shows up in both rows:[[5, 0], [5, 0]]. UseArray.fromor a loop to create separate rows. - Negative values and duplicates. The swaps move values without comparing them, so negative numbers and repeated numbers need no special handling.
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]].[[7]]stays[[7]].[[1, -1], [-2, 2]]becomes[[-2, 1], [2, -1]].
