DSA
Rotate matrix by 90 degrees
Covers: Brute Force, optimal. Optimal — Time O(m*n), Space O(1).
Given an N * N 2D integer matrix, rotate the matrix by 90 degrees clockwise.
The rotation must be done in place, meaning the input 2D matrix must be modified directly.
Brute Force#
Allocate a new N×N matrix. The first row of the original becomes the last column of the rotated matrix, the second row becomes the second-to-last column, and so on — concretely, result[col][n-1-row] = matrix[row][col]. Then copy back. This is straightforward but uses O(m*n) extra space, which violates the in-place requirement for large matrices.
- Use Dummy matrix
- Take first row, place in last matrix and so on
Time Complexity: O(m*n)
Space Complexity: O(m*n)
optimal Approach#
A 90° clockwise rotation is equivalent to two simpler operations applied in sequence: first transpose the matrix (mirror across the main diagonal), then reverse each row. Both operations are done in-place with only index swaps, giving O(1) extra space while preserving the same O(m*n) time complexity. The key insight is that decomposing the rotation into transpose + row-reverse avoids the need for a temporary matrix entirely.
- Take transpose of the matrix
- swap(matrix[i][j], matrix[j][i]), until j < i
- Take reverse for every row
class Solution {
public:
void rotateMatrix(vector<vector<int>>& matrix) {
int n = matrix.size();
//transpose
for(int row = 0; row < n; row++){
for(int col = 0; col < row; col++){
swap(matrix[row][col], matrix[col][row]);
}
}
//reverse each row
for(int row = 0; row < n; row++){
reverse(matrix[row].begin(), matrix[row].end());
}
}
};
Time Complexity: O(m*n)
Space Complexity: O(1)