You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]

Example 2:

Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]

Constraints:

  • n == matrix.length == matrix[i].length
  • 1 <= n <= 20
  • -1000 <= matrix[i][j] <= 1000

Approach

  • We do 2 things first we transpose the matrix then we reverse it to create the rotate image
  • first loop goes the way it does because we have to skip the diagonal
  • second loop goes this way because we only have to mirror by the diagonal so no only need half
  • ⏱ Time Complexity: O(n²)

    • Two nested loops over an n×n matrix:
    • Transpose: visits each element above the diagonal → ≈ n²/2 swaps
    • Reverse: visits half of each row → ≈ n²/2 swaps
    • Total work ∝ n².
  • 📦 Space Complexity: O(1)

    • In-place swaps only; no auxiliary arrays or recursion.
class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        // transpose
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int t = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = t;
            }
        }
 
        //reverse
        for(int i = 0; i < n; i++) {
            for (int j = 0; j < n / 2; j++) {
                int t = matrix[i][j];
                matrix[i][j] = matrix[i][n - j - 1];
                matrix[i][n - j - 1] = t;
            }
        }
    }
}