Back to questions
You are given an n x n 2D matrix representing an image, and you need to rotate the image by 90 degrees clockwise. You are basically being asked to implement the functionality of numpy.rot90(matrix, k=-1) (without actually using any helper functions or outside libraries).
Input: matrix =
Output:
Input: matrix =
Output:
Implement the rotation in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Take a closer look at the image above. Notice how each column in the original matrix ends up as a row in the rotated matrix—but with a twist: it's reversed!
With that in mind, the plan is simple. We'll track each column from the original matrix, store it in a dictionary as a list, and then reverse those lists to form the rows of the final matrix.
We don’t actually need extra space (beyond the input and expected output) to solve this problem. Instead, we can do it in place. First, we transpose the matrix (swap rows with columns), and then reverse each row.
This works because rotating a matrix 90 degrees clockwise is essentially shifting the rows into columns, which is what transposing does, and then reversing the order of the elements in each row to get the correct orientation.