Rotate Image/Matrix
Arrangement
Problem
You are given an n x n 2D matrix
representing an image, rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
For example:


Thought Process
All rotations are essentially composite reflections (A composite transformation is when two or more transformations are combined to form a new image from the preimage); in this case, a reflection across the diagonal line of symmetry, then a reflection across the vertical line of symmetry.

Notice how we can trasform each row of the matrix into a corresponding column (i.e. the diagonal transofrmation)

After transforming the rows to columns, we can flip the columns in a horizontal fashion (i.e. across the vertical line of symmetry)
It is important to consider when swapping horizontally, you only go until the halfway point of each row.
Solution
Key Facts
We are transforming each row in the source matrix to the required column in the final matrix
We are turning corresponding rows into columns with a reflection across the diagonal. We are then performing a reflection across the vertical to flip the elements horizontally in each row.
Turning rows into columns - swap(array[i][j], array[j][i]
Horizontally flipping - swap(array[i][j], array[i][N - 1 - j]
Time Complexity
Time:
Space:
Last updated
Was this helpful?