Problem overview
The method rotate receives a square matrix, a list of n rows with n integers each, and turns it a quarter turn clockwise, as you would turn a picture. It must do this in place: the numbers move inside matrix itself, no second matrix is built, and the method returns nothing. The result is whatever matrix holds after the call.
For this matrix:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
the rotated matrix 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. The required time is O(n²), which is the size of the matrix, and the extra space is O(1).
Approach: two simple flips make one rotation
The direct way to rotate is to work out where each cell goes: the number at row i, column j lands at row j, column n - 1 - i. Doing that in place means moving four cells in a cycle and keeping track of the corners, which is easy to get wrong. Building a second matrix is easy but uses O(n²) extra space, which the lesson rules out.
A cleaner idea splits the rotation into two flips that are each easy to do in place:
- Transpose the matrix: flip it over its main diagonal, the line from the top-left corner to the bottom-right one. The number at row
i, columnjswaps places with the one at rowj, columni, so every row becomes the column with the same number. - Reverse every row. After the transpose, row
iholds the old columnifrom top to bottom, and a clockwise turn needs that column from bottom to top.
On the example, the transpose gives:
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
Reversing each row then gives [7, 4, 1], [8, 5, 2] and [9, 6, 3], which is the rotated matrix.
Step by step
- Store the size in
n. The matrix is square, so it is both the number of rows and the number of columns. - Loop over the rows with
iinrange(n)to start the transpose. - Loop over the columns to the right of the diagonal with
jinrange(i + 1, n). Each pair of mirrored cells is visited exactly once. Ifjstarted at 0, every pair would be swapped twice and the second swap would undo the first. - Swap the two mirrored cells,
matrix[i][j]andmatrix[j][i], with one tuple assignment. - Start a second loop over the rows to reverse them, after the transpose is complete.
- Reverse each row in place with its
reverse()method.
The solution in Python
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
n = len(matrix)
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for i in range(n):
matrix[i].reverse()
The Python details that matter here:
- Tuple assignment swaps without a temporary. Python evaluates the whole right-hand side first, producing both old values, and only then assigns them. Neither cell is overwritten before it is read.
reverse()works in place and returnsNone. Writingmatrix[i] = matrix[i].reverse()would replace the row withNone. The slicematrix[i][::-1]builds a new list instead, which an in-place method has no use for.- Rows are shared objects. The matrix is a list of lists, so
matrix[i].reverse()changes the row that the caller sees. That is why a method that returns nothing can still deliver the result. - The method returns
None. PrintingSolution().rotate(m)showsNone; look atmafterwards.
Complexity
Time: O(n²). The transpose swaps about half of the n² cells with their mirrors, and the row reversals touch every cell once more. Both are proportional to the number of cells.
Space: O(1) extra. The method keeps only n and the loop variables. The swaps happen inside matrix, and reverse() works within each row without making a copy.
Edge cases and common mistakes
- A single cell.
[[7]]stays[[7]]. The inner loop has nothing to swap, and reversing a one-element row changes nothing. - The 2 by 2 case.
[[1, 2], [3, 4]]becomes[[1, 3], [2, 4]]after the transpose and[[3, 1], [4, 2]]after the reversals. - Swapping every pair twice. With
joverrange(n), the transpose undoes itself and the matrix comes out unchanged after the first stage. Starting ati + 1avoids it. - Counter-clockwise by mistake. Reversing the rows is what makes the turn clockwise. Doing the reversals first and the transpose second turns the matrix counter-clockwise instead.
- Returning a new matrix. Building a rotated copy and returning it leaves
matrixunchanged, so the caller sees no rotation.
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]].[[7]]stays[[7]].
