48. Rotate Image

Intuition

To rotate an image (matrix) 90 degrees clockwise in-place, we can break it down into two simple transformations:

  1. Transpose the matrix: convert rows to columns by flipping over the diagonal.

  2. Reverse each row (mirror along the vertical center axis).

These two operations combined result in a 90° clockwise rotation without using extra space.

Complexity

Space Complexity
Time Complexity

O(1)\text{O}(1)

O(N2)\text{O}(N^2)

Code

public void rotate(int[][] matrix) {
    int rowCount = matrix.length;
    int colCount = matrix[0].length;

    // Step 1: Transpose the matrix (flip over diagonal)
    for (int row = 0; row < rowCount; ++row) {
        for (int col = row; col < colCount; ++col) {
            // Swap matrix[row][col] with matrix[col][row]
            int temp = matrix[row][col];
            matrix[row][col] = matrix[col][row];
            matrix[col][row] = temp;
        }
    }

    // Step 2: Reverse each row (mirror horizontally)
    int left = 0;
    int right = colCount - 1;
    while (left < right) {
        for (int row = 0; row < rowCount; ++row) {
            // Swap elements at the current row between left and right columns
            int temp = matrix[row][left];
            matrix[row][left] = matrix[row][right];
            matrix[row][right] = temp;
        }
        left++;
        right--;
    }
}

Last updated