</>

48. Rotate Image

Medium NeetCode 150
Math & Geometry Time O(N^2) Space O(1)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Math & Geometry
Time
O(N^2)
Space
O(1)

Standard Solution (C++)

SummaryGiven an n×n integer matrix, rotate all its elements 90 degrees clockwise in-place without allocating an auxiliary matrix.

Approach
  • A 90° clockwise rotation can be decomposed into two simpler in-place operations: transpose followed by horizontal mirror.
  • Transposing swaps every element matrix[i][j] with matrix[j][i] (upper triangle only, to avoid double-swapping).
  • Reversing each row then shifts columns left-to-right, which is equivalent to mirroring along the vertical axis — together the two steps produce a 90° clockwise result.
  • Both passes are O(n²) and neither requires extra storage, so the solution is truly in-place.
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        int n = matrix.size();

        // Step 1: transpose — swap matrix[i][j] with matrix[j][i]
        // Iterate only the upper triangle to avoid double-swapping.
        for (int i = 0; i < n; ++i)
            for (int j = i + 1; j < n; ++j)
                swap(matrix[i][j], matrix[j][i]);

        // Step 2: reverse each row — equivalent to a horizontal flip.
        // Transpose + horizontal flip == 90° clockwise rotation.
        for (int i = 0; i < n; ++i)
            reverse(matrix[i].begin(), matrix[i].end());
    }
};
Time O(n²) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        int n=matrix.size();
        
        for(int i=0; i<n; ++i){
            for(int j=i; j<n; ++j){
                std::swap(matrix[i][j], matrix[j][i]);
            }
        }

        for(int i=0; i<n; ++i){
            std::reverse(matrix[i].begin(), matrix[i].end());
        }
    }
};

// Time Complexity: O(N^2)
// Space Complexity: O(1)
Time O(N^2) Space O(1)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern