All Blind 75 questions

Rotate Image

FreeMatricesMedium68 of 75

The problem

Rotate a square matrix 90 degrees clockwise in place. Do not allocate another matrix.

Example

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

Need a hint?

Two simple reflections compose a rotation.

Write pseudocode, trace the example, or note an edge case. This scratchpad does not run code.

Notes stay in this browser when storage is available.

Read the solution approach

Transpose the matrix by swapping entries across the main diagonal, touching each pair once. Then reverse every row in place. An original entry at (r,c) ends at (c,n−1−r), which is the clockwise rotation.

Complexity

O(n²) time and O(1) extra space.

Before moving on, explain why the algorithm is correct and trace a boundary case without looking at the approach.