08. Rotate Image (2D Matrix)

Difficulty:MediumPattern:Matrix ManipulationTime:O(n^2)Space:O(1)

Given an $n \times n$ 2D matrix representing an image, rotate the image by 90 degrees clockwise in-place.

How It Works & Algorithmic Design

Mathematical transformation through Transpose then Reverse:

  1. Step 1: Transpose Matrix (Swap rows and columns across main diagonal):
    • For every $i$ from $0$ to $n-1$ and $j$ from $i+1$ to $n-1$, swap matrix[i][j] with matrix[j][i].
  2. Step 2: Reverse Each Row:
    • For each row $i$, reverse elements horizontally (left and right pointers swapping matrix[i][left] and matrix[i][right]).

Why This Approach Works Best

Transpose + Reverse turns $90^\circ$ rotation into two clean, in-place matrix ops. Avoids $O(n^2)$ extra memory allocation, achieving true $O(1)$ space and $O(n^2)$ time complexity.

Example Walkthrough

Input

[[1,2,3],[4,5,6],[7,8,9]]

3x3 matrix.

After Transpose

[[1,4,7],[2,5,8],[3,6,9]]

Rows converted to columns.

After Row Reversal

[[7,4,1],[8,5,2],[9,6,3]]

Each row reversed horizontally.

Output

[[7,4,1],[8,5,2],[9,6,3]]

Rotated 90 degrees clockwise.

Answer: In-place 90-degree matrix rotation

function rotate(matrix) {
  const n = matrix.length;
  for (let i = 0; i < n; i++) {
    for (let j = i + 1; j < n; j++) {
      [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
    }
  }
  for (let i = 0; i < n; i++) {
    matrix[i].reverse();
  }
}

Transpose matrix across diagonal, then reverse each row horizontally.

Key Takeaways
  • Rotate clockwise = Transpose matrix + Reverse rows.

  • Rotate counter-clockwise = Transpose matrix + Reverse columns.

  • Performs in-place updates achieving $O(1)$ extra space and $O(n^2)$ time.