Rotate Image (LeetCode 48): Solution and Explanation
Given an n by n matrix representing an image, rotate it 90 degrees clockwise. The rotation must happen in place, overwriting the original matrix, without allocating a second matrix.
Watch it run step by step
Try your own input and write the code →Intuition
If extra memory were allowed, the rotation would be simple: the value at row r and column c moves to row c and column n minus 1 minus r, so you could copy into a new matrix and then copy back. The in-place requirement is what makes this interesting, because writing a value to its new spot overwrites a value you have not moved yet.
Follow one value around. The top-left corner moves to the top-right, which moves to the bottom-right, which moves to the bottom-left, which moves back to the top-left. Four cells form a closed cycle, and every cell belongs to exactly one such cycle. If you save one of the four in a temporary variable, you can shift the other three along the cycle and then drop the saved value into the last free spot. No information is lost.
To cover the whole matrix, think in concentric square layers, like rings of an onion. For the outer layer, the cycles start at each position along the top edge except the last, because the last top cell is the first cell of the right edge and is handled by the first cycle. Then shrink inward by one on every side and repeat until the boundaries meet. The reference code tracks the layer with l and r and uses offset i to walk along the edge.
Approach: Layer-by-layer four-way swap
- Set
l = 0andr = n - 1, the left and right boundaries of the current layer. The top and bottom rows equallandrfor a square matrix. - While
l < r, loopifrom 0 tor - l - 1, one cycle per offset along the edge. - Save the top-left element of the cycle,
matrix[top][l + i], intopLeft. - Move the bottom-left value
matrix[bottom - i][l]into the top-left spot, then the bottom-right valuematrix[bottom][r - i]into the bottom-left spot. - Move the top-right value
matrix[top + i][r]into the bottom-right spot, then puttopLeftinto the top-right spot. - After finishing a layer, move inward with
l += 1andr -= 1.
Step-by-step example
matrix = [[1,2,3],[4,5,6],[7,8,9]]
- The only layer that needs work has
l = 0andr = 2, so there are two cycles, fori = 0andi = 1. - With
i = 0, save 1. Then 7 moves to the top-left, 9 to the bottom-left, 3 to the bottom-right, and 1 to the top-right. The matrix is [[7,2,1],[4,5,6],[9,8,3]]. - With
i = 1, save 2. Then 4 moves to the top middle, 8 to the left middle, 6 to the bottom middle, and 2 to the right middle. - The matrix is now [[7,4,1],[8,5,2],[9,6,3]].
- Moving inward gives
l = 1andr = 1, so the loop stops. The center 5 never needs to move.
Code: Python, Java, C++
1class Solution:
2 def rotate(self, matrix: List[List[int]]) -> None:
3 l, r = 0, len(matrix) - 1
4
5 while l < r:
6 for i in range(r - l):
7 top, bottom = l, r
8
9 # save the topleft
10 topLeft = matrix[top][l + i]
11
12 # move bottom left into top left
13 matrix[top][l + i] = matrix[bottom - i][l]
14
15 # move bottom right into bottom left
16 matrix[bottom - i][l] = matrix[bottom][r - i]
17
18 # move top right into bottom right
19 matrix[bottom][r - i] = matrix[top + i][r]
20
21 # move top left into top right
22 matrix[top + i][r] = topLeft
23 r -= 1
24 l += 11class Solution {
2 public void rotate(int[][] matrix) {
3 int n = matrix.length;
4
5 // Transpose
6 for (int i = 0; i < n; i++) {
7 for (int j = i; j < n; j++) {
8 int temp = matrix[i][j];
9 matrix[i][j] = matrix[j][i];
10 matrix[j][i] = temp;
11 }
12 }
13
14 // Reverse rows
15 for (int i = 0; i < n; i++) {
16 for (int j = 0; j < n / 2; j++) {
17 int temp = matrix[i][j];
18 matrix[i][j] = matrix[i][n - 1 - j];
19 matrix[i][n - 1 - j] = temp;
20 }
21 }
22 }
23}1class Solution {
2public:
3 void rotate(vector<vector<int>>& matrix) {
4 int n = matrix.size();
5
6 // Transpose
7 for (int i = 0; i < n; i++) {
8 for (int j = i; j < n; j++) {
9 swap(matrix[i][j], matrix[j][i]);
10 }
11 }
12
13 // Reverse rows
14 for (int i = 0; i < n; i++) {
15 reverse(matrix[i].begin(), matrix[i].end());
16 }
17 }
18};Time and space complexity
O(n²)
Each of the n × n cells is moved exactly once as part of a four-cell cycle, so the work is proportional to the number of cells.
O(1)
Only the single temporary topLeft and a few index variables are used, regardless of matrix size.
Other approaches
Transpose, then reverse each row (time O(n²), space O(1))
Swap matrix[i][j] with matrix[j][i] for all j > i, which flips the matrix across its main diagonal, then reverse every row. Two simple passes produce a clockwise rotation, and the code is easy to remember.
Copy into a new matrix (time O(n²), space O(n²))
Write each matrix[r][c] into rotated[c][n - 1 - r], then copy back. It is the most direct translation of the rotation formula but violates the in-place requirement.
Common mistakes
- Looping
iover the full edge lengthr - l + 1instead ofr - l. The last position is the start of the next edge and would be rotated twice. - Moving values in the wrong direction around the cycle, which produces a counterclockwise rotation.
- Forgetting to subtract or add
ion the right axis in each of the four indices, such as writingmatrix[bottom][r]instead ofmatrix[bottom][r - i]. - Transposing over the whole matrix rather than only above the diagonal in the alternative approach, which swaps every pair twice and undoes the transpose.
Frequently asked questions
How do you rotate a matrix 90 degrees clockwise in place?
Either cycle four cells at a time through each concentric layer, or transpose the matrix and then reverse every row. Both run in O(n²) time and O(1) extra space.
How do you rotate counterclockwise instead?
Transpose and then reverse each column, or reverse each row first and then transpose. In the four-way swap, move values around the cycle in the opposite direction.
Why can't you just swap matrix[r][c] with its target position?
A single swap sends the target's old value to the wrong place, because positions form cycles of four, not pairs. You need a temporary value and three shifts to complete each cycle correctly.