📝 Problem Details
- Title:
48. Rotate Image
- Link: https://leetcode.com/problems/rotate-image/
- Difficulty: Medium
- Tags/Categories: Math
input
n x n
2Dmatrix
representing an image rotate the image 90 degrees (clockwise) rotation has to be done in-place
💡 Explanation of Solution
1. Transpose the Matrix
- swap matrix[i][j] with matrix[j][i] for all elements above the diagonal
- this converts rows into columns
2. Reverse Each Row
- swap elements symmetrically from left to right in each row
- this achieves the 90-degree clockwise rotation
⌛ Complexity Analysis
Time Complexity: O(n^2)
Space Complexity: O(1)
💻 Implementation of Solution
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
// step 1 : transpose the matrix
for(int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
swap(matrix[i][j] , matrix[j][i]);
}
}
// step 2 : reverse each row
for(int i=0; i < n; i++) {
reverse(matrix[i].begin(), matrix[i].end());
}
}
};