Math & Geometry

LeetCode 48

LeetCode #48Difficulty: MediumNeetCode 150

LeetCode 48: Rotate Image

LeetCode

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise) in-place.

Problem Description

You are given an `n x n` 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly.

Examples:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]
Constraints:
  • n == matrix.length == matrix[i].length
  • 1 <= n <= 20

Core Mental Model

A 90° clockwise rotation is mathematically equivalent to: 1. Transpose the matrix (swap matrix[i][j] with matrix[j][i]). 2. Reverse each row horizontally.

Formal Loop Invariant

Invariant: Transposition swaps across main diagonal; horizontal reversal rotates clockwise.

Key Architectural Takeaway:

Decompose spatial matrix rotations into symmetrical operations: transpose + reflection.

Asymptotic Complexity Analysis

Time ComplexityO(N²)Linear scan
Space ComplexityO(1) in-place.Constant auxiliary

Bottleneck: Matrix element swaps.

Edge Cases & Screener Traps

  • 1x1 matrix