LeetCode Β· #48

Rotate Image Solution

Rotate an n Γ— n matrix 90Β° clockwise in-place.

01
Section One Β· Problem

Problem Statement

🏷️

Difficulty

Medium

πŸ”—

LeetCode

Problem #48

πŸ—οΈ

Pattern

Matrix β€” transpose + reverse

Example
Input: [[1,2,3],[4,5,6],[7,8,9]] Output: [[7,4,1],[8,5,2],[9,6,3]]
02
Section Two Β· Approach 1

Extra Matrix β€” O(nΒ²) space

Create a new matrix and place new[j][n-1-i] = old[i][j].

Problem: O(nΒ²) extra space. In-place: transpose (swap rows↔cols) then reverse each row. Two passes, no extra space.
03
Section Three Β· Approach 2

Transpose + Reverse β€” O(nΒ²), O(1) space

Step 1: Transpose (swap matrix[i][j] with matrix[j][i]). Step 2: Reverse each row. The composition of these two operations equals a 90Β° clockwise rotation.

πŸ’‘ Mental model: Fold the matrix along its main diagonal (transpose). Then flip it left-to-right (reverse rows). The result is a 90Β° clockwise rotation. For counter-clockwise: reverse rows first, then transpose. Or: transpose then reverse columns.
🎯 Pattern: "In-place matrix rotation." Transpose + reverse is the elegant O(1) space approach. Works for any square matrix. For 180°: reverse each row, then reverse row order. For 270° (counter-clockwise): transpose, then reverse columns.
04
Section Four Β· Trace

Visual Walkthrough

Rotate Image β€” Transpose + Reverse
Original β†’ Transpose β†’ Reverse rows [1,2,3] [1,4,7] [7,4,1] [4,5,6] β†’ [2,5,8] β†’ [8,5,2] βœ“ [7,8,9] [3,6,9] [9,6,3]
05
Section Five Β· Implementation

Code β€” Java & Python

Java
class Solution { public void rotate(int[][] m) { int n = m.length; // Transpose for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) { int tmp = m[i][j]; m[i][j] = m[j][i]; m[j][i] = tmp; } // Reverse each row for (int[] row : m) for (int l = 0, r = n - 1; l < r; l++, r--) { int tmp = row[l]; row[l] = row[r]; row[r] = tmp; } } }
Python
class Solution: def rotate(self, m: list[list[int]]) -> None: n = len(m) for i in range(n): for j in range(i + 1, n): m[i][j], m[j][i] = m[j][i], m[i][j] for row in m: row.reverse()
06
Section Six Β· Analysis

Complexity Analysis

ApproachTimeSpace
Extra matrixO(nΒ²)O(nΒ²)
Transpose + reverse ← optimalO(nΒ²)O(1)
07
Section Seven Β· Edge Cases

Edge Cases & Pitfalls

CaseInputWhy It Matters
1Γ—1[[1]]No change.
2Γ—2[[1,2],[3,4]]β†’ [[3,1],[4,2]].
Even n4Γ—4Works the same; no center element stays fixed.
⚠ Common Mistake: Transposing the full matrix β€” swapping (i,j) and (j,i) for ALL i,j. This swaps each pair twice, undoing the transpose. Only swap where j > i (upper triangle).

← Back to Math & Bit problems