Algorithm-Day20-Rotate-Image-lc-48
π§© Problem Description
You are given an n x n
2D matrix representing an image. Rotate the image 90 degrees clockwise.
You must rotate the image in place.
Example:
1 | Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] |
π‘ Brute Force Approach (Not Allowed)
- Create a new matrix and write rotated values into it.
- β Uses O(nΒ²) extra space, violates βin-placeβ requirement.
π‘ Optimal Approach: Transpose + Reverse
β¨ Key Idea
- Transpose the matrix:
- Swap
matrix[i][j]
withmatrix[j][i]
for alli < j
.
- Swap
- Reverse each row.
This combination achieves a 90-degree clockwise rotation in place.
π’ Java Code
1 | class Solution { |
β± Time and Space Complexity
- Time Complexity: O(nΒ²)
Each element is processed twice (transpose + reverse). - Space Complexity: O(1)
Fully in-place.
βοΈ Summary
- The transpose + reverse method is an elegant solution for in-place rotation problems.
- Remember:
- Clockwise β transpose + reverse rows
- Counterclockwise β transpose + reverse columns
- This is a core pattern in matrix transformation problems.
Mastering in-place matrix tricks helps with both interviews and real-world image manipulation tasks.