Browse curriculum

FAANGPrep Sprint

Rotate Image

Rotate the matrix by 90 degrees clockwise in-place.

Problem Understanding

Turn an n x n matrix, an image stored as a grid of pixels, a quarter turn clockwise. The rotation must happen in-place, inside the same matrix, without allocating a second one.

Strategy (Transpose + Reflect)

  1. Transpose: Swap matrix[i][j] with matrix[j][i].
  2. Reflect: Reverse each row.
  • Step 1: Transpose converts rows to columns.

  • Step 2: Reversing rows fixes the left-right order for 90 deg rotation.

Interactive Visualization

READY

0

1

2

0

1
2
3

1

4
5
6

2

7
8
9

Size

3 × 3

Swaps

0

 

n = 3. First transpose: swap each cell above the diagonal with its mirror below it (the diagonal swaps with itself, so it never moves)

Next

Swap matrix[0][1] and matrix[1][0]: 2 ↔ 4

Matrix

See the two-step process: Transpose then Reverse.