← Back to Leo Academy Masterclass

Problem #48: Rotate Image

Medium Matrix

Intuition & Strategy Breakdown

Transpose the matrix (swap matrix[i][j] with matrix[j][i]), then reverse each row horizontally to achieve a 90-degree clockwise rotation in-place.

Python Solution

def rotate(matrix):
    n = len(matrix)
    # 1. Transpose: swap(matrix[i][j], matrix[j][i])
    for i in range(n):
        for j in range(i, n):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
            
    # 2. Reverse: flip each row horizontally
    for row in matrix:
        row.reverse()

Java Solution

class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        // 1. Transpose
        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
        // 2. Reverse each row
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n / 2; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[i][n - 1 - j];
                matrix[i][n - 1 - j] = temp;
            }
        }
    }
}
Watch Interactive Video on Leo Academy Main App