18. Rotate Image
mediumAsked at UnityRotate an n×n matrix 90 degrees in-place — a direct model of the 2D texture rotation Unity applies when normalizing atlas sprites or computing orthographic transform matrices without allocating new buffers.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees clockwise in-place. You must modify the input matrix directly without allocating another 2D matrix.
Constraints
n == matrix.length == matrix[i].length1 <= n <= 20-1000 <= matrix[i][j] <= 1000
Examples
Example 1
matrix = [[1,2,3],[4,5,6],[7,8,9]][[7,4,1],[8,5,2],[9,6,3]]Explanation: Transpose then reverse each row gives a 90-degree clockwise rotation.
Example 2
matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]][[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]Approaches
1. Extra matrix
Allocate a copy; place matrix[i][j] at copy[j][n-1-i]. Then copy back. Clear but uses O(n^2) extra space.
- Time
- O(n^2)
- Space
- O(n^2)
function rotate(matrix) {
const n = matrix.length;
const copy = matrix.map(r => [...r]);
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
matrix[j][n - 1 - i] = copy[i][j];
}
}
}Tradeoff:
2. Transpose then reverse rows
Step 1: transpose in-place (swap matrix[i][j] with matrix[j][i] for j>i). Step 2: reverse each row. Achieves 90-degree clockwise rotation with O(1) extra space.
- Time
- O(n^2)
- Space
- O(1)
function rotate(matrix) {
const n = matrix.length;
// transpose
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
[matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
}
}
// reverse each row
for (let i = 0; i < n; i++) {
matrix[i].reverse();
}
}Tradeoff:
Unity-specific tips
Unity engineers expect you to name the two-step pattern (transpose + row-reverse) and connect it to how a rotation matrix decomposes — saying 'this mirrors what Matrix4x4.TRS does for 2D orthographic cases' signals you understand transform math, not just array mechanics.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Rotate Image and other Unity interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →