1. Problem Statement (Simple Explanation):
You’re given an n x n 2D matrix representing an image.
You must rotate the image by 90° clockwise in-place, meaning:
Modify the input matrix directly.
Do not allocate another n x n matrix.
2. Examples:
Example 1:
Input:
matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
Output (90° clockwise):
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Input:
matrix = [
[5,1,9,11],
[2,4,8,10],
[13,3,6,7],
[15,14,12,16]
]
Output:
[
[15,13,2,5],
[14,3,4,1],
[12,6,8,9],
[16,7,10,11]
]
3. Approach 1 – Transpose + Reverse Each Row (Clean & Standard):
A 90° clockwise rotation can be done in two in-place steps:
Transpose the matrix (swap rows and columns):
matrix[i][j] ↔ matrix[j][i] for i < j.
After transpose, rows become columns.
Reverse each row:
For each row, reverse the order of elements.
This combination is equivalent to rotating the matrix 90° clockwise.
Example – [ [1,2,3], [4,5,6], [7,8,9] ]:
Transpose:
[
[1,4,7],
[2,5,8],
[3,6,9]
]
Reverse each row:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Pseudo-code:
Complexity:
Time: O(n2) – every element is touched a constant number of times.
Space: O(1) extra – in-place.
4. Java code:
6. C++ code:
7. Python code:
8. JavaScript code:






Comments
Post a Comment