Blind 75 · #68 · Math & Geometry

Rotate Image

MediumTranspose + reverseTime O(n²)Space O(1)

Rotate Image is a medium Math & Geometry problem from the Blind 75. The key pattern is transpose + reverse, and a good solution runs in O(n²) time.

Problem

Rotate a square matrix 90 degrees clockwise and print the resulting matrix.

Examples

Example 1

Input

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

Output

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

Example 2

Input

[[1,2],[3,4]]

Output

[[3,1],[4,2]]

Example 3

Input

[[4,8,1,6],[2,7,3,9],[5,0,11,12],[13,14,15,10]]

Output

[[13,5,2,4],[14,0,7,8],[15,11,3,1],[10,12,9,6]]

Approach

Transpose the matrix across its main diagonal, then reverse each row to rotate it 90° clockwise in place.

PatternTranspose + reverse
TimeO(n²)
SpaceO(1)

Watch out for

Reversing columns instead of rows rotates the other way.

More Math & Geometry problems