Back to solutions

Rotate Image

MediumMatrix

Rotate an n x n matrix 90 degrees clockwise in place.

Constraints
  • n == matrix.length == matrix[i].length
  • 1 <= n <= 20

Transpose then reverse rows

Time O(n^2)Space O(1)

Transposing swaps rows and columns; reversing each row afterward yields a clockwise rotation. Both steps work in place.

#include <bits/stdc++.h>
using namespace std;

void rotate(vector<vector<int>>& m) {
    int n = m.size();
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
            swap(m[i][j], m[j][i]);
    for (auto& row : m) reverse(row.begin(), row.end());
}