class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
# Tranpose
for i in range(n):
for j in range(i+1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reflection
for i in range(n):
for j in range(n // 2):
matrix[i][j], matrix[i][n-j-1] = matrix[i][n-j-1], matrix[i][j]
# Time: O(n^2)
# Space: O(1)
The “Rotate Image” problem requires you to rotate an n × n
2D matrix 90 degrees clockwise, in-place. This means you must rearrange the values inside the matrix without using extra space for another matrix.
For example, given:
1 | 2 | 3 |
4 | 5 | 6 |
7 | 8 | 9 |
7 | 4 | 1 |
8 | 5 | 2 |
9 | 6 | 3 |
Matrix rotation is a core concept in geometry, image processing, and computer graphics. Solving this problem builds your understanding of 2D array manipulation, in-place transformations, and symmetry properties. In interviews, it tests your ability to reason about indexes and operate efficiently with limited memory.
The trick to solving this problem in-place lies in recognizing a two-step transformation:
These two operations, when combined, result in a 90-degree clockwise rotation.
Transposing means turning all rows into columns. For every cell (i, j)
above the main diagonal, we swap it with (j, i)
.
i = 0
to n - 1
i
, loop j = i + 1
to n - 1
matrix[i][j]
and matrix[j][i]
After transposition, our example becomes:
1 | 4 | 7 |
2 | 5 | 8 |
3 | 6 | 9 |
Now we reverse each row to complete the 90° rotation. This swaps the elements on the left with those on the right.
i = 0
to n - 1
j
and n - j - 1
for j = 0
to n / 2 - 1
Final rotated matrix:
7 | 4 | 1 |
8 | 5 | 2 |
9 | 6 | 3 |
Another solution involves rotating the matrix layer by layer (or ring by ring). For each square layer from the outside in:
Repeat this for each layer. Though this method is more complex, it avoids transposition logic and operates purely by index manipulation.
Time Complexity: O(n²), since every element in the matrix is accessed and possibly swapped once.
Space Complexity: O(1), because all transformations are done in-place without allocating another matrix.
The “Rotate Image” problem elegantly demonstrates how simple geometric operations—transpose and reflect—can yield powerful transformations. It’s a prime example of solving problems using patterns and properties rather than brute-force logic. Mastering this in-place algorithm prepares you for more advanced matrix manipulation tasks, like rotating images in-place or optimizing spatial layouts.