HARD Lab · Matrix · 61

48. Rotate Image

Rotating an n×n matrix 90° clockwise in-place looks daunting, but decomposes neatly into two familiar operations: transpose (swap across the main diagonal), then reverse each row — no extra array needed.

MediumMatrixIn-place TransposeTypeScript

PROBLEM What we're solving

Given an n×n matrix, rotate it 90° clockwise in-place — no allocating a new matrix.

Example: [[1,2,3],[4,5,6],[7,8,9]] → after rotation: [[7,4,1],[8,5,2],[9,6,3]]. The first column of the original becomes the first row of the result, bottom-to-top.

KEY IDEA Transpose + reverse rows = 90° CW rotation

Insight → A 90° clockwise rotation is equivalent to two simpler operations applied sequentially: (1) transpose — flip across the main diagonal so matrix[i][j] swaps with matrix[j][i]; then (2) reverse each row — mirror each row left-to-right. Each step touches every cell exactly once, so the combined cost is O(n²) with O(1) extra space.

RECIPE Transpose, then reverse

  • 1 · Transpose. Iterate i from 0 to n-1, j from i+1 to n-1 (only the upper triangle, to avoid double-swapping). Swap matrix[i][j] matrix[j][i].
  • 2 · Reverse each row. For each row i, use two pointers lo=0, hi=n-1; swap while lo < hi, then advance inward. This mirrors the row, completing the 90° rotation.
Classic confusion → A common mistake is swapping the entire matrix rather than only the upper triangle during the transpose. If j starts at 0 instead of i+1, each pair gets swapped twice — returning to the original matrix. Always start j at i+1.
Pattern transfer → For a counter-clockwise 90° rotation, reverse each row first, then transpose. For 180°, reverse every row and every column (or transpose twice). The transpose trick generalises to any matrix reflection.

COST Complexity & alternatives

Copy to new matrix
O(n²) space
Place each cell at its rotated position; simple but uses extra memory.
Transpose + reverse rows
O(1) space
Two in-place sweeps. O(n²) time, O(1) extra space.

Both approaches are O(n²) time — every cell must move. The in-place approach is preferred in interviews because it demonstrates the decomposition insight and avoids the O(n²) auxiliary allocation. A third option is 4-way cycle rotation (rotate groups of four cells in concentric rings), which is also O(1) space but harder to implement without off-by-one errors.

RUN IT Transpose then reverse each row

step 0 / 14
STARTInput: 3×3 matrix. We'll rotate 90° clockwise in-place via transpose then reverse each row.
1
2
3
4
5
6
7
8
9
Phase 1 of 2
Transpose the matrix
(swap [i][j] ↔ [j][i])
target cellmirror / swap partner
slowfast

TYPESCRIPT The solution, annotated

rotateImage.ts
function rotate(matrix: number[][]): void {
  const n = matrix.length;

  // Phase 1 — transpose: swap matrix[i][j] with matrix[j][i]
  for (let i = 0; i < n; i++) {
    for (let j = i + 1; j < n; j++) {
      const tmp = matrix[i][j];
      matrix[i][j] = matrix[j][i];
      matrix[j][i] = tmp;
    }
  }

  // Phase 2 — reverse each row
  for (let i = 0; i < n; i++) {
    let lo = 0, hi = n - 1;
    while (lo < hi) {
      const tmp = matrix[i][lo];
      matrix[i][lo] = matrix[i][hi];
      matrix[i][hi] = tmp;
      lo++;
      hi--;
    }
  }
}

Reading it block by block

Lines 4–10 — transpose. The outer loop picks row i; the inner loop starts at j = i + 1 so we only visit the upper triangle. Each iteration does a 3-variable swap of matrix[i][j] and matrix[j][i]. After this phase the matrix equals the mathematical transpose of the original.
Lines 13–20 — reverse each row. A classic two-pointer reversal: start with lo = 0 and hi = n - 1, swap, and move the pointers inward until they meet. Doing this for every row turns the transpose into a 90° clockwise rotation.
Complexity → O(n²) time — every cell is touched once in each phase. O(1) extra space — all swaps are in-place with a single temporary variable.

INTERVIEWFollow-ups they'll ask

  • "What about counter-clockwise?" Reverse each row first, then transpose. The two operations commute into either direction of rotation depending on their order.
  • "What about 180°?" Reverse every row, then reverse the order of the rows (or equivalently, reverse along both axes). Or apply the 90° rotation twice.
  • "Can you do it with 4-way ring rotation?" Yes — for each layer from outside in, cycle groups of four cells. Same O(n²) time and O(1) space, but trickier indexing.
  • "Does this work for non-square matrices?" No — transposing a rectangular m×n matrix into an n×m result requires a new allocation because the dimensions change.
  • "Why start j at i+1 not 0?" Starting at 0 would swap each pair twice (once as [i][j] and once as [j][i]), undoing both swaps and leaving the matrix unchanged.

MNEMONIC The one-liner

"Transpose the diagonal, then mirror each row — clockwise rotation for free."

TRIGGERS When you see ___ → reach for ___

rotate matrix 90° clockwise in-placetranspose then reverse rows
flip matrix across main diagonalswap [i][j] ↔ [j][i], j starts at i+1
rotate counter-clockwisereverse rows first, then transpose
in-place 2D transformation without extra spacedecompose into two sweeps

SKELETON The reusable shape

skeleton.ts
function rotate(matrix: number[][]): void {
  const n = matrix.length;
  // Phase 1: transpose
  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]];
    }
  // Phase 2: reverse each row
  for (let i = 0; i < n; i++) {
    let lo = 0, hi = n - 1;
    while (lo < hi) {
      [matrix[i][lo], matrix[i][hi]] = [matrix[i][hi], matrix[i][lo]];
      lo++; hi--;
    }
  }
}

FLASHCARDS Tap to flip

90° clockwise rotation = ?
Transpose (swap across main diagonal), then reverse each row.
tap to flip
1 / 7
Answer to reveal explanations. No penalty for retries.Score: 0 / 7
QUESTION 01
What is the correct order of operations for a 90° clockwise in-place rotation?
QUESTION 02
During the transpose phase, why should the inner loop index j start at i + 1 rather than 0?
QUESTION 03
What is the space complexity of the transpose + reverse approach?
QUESTION 04
Input: [[1,2],[3,4]]. After 90° clockwise rotation, the result is:
QUESTION 05
What is the time complexity of rotating an n×n matrix?
QUESTION 06
Which modification produces a 90° counter-clockwise rotation?
QUESTION 07
Why does the transpose + reverse approach not work for non-square (m×n) matrices?