Rotate a Square Image 90 Degrees

medium matrix in-place

Problem

Given an n × n matrix representing an image, rotate it 90° clockwise in place. The trick: a 90° clockwise rotation equals a transpose (swap across the main diagonal) followed by reversing each row. Each step touches every cell once and uses no extra matrix.

Input[[1,2,3],[4,5,6],[7,8,9]]
Output[[7,4,1],[8,5,2],[9,6,3]]
Transpose first, then reverse each row.

def rotate(matrix):
    n = len(matrix)
    for r in range(n):
        for c in range(r + 1, n):
            matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c]
    for r in range(n):
        matrix[r].reverse()
function rotate(matrix) {
  const n = matrix.length;
  for (let r = 0; r < n; r++) {
    for (let c = r + 1; c < n; c++) {
      const t = matrix[r][c];
      matrix[r][c] = matrix[c][r];
      matrix[c][r] = t;
    }
  }
  for (let r = 0; r < n; r++) {
    matrix[r].reverse();
  }
}
class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        for (int r = 0; r < n; r++) {
            for (int c = r + 1; c < n; c++) {
                int t = matrix[r][c];
                matrix[r][c] = matrix[c][r];
                matrix[c][r] = t;
            }
        }
        for (int r = 0; r < n; r++) {
            for (int i = 0, j = n - 1; i < j; i++, j--) {
                int t = matrix[r][i];
                matrix[r][i] = matrix[r][j];
                matrix[r][j] = t;
            }
        }
    }
}
void rotate(vector<vector<int>>& matrix) {
    int n = matrix.size();
    for (int r = 0; r < n; ++r) {
        for (int c = r + 1; c < n; ++c) {
            swap(matrix[r][c], matrix[c][r]);
        }
    }
    for (int r = 0; r < n; ++r) {
        reverse(matrix[r].begin(), matrix[r].end());
    }
}
Time: O(n²) Space: O(1)