Solution: Rotate Image
Let's solve the Rotate Image problem using the Matrices pattern.
We'll cover the following
Statement
Given an 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
-
matrix.length
-
matrix[i][j]
Solution
The idea is to make groups of four cells and rotate them by 90 degrees clockwise.
Here’s how the algorithm works:
-
We run a loop where
row
ranges from0
ton / 2
.-
Within this loop, we run a nested loop where
col
ranges fromrow
ton - row - 1
. These loops traverse the groups of four cells in the matrix. In this nested loop, we perform three swaps:-
The value of the top-left cell is swapped with the value of the top-right cell.
-
The value of the top-left cell is swapped with the value of the bottom-right cell.
-
The value of the top-left cell is swapped with the value of the bottom-left cell.
-
-
The current group of four cells has been rotated by degrees. We now move to the next iteration of the outer loop to rotate the next group.
-
-
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.