|
| 1 | +# Rotate Image |
| 2 | + |
| 3 | +## Problem Statement |
| 4 | + |
| 5 | +You are given an `n x n` 2D `matrix` representing an image, rotate the image by 90 degrees (clockwise). |
| 6 | + |
| 7 | +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. |
| 8 | + |
| 9 | +## Examples |
| 10 | + |
| 11 | +**Example 1:** |
| 12 | +``` |
| 13 | +Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] |
| 14 | +Output: [[7,4,1],[8,5,2],[9,6,3]] |
| 15 | +``` |
| 16 | + |
| 17 | +## Approach |
| 18 | + |
| 19 | +### Method 1: Transpose + Reverse (Recommended) |
| 20 | +1. Transpose the matrix (swap rows and columns) |
| 21 | +2. Reverse each row |
| 22 | +3. Most efficient approach |
| 23 | + |
| 24 | +**Time Complexity:** O(n²) - Two passes |
| 25 | +**Space Complexity:** O(1) - In-place modification |
| 26 | + |
| 27 | +### Method 2: Layer by Layer Rotation |
| 28 | +1. Rotate matrix layer by layer |
| 29 | +2. Use four-way swap for each layer |
| 30 | +3. Less efficient than transpose approach |
| 31 | + |
| 32 | +**Time Complexity:** O(n²) - Two passes |
| 33 | +**Space Complexity:** O(1) - In-place modification |
| 34 | + |
| 35 | +## Algorithm |
| 36 | + |
| 37 | +``` |
| 38 | +1. Transpose matrix: matrix[i][j] = matrix[j][i] |
| 39 | +2. Reverse each row: matrix[i][j] = matrix[i][n-1-j] |
| 40 | +``` |
| 41 | + |
| 42 | +## Key Insights |
| 43 | + |
| 44 | +- **Transpose**: Swap rows and columns |
| 45 | +- **Reverse**: Reverse each row after transpose |
| 46 | +- **Local Optimum**: Efficient matrix transformation |
| 47 | +- **Global Optimum**: 90-degree clockwise rotation |
| 48 | + |
| 49 | +## Alternative Approaches |
| 50 | + |
| 51 | +1. **Layer by Layer**: Rotate layer by layer |
| 52 | +2. **Four-way Swap**: Use four-way swap for each element |
| 53 | +3. **Brute Force**: Create new matrix and copy |
| 54 | + |
| 55 | +## Edge Cases |
| 56 | + |
| 57 | +- Single element: Return as is |
| 58 | +- 2x2 matrix: Handle appropriately |
| 59 | +- Large matrix: Handle efficiently |
| 60 | +- Empty matrix: Return empty matrix |
| 61 | + |
| 62 | +## Applications |
| 63 | + |
| 64 | +- Matrix algorithms |
| 65 | +- Image processing |
| 66 | +- Algorithm design patterns |
| 67 | +- Interview preparation |
| 68 | +- System design |
| 69 | + |
| 70 | +## Optimization Opportunities |
| 71 | + |
| 72 | +- **Transpose + Reverse**: Most efficient approach |
| 73 | +- **Space Optimization**: O(1) space complexity |
| 74 | +- **Quadratic Time**: O(n²) time complexity |
| 75 | +- **No Extra Space**: Use only necessary space |
0 commit comments