matrix rotation
in-place algorithm
coding interview
data structures
programming技巧

How to rotate a matrix 90 degrees without using any extra space?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Rotating a matrix by 90 degrees in place is a classic interview problem because it tests whether you understand index transformations and memory constraints. The standard solution uses constant extra space and works cleanly for square matrices, where the number of rows and columns is the same.

The Key Observation

For a clockwise 90-degree rotation of an n x n matrix, the value at row r and column c moves to row c and column n - 1 - r. You can implement that either with layer-by-layer swaps or with the simpler two-step trick of transposing the matrix and then reversing each row.

The transpose step swaps rows and columns. The row-reversal step then completes the clockwise rotation.

For example, this matrix:

text
1 2 3
4 5 6
7 8 9

becomes this after transpose:

text
1 4 7
2 5 8
3 6 9

and this after reversing each row:

text
7 4 1
8 5 2
9 6 3

In-Place Algorithm Using Transpose and Reverse

This approach is popular because it is short, readable, and still uses O(1) additional space.

python
1def rotate_clockwise(matrix: list[list[int]]) -> None:
2    n = len(matrix)
3
4    if any(len(row) != n for row in matrix):
5        raise ValueError("Matrix must be square")
6
7    # Step 1: transpose in place
8    for i in range(n):
9        for j in range(i + 1, n):
10            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
11
12    # Step 2: reverse each row in place
13    for row in matrix:
14        row.reverse()
15
16
17grid = [
18    [1, 2, 3],
19    [4, 5, 6],
20    [7, 8, 9],
21]
22
23rotate_clockwise(grid)
24print(grid)

The important detail is the transpose loop. It starts the inner loop at i + 1 so each pair is swapped exactly once and the diagonal stays in place.

Layer-by-Layer Rotation

Another valid in-place solution rotates the matrix ring by ring. Each step moves four values at once.

cpp
1#include <iostream>
2#include <vector>
3
4void rotateClockwise(std::vector<std::vector<int>>& matrix) {
5    int n = static_cast<int>(matrix.size());
6
7    for (int layer = 0; layer < n / 2; ++layer) {
8        int first = layer;
9        int last = n - 1 - layer;
10
11        for (int i = first; i < last; ++i) {
12            int offset = i - first;
13            int top = matrix[first][i];
14
15            matrix[first][i] = matrix[last - offset][first];
16            matrix[last - offset][first] = matrix[last][last - offset];
17            matrix[last][last - offset] = matrix[i][last];
18            matrix[i][last] = top;
19        }
20    }
21}

This version is useful if you want to show you understand the raw index movement. It is slightly harder to reason about than transpose-plus-reverse, but both have the same asymptotic complexity.

Complexity

Both in-place methods visit each element a constant number of times, so the time complexity is O(n^2). The extra space usage is O(1) because all swaps happen inside the original matrix.

That is optimal for this problem. You cannot rotate an n x n matrix without touching essentially every element.

What About Counterclockwise Rotation?

For a 90-degree counterclockwise rotation, you can still use transpose, but instead of reversing each row, reverse the order of rows.

python
1def rotate_counterclockwise(matrix: list[list[int]]) -> None:
2    n = len(matrix)
3
4    for i in range(n):
5        for j in range(i + 1, n):
6            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
7
8    matrix.reverse()

This is a good mental check that the transpose trick is really about decomposing the rotation into simpler operations.

Common Pitfalls

The most common mistake is applying the in-place algorithm to a non-square matrix. The index mapping only works cleanly without extra storage when the matrix is square.

Another issue is writing the transpose loop incorrectly and swapping elements twice. If your inner loop starts at 0 instead of i + 1, you undo earlier swaps.

Developers also sometimes reverse columns instead of rows and end up with a counterclockwise rotation when they meant clockwise.

Finally, if the matrix is represented by immutable tuples or fixed-size structures, the in-place strategy may not be possible in that language or representation. The algorithm assumes writable cells.

Summary

  • For an n x n matrix, the cleanest in-place clockwise rotation is transpose plus reverse-each-row.
  • The operation uses O(n^2) time and O(1) extra space.
  • A layer-by-layer four-way swap solution is equally valid but harder to implement.
  • In-place rotation requires a square matrix.
  • Be careful with loop bounds, because incorrect transpose logic produces double swaps or the wrong rotation direction.

Course illustration
Course illustration

All Rights Reserved.