← DSA
MEDIUM

Rotate Image

PracticeNeetCode ↗LeetCode ↗

Given an n × n 2D matrix representing an image, rotate the image by 90 degrees clockwise, in place — without allocating a second matrix.

Example

Input matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output [[7,4,1],[8,5,2],[9,6,3]]

Key Pointers

Step-by-Step Analysis

  1. Transpose the matrix in place: for every i < j, swap matrix[i][j] and matrix[j][i].
  2. Reverse each row in place.
  3. The matrix now holds the 90° clockwise rotation.

Complexity

Time: O(n²) — Space: O(1)

Code

def rotate(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 row in matrix:
        row.reverse()

Code Explanation

How the solution above works, piece by piece.

  1. A 90° clockwise rotation = transpose, then mirror each row left-to-right.
  2. Transpose in place: for each pair with j > i (above the diagonal), swap matrix[i][j] and matrix[j][i]. Starting j at i + 1 ensures each pair is swapped once, not twice.
  3. row.reverse() mirrors every row.
  4. No extra matrix is used: O(n²) time, O(1) space.

Visual Walkthrough

Running it on matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]:

Rotation as transpose followed by reversing rowsstart1234567891. transpose (swap across ↘)1472583692. reverse each row741852963
Transposing swaps matrix[i][j] with matrix[j][i] (the diagonal, amber, stays put). Reversing each row then turns that into a 90° clockwise rotation. Both steps work in place.
diagonalrotated

Video Explanation

NeetCode — Rotate Image, LeetCode 48