Q4: How do you rotate an N x N 2D matrix 90 degrees clockwise in-place?
Rotating a matrix 90 degrees clockwise in-place involves two steps:
- Transpose the matrix: Swap
matrix[i][j]withmatrix[j][i]for all $i < j$. - Reverse each row: Swap elements from outer columns inward (
matrix[i][left]withmatrix[i][right]).
Matrix 90 Degree Rotation
public class RotateMatrix {
public static void rotate(int[][] matrix) {
int n = matrix.length;
// Step 1: Transpose
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
// Step 2: Reverse rows
for (int i = 0; i < n; i++) {
int left = 0, right = n - 1;
while (left < right) {
int temp = matrix[i][left];
matrix[i][left] = matrix[i][right];
matrix[i][right] = temp;
left++; right--;
}
}
}
}💡 Transposes the grid matrix across its main diagonal and flips rows horizontally.
Key Takeaways
- Step 1: Transpose matrix along the main diagonal.
- Step 2: Reverse elements horizontally in each row.
Knowledge Check
How would you rotate an N x N matrix 90 degrees COUNTER-clockwise in-place?