Algo-Sim › Matrix & Bit Manipulation

Rotate Image

Medium · Matrix & Bit Manipulation · step through it in Java, Python and C++ on your own input

Rotate an n×n matrix 90° clockwise in place: transpose across the diagonal, then reverse each row.

Problem

Given an n × n matrix, rotate it 90° clockwise. Change the matrix in place rather than allocating a second one.

Constraints

Edge cases to test

Follow-up questions

How do you rotate counter-clockwise?
Transpose, then reverse each column (or reverse each row first, then transpose). Still O(n²), in place.
What if the matrix is not square?
It can’t be rotated in place; build an n × m result with result[j][m − 1 − i] = a[i][j].

Solution

Java

public void rotate(int[][] matrix) {
    int n = matrix.length;
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            int tmp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = tmp;
        }
    }
    for (int[] row : matrix) {
        for (int l = 0, r = n - 1; l < r; l++, r--) {
            int tmp = row[l];
            row[l] = row[r];
            row[r] = tmp;
        }
    }
}

Python

def rotate(matrix):
    n = len(matrix)
    for i in range(n):
        for j in range(i + 1, n):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
    for row in matrix:
        l, r = 0, n - 1
        while l < r:
            row[l], row[r] = row[r], row[l]
            l += 1
            r -= 1

C++

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

class Solution {
  public:
    void rotate(vector<vector<int>> &matrix) {
        int n = int(matrix.size());
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int tmp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = tmp;
            }
        }
        for (vector<int> &row : matrix) {
            for (int l = 0, r = n - 1; l < r; l++, r--) {
                int tmp = row[l];
                row[l] = row[r];
                row[r] = tmp;
            }
        }
    }
};

More Matrix & Bit Manipulation problems