> For the complete documentation index, see [llms.txt](https://private-26.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://private-26.gitbook.io/notes/coding/medium/48.-rotate-image.md).

# 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   |
| ---------------- | ----------------- |
| $$\text{O}(1)$$  | $$\text{O}(N^2)$$ |

## Code

```java
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--;
    }
}

```
