# Solution: Rotate Image

Let's solve the Rotate Image problem using the Matrices pattern.

We'll cover the following

## Statement

Given an $n \times n$ matrix, rotate the matrix 90 degrees clockwise. The performed rotation should be in place, i.e., the given matrix is modified directly without allocating another matrix.

Note: The function should only return the modified input matrix.

Constraints:

• matrix.length $=$ matrix[i].length
• $1 \leq$ matrix.length $\leq 20$
• $-10^3 \leq$ matrix[i][j] $\leq 10^3$

## Solution

The idea is to make groups of four cells and rotate them by 90 degrees clockwise.

Hereâ€™s how the algorithm works:

1. We run a loop where row ranges from 0 to n / 2.

1. Within this loop, we run a nested loop where col ranges from row to n - row - 1. These loops traverse the groups of four cells in the matrix. In this nested loop, we perform three swaps:

1. The value of the top-left cell is swapped with the value of the top-right cell.

2. The value of the top-left cell is swapped with the value of the bottom-right cell.

3. The value of the top-left cell is swapped with the value of the bottom-left cell.

2. The current group of four cells has been rotated by $90$ degrees. We now move to the next iteration of the outer loop to rotate the next group.

2. We repeat the process above until the whole matrix has been rotated.

Letâ€™s look at the following illustration to get a better understanding of the solution:

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.