Rotate Image
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
- n == matrix.length == matrix[i].length
- 1 <= n <= 20
- -1000 <= matrix[i][j] <= 1000
matrix = [[1,2,3],[4,5,6],[7,8,9]][[7,4,1],[8,5,2],[9,6,3]]matrix = [[1,2],[3,4]][[3,1],[4,2]]matrix = [[1]][[1]]Rotating a matrix 90 degrees clockwise means shifting every element to its corresponding position in a new, turned orientation. The challenge is to perform this transformation in-place without using any extra grids or large temporary storage.
The easiest way to rotate is to create a new empty matrix and map each cell to its new coordinates. If a cell is at (i, j), it will land at (j, n - 1 - i) in the rotated matrix.
n = len(matrix)
res = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
res[j][n - 1 - i] = matrix[i][j]
matrix[:] = resUsing a separate matrix takes O(N²) space. The core insight is that a 90° clockwise rotation is mathematically equivalent to two simple, in-place grid operations:
1. Transpose: Swap elements across the main diagonal (matrix[i][j] with matrix[j][i]).
2. Reverse Rows: Reverse each row horizontally.
We rotate the matrix in-place by performing these two steps:
n = len(matrix)
# 1. Transpose: Swap elements across diagonal
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# 2. Reverse each row
for i in range(n):
matrix[i].reverse()Rotation Sequence
Initial matrix. Goal: Rotate 90° clockwise in-place.
DIAGONAL SYMMETRY
Transposing swaps (i, j) with (j, i). This swaps the x and y axes, preparing the grid for its final rotated state.
MEMORY LIMITS
By performing these flips in-place, we use O(1) extra space. This is critical for large datasets like HD images.