Problem Description
Given an n x n 2D matrix representing an image, rotate the image by 90 degrees clockwise in-place without allocating an additional matrix.
Key Insights
- The rotation can be achieved in two steps: first transpose the matrix and then reverse each row.
- Transposing the matrix swaps matrix[i][j] with matrix[j][i], converting rows into columns.
- Reversing each row post-transposition yields the desired clockwise rotation.
- This approach works in-place with O(1) extra space.
Space and Time Complexity
Time Complexity: O(n^2) since every element is processed during the transpose and row reversal. Space Complexity: O(1) as the operations are performed in-place without extra data structures.
Solution
The solution leverages a two-step in-place transformation:
- Transpose the matrix: Iterate through the matrix and swap each element (i, j) with element (j, i) for j >= i.
- Reverse each row: After the transpose, each row is reversed to rotate the matrix 90 degrees clockwise. The key trick is to realize that a transpose followed by a reverse of each row achieves the rotation without needing extra space.