Solution: Rotate Image

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

Statement

Given an n×nn \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≤1 \leq matrix.length ≤20\leq 20
  • −103≤-10^3 \leq matrix[i][j] ≤103\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 9090 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.