Rotate Image (LeetCode 48): Solution and Explanation

Medium
Array
Math
Matrix

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Set l = 0 and r = n - 1, the left and right boundaries of the current layer. The top and bottom rows equal l and r for a square matrix.
  2. While l < r, loop i from 0 to r - l - 1, one cycle per offset along the edge.
  3. Save the top-left element of the cycle, matrix[top][l + i], in topLeft.
  4. Move the bottom-left value matrix[bottom - i][l] into the top-left spot, then the bottom-right value matrix[bottom][r - i] into the bottom-left spot.
  5. Move the top-right value matrix[top + i][r] into the bottom-right spot, then put topLeft into the top-right spot.
  6. After finishing a layer, move inward with l += 1 and r -= 1.

Step-by-step example

matrix = [[1,2,3],[4,5,6],[7,8,9]]
  1. The only layer that needs work has l = 0 and r = 2, so there are two cycles, for i = 0 and i = 1.
  2. 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]].
  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.
  4. The matrix is now [[7,4,1],[8,5,2],[9,6,3]].
  5. Moving inward gives l = 1 and r = 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 += 1

Time and space complexity

Time

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.

Space

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 i over the full edge length r - l + 1 instead of r - 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 i on the right axis in each of the four indices, such as writing matrix[bottom][r] instead of matrix[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.