Rotate Matrix
Java coding interview problem for Matrix Problems: Rotate Matrix.
Matrix rotation is one of the most frequently asked matrix problems in coding interviews.
It is a natural extension of:
- Matrix Transpose
- 2D Array Traversal
- Index Mapping
- In-place Transformation
This problem tests whether you understand how elements move inside a matrix.
Common interview variations:
- Rotate matrix 90 degrees clockwise
- Rotate matrix 90 degrees anti-clockwise
- Rotate matrix 180 degrees
- Rotate image in-place
What is Matrix Rotation?
Matrix rotation means changing the position of elements by rotating the entire matrix around its center.
The most common requirement:
Rotate Matrix 90 Degrees Clockwise
Example 1 — 90 Degree Clockwise Rotation
Input:
1 2 3
4 5 6
7 8 9
After rotation:
7 4 1
8 5 2
9 6 3
Understanding Element Movement
Original position:
matrix[i][j]
After 90 degree clockwise rotation:
matrix[j][n-1-i]
Example:
Element:
1
Position:
[0][0]
moves to:
[0][2]
Element:
3
Position:
[0][2]
moves to:
[2][2]
Clockwise vs Anti-Clockwise Rotation
Clockwise Rotation
Direction:
Right → Down → Left → Up
Example:
Before:
1 2 3
4 5 6
7 8 9
After:
7 4 1
8 5 2
9 6 3
Anti-Clockwise Rotation
Direction:
Left → Down → Right → Up
Result:
3 6 9
2 5 8
1 4 7
Why Is Matrix Rotation Asked in Interviews?
Interviewers test:
1. Index Transformation
Can you understand:
old position
↓
new position
2. In-place Algorithm Design
Can you modify:
same matrix
without extra memory?
3. Matrix Manipulation Skills
Important for:
- Image processing
- Grid problems
- Game boards
- Computer vision
4. Problem Decomposition
Can you break:
Rotation
into:
Transpose
+
Reverse
Real-World Applications
Image Processing
Images are represented as:
Pixel Matrix
Rotation changes image orientation.
Examples:
- Camera rotation
- Photo editing
- Computer vision
Gaming
Game boards:
Chess
Tetris
Puzzle games
require rotation operations.
Machine Learning
Matrix transformations are used in:
- Feature transformations
- Tensor operations
- Data preprocessing
Robotics
Coordinate transformations use matrix rotation.
Problem Statement
Given an:
n × n matrix
rotate the matrix:
90 degrees clockwise
The rotation must be performed:
in-place
without creating another matrix.
Example
Input:
[
[1,2,3],
[4,5,6],
[7,8,9]
]
Output:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Constraints
Example:
1 <= n <= 20
Matrix:
n × n
Values:
-1000 <= matrix[i][j] <= 1000
Square Matrix Requirement
The in-place rotation algorithm works for:
n × n
matrices.
Examples:
2 × 2
3 × 3
4 × 4
Why Only Square Matrices?
Example:
2 × 3 Matrix
Before:
1 2 3
4 5 6
After rotation:
4 1
5 2
6 3
Dimensions change:
2 × 3
becomes
3 × 2
The original memory structure cannot directly hold this.
Matrix Visualization
Input:
1 2 3
4 5 6
7 8 9
Coordinates:
[0][0] [0][1] [0][2]
[1][0] [1][1] [1][2]
[2][0] [2][1] [2][2]
After rotation:
7 4 1
8 5 2
9 6 3
Coordinates change:
[0][2] → [0][0]
[1][2] → [0][1]
[2][2] → [0][2]
Mathematical Concept Behind Rotation
For a matrix:
n × n
clockwise rotation has two operations:
Step 1
Transpose:
Rows become columns
Step 2
Reverse every row.
Example:
Original:
1 2 3
4 5 6
7 8 9
Transpose:
1 4 7
2 5 8
3 6 9
Reverse rows:
7 4 1
8 5 2
9 6 3
Rotation Algorithm
Method 1
Create a new matrix.
Steps:
- Create result matrix.
- Move:
result[j][n-1-i] = matrix[i][j]
Method 2 (Optimal)
Transpose + Reverse.
Steps:
- Swap:
matrix[i][j]
with
matrix[j][i]
- Reverse each row.
Dry Run Example
Input:
1 2 3
4 5 6
7 8 9
Step 1: Transpose
Swap:
2 ↔ 4
3 ↔ 7
6 ↔ 8
Result:
1 4 7
2 5 8
3 6 9
Step 2: Reverse Rows
Row 1:
1 4 7
becomes:
7 4 1
Row 2:
2 5 8
becomes:
8 5 2
Row 3:
3 6 9
becomes:
9 6 3
Final:
7 4 1
8 5 2
9 6 3
Approach 1 — Using Extra Matrix
The easiest approach is creating a new matrix.
Algorithm
For every element:
Original:
matrix[i][j]
Move to:
result[j][n-1-i]
Java Program
import java.util.Arrays;
public class RotateMatrixExtraSpace {
public static int[][] rotate(
int[][] matrix) {
int n =
matrix.length;
int[][] result =
new int[n][n];
for (int i = 0;
i < n;
i++) {
for (int j = 0;
j < n;
j++) {
result[j][n - 1 - i] =
matrix[i][j];
}
}
return result;
}
public static void main(String[] args) {
int[][] matrix =
{
{1,2,3},
{4,5,6},
{7,8,9}
};
int[][] result =
rotate(matrix);
for (int[] row : result) {
System.out.println(
Arrays.toString(row));
}
}
}
Output
[7,4,1]
[8,5,2]
[9,6,3]
Step-by-Step Explanation
Input:
1 2 3
4 5 6
7 8 9
Element:
1
Position:
[0][0]
New position:
[0][2]
Element:
3
Position:
[0][2]
New position:
[2][2]
Element:
7
Position:
[2][0]
New position:
[0][0]
Complexity Analysis
Every element is processed once.
Time:
O(n²)
Space:
O(n²)
Advantages
- Simple logic.
- Easy to understand.
- Works for all square matrices.
Drawbacks
- Uses extra memory.
- Not the expected optimal interview solution.
Approach 2 — Transpose + Reverse Approach (Optimal)
The optimal solution rotates a matrix 90 degrees clockwise without using extra space.
The idea:
Rotate Matrix
=
Transpose
+
Reverse Rows
Algorithm
Step 1 — Transpose Matrix
Swap:
matrix[i][j]
with
matrix[j][i]
Only swap upper triangle elements:
j = i + 1
to avoid duplicate swapping.
Step 2 — Reverse Each Row
After transpose:
Reverse every row
Example
Input:
1 2 3
4 5 6
7 8 9
Step 1: Transpose
Swap:
2 ↔ 4
3 ↔ 7
6 ↔ 8
Result:
1 4 7
2 5 8
3 6 9
Step 2: Reverse Rows
Row 1:
1 4 7
becomes:
7 4 1
Row 2:
2 5 8
becomes:
8 5 2
Row 3:
3 6 9
becomes:
9 6 3
Final Output:
7 4 1
8 5 2
9 6 3
Java Program — In-Place Rotation
public class RotateMatrixInPlace {
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;
int right = n - 1;
while (left < right) {
int temp =
matrix[i][left];
matrix[i][left] =
matrix[i][right];
matrix[i][right] =
temp;
left++;
right--;
}
}
}
public static void main(String[] args) {
int[][] matrix =
{
{1,2,3},
{4,5,6},
{7,8,9}
};
rotate(matrix);
for (int[] row : matrix) {
for (int value : row) {
System.out.print(
value + " ");
}
System.out.println();
}
}
}
Output
7 4 1
8 5 2
9 6 3
Step-by-Step Explanation
Input:
1 2 3
4 5 6
7 8 9
Transpose Phase
Initial:
1 2 3
4 5 6
7 8 9
Swap:
matrix[0][1]
with
matrix[1][0]
Result:
1 4 3
2 5 6
7 8 9
Swap:
matrix[0][2]
with
matrix[2][0]
Result:
1 4 7
2 5 6
3 8 9
Swap:
matrix[1][2]
with
matrix[2][1]
Result:
1 4 7
2 5 8
3 6 9
Reverse Rows
Before:
1 4 7
2 5 8
3 6 9
After reversing:
7 4 1
8 5 2
9 6 3
Complexity Analysis
For:
n × n matrix
Transpose:
O(n²)
Reverse:
O(n²)
Overall:
Time Complexity: O(n²)
Space:
O(1)
Advantages
- Optimal memory usage.
- Modifies matrix in-place.
- Industry preferred approach.
- Used in image rotation problems.
Drawbacks
- Works only for square matrices.
- Slightly harder to understand.
Approach 3 — Layer by Layer Rotation
Another in-place approach is rotating the matrix layer by layer.
A matrix contains:
Outer layer
Inner layer
Center element
Example
Matrix:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Layers:
Outer:
1 2 3 4
5 8
9 12
13 14 15 16
Inner:
6 7
10 11
Rotation Process
For every layer:
Move four sides:
Top → Right
Right → Bottom
Bottom → Left
Left → Top
Java Program
public class RotateMatrixLayer {
public static void rotate(
int[][] matrix) {
int n =
matrix.length;
for (int layer = 0;
layer < n / 2;
layer++) {
int first = layer;
int last = n - 1 - layer;
for (int i = first;
i < last;
i++) {
int offset =
i - first;
int top =
matrix[first][i];
// Left -> Top
matrix[first][i] =
matrix[last - offset]
[first];
// Bottom -> Left
matrix[last - offset]
[first] =
matrix[last][last-offset];
// Right -> Bottom
matrix[last][last-offset] =
matrix[i][last];
// Top -> Right
matrix[i][last] =
top;
}
}
}
}
Complexity Analysis
Time:
O(n²)
Space:
O(1)
90 Degree Anti-Clockwise Rotation
For anti-clockwise rotation:
Steps:
- Transpose matrix.
- Reverse columns.
Example
Input:
1 2 3
4 5 6
7 8 9
Transpose:
1 4 7
2 5 8
3 6 9
Reverse columns:
3 6 9
2 5 8
1 4 7
Output:
3 6 9
2 5 8
1 4 7
180 Degree Rotation
Two possible approaches:
Method 1
Rotate 90 degrees twice.
Rotate 90°
+
Rotate 90°
Method 2
Reverse:
- Rows
- Columns
Example:
Input:
1 2 3
4 5 6
7 8 9
Output:
9 8 7
6 5 4
3 2 1
Java Streams Approach
Matrix rotation requires:
- Index transformation
- Mutation
- Position tracking
Streams are not ideal.
Traditional loops are preferred.
Comparison of All Approaches
| Approach | Time | Space | Best Use |
|---|---|---|---|
| Extra Matrix | O(n²) | O(n²) | Simple solution |
| Transpose + Reverse | O(n²) | O(1) | Best interview solution |
| Layer Rotation | O(n²) | O(1) | Advanced in-place solution |
| Streams | O(n²) | O(n²) | Learning only |
Matrix Index Mapping
For clockwise rotation:
Original:
(i,j)
moves to:
(j,n-1-i)
Example:
Matrix:
3 × 3
Element:
[0][1]
moves to:
[1][2]
Primitive vs Object Arrays
Primitive Matrix
int[][]
Advantages:
- Faster.
- Less memory.
- Better cache performance.
Object Matrix
Integer[][]
Advantages:
- Supports collections.
- Allows null values.
Disadvantages:
- More memory.
Common Interview Mistakes
Mistake 1
Swapping complete matrix.
Wrong:
for(i=0;i<n;i++)
for(j=0;j<n;j++)
This swaps elements multiple times.
Mistake 2
Not limiting transpose loop.
Correct:
j = i + 1
Mistake 3
Confusing:
Transpose
with:
Rotation
Mistake 4
Trying in-place rotation on rectangular matrices.
Edge Cases
| Input | Output |
|---|---|
[[1]] |
[[1]] |
2×2 matrix |
Works |
3×3 matrix |
Works |
| Empty matrix | Handle separately |
| Single row | Requires extra matrix |
Interview Follow-up Questions
Q1. Rotate matrix 90 degrees clockwise.
Q2. Rotate matrix 90 degrees anti-clockwise.
Q3. Rotate matrix 180 degrees.
Q4. Solve without extra space.
Q5. Rotate rectangular matrix.
Q6. Explain index mapping.
Q7. Rotate image in-place.
Related Problems
- Matrix Transpose
- Spiral Matrix
- Set Matrix Zeroes
- Search a 2D Matrix
- Flood Fill
- Number of Islands
- Sudoku Validator
Key Takeaways
Matrix rotation is built using simple transformations.
For 90-degree clockwise rotation:
Transpose
+
Reverse Rows
Optimal solution:
Time: O(n²)
Space: O(1)
The most important interview concept:
Break a complex matrix transformation into smaller operations.
Frequently Asked Interview Questions
Q1. How do you rotate a matrix?
Transpose and reverse rows.
Q2. Why transpose first?
Transpose changes:
rows → columns
which is required for rotation.
Q3. Can it be done without extra space?
Yes, for square matrices.
Q4. What is the complexity?
Every element is processed:
O(n²)
Interview Tip
When asked:
"Rotate Matrix."
Explain:
- Identify matrix type.
- If square:
- Transpose
- Reverse rows
- If rectangular:
- Create new matrix.
For senior interviews, explain the transformation:
Old Index → New Index
because that demonstrates strong matrix problem-solving skills.