Rotate Matrix by 90°
Learn matrix rotation algorithms through interactive challenges. Master in-place matrix manipulation and transpose operations.
Rotate Matrix 90° Clockwise
Manipulate the matrix and enter your rotated solution in the input fields.
Original Matrix:
Your Matrix
Enter Your Rotated Matrix:
Your Answer
šÆ Problem Statement
Given an nĆn matrix, rotate it 90 degrees clockwise in-place. The rotation should be done without using extra space (in-place algorithm).
š” Key Concepts
Two-Step Process
Step 1: Transpose the matrix (swap rows and columns) Step 2: Reverse each row
In-Place Algorithm
The algorithm modifies the matrix in-place without using additional space, making it memory efficient.
š Algorithm Pseudo Code
function rotateMatrix90Clockwise(matrix):
n = length(matrix)
// Step 1: Transpose the matrix
for i from 0 to n-1:
for j from i to n-1:
// Swap matrix[i][j] with matrix[j][i]
temp = matrix[i][j]
matrix[i][j] = matrix[j][i]
matrix[j][i] = temp
// Step 2: Reverse each row
for i from 0 to n-1:
left = 0
right = n-1
while left < right:
// Swap matrix[i][left] with matrix[i][right]
temp = matrix[i][left]
matrix[i][left] = matrix[i][right]
matrix[i][right] = temp
left += 1
right -= 1
return matrixš Step-by-Step Example
Input Matrix:
[4, 5, 6]
[7, 8, 9]
Step 1: Transpose
[2, 5, 8]
[3, 6, 9]
Step 2: Reverse each row
[8, 5, 2]
[9, 6, 3]
Result: Matrix rotated 90° clockwise
š Visual Representation
ā±ļø Complexity Analysis
Time Complexity
O(n²) - We need to visit each element twice (transpose + reverse)
Space Complexity
O(1) - In-place algorithm, no extra space needed
š Alternative Approaches
Layer by Layer Rotation
Rotate the matrix layer by layer, starting from the outermost layer and moving inward.
Transpose + Reverse (Optimal)
Most efficient and easiest to understand approach.
š Real-world Applications
ā ļø Common Mistakes
Mistake: Trying to rotate in one step without understanding the two-step process
Mistake: Using extra space instead of in-place algorithm
Mistake: Confusing clockwise vs counterclockwise rotation
Arrow Keys: Navigate between input fields
Tab: Move to next input field
Shift + Tab: Move to previous input field
Numbers: Type directly to enter values
1. Click on two cells to swap them
2. Rotate the matrix 90° clockwise
3. Enter your answer in the input fields
4. Use arrow keys to navigate inputs
5. Click "Check Solution" when done
Step 1: Transpose the matrix
Step 2: Reverse each row
This gives you 90° clockwise rotation
Difficulty: Easy
Matrix Size: 3Ć3
Moves Made: 0
Attempts: 0
Completed Levels: 0/5