Rotate Image - Problem

You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees clockwise.

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Input & Output

Example 1 — 3×3 Matrix
$ Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]
💡 Note: After 90° clockwise rotation: first row [1,2,3] becomes last column [1,2,3], second row [4,5,6] becomes middle column [4,5,6], third row [7,8,9] becomes first column [7,8,9]
Example 2 — 4×4 Matrix
$ 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]]
💡 Note: Each element moves to its rotated position: element at (0,0) which is 5 moves to (0,3), element at (0,1) which is 1 moves to (1,3), etc.
Example 3 — 1×1 Matrix
$ Input: matrix = [[1]]
Output: [[1]]
💡 Note: Single element matrix remains unchanged after rotation

Constraints

  • 1 ≤ matrix.length ≤ 20
  • matrix.length == matrix[i].length
  • -1000 ≤ matrix[i][j] ≤ 1000

Visualization

Tap to expand
Rotate Image - Layer by Layer Rotation INPUT Original 3x3 Matrix 1 2 3 4 5 6 7 8 9 Outer Layer matrix = [[1,2,3], [4,5,6],[7,8,9]] 90° ALGORITHM STEPS 1 Identify Layers n/2 layers to rotate 2 4-Way Swap Rotate 4 corners at once 1 3 7 9 3 Process Each Element Move along layer edge 4 Repeat Inner Layers Until center reached temp = matrix[i][j] matrix[i][j] = matrix[n-j-1][i] matrix[n-j-1][i] = ... // 4-way rotation FINAL RESULT Rotated 90° Clockwise 7 4 1 8 5 2 9 6 3 Corners swapped Output: [[7,4,1], [8,5,2],[9,6,3]] OK - In-Place! Time: O(n^2) | Space: O(1) Key Insight: Layer-by-layer rotation swaps 4 elements at a time using only one temp variable. For each position in a layer, we perform: top-->right-->bottom-->left-->top. This achieves O(1) space complexity by modifying the matrix in-place without allocating additional memory for a new matrix. TutorialsPoint - Rotate Image | Layer by Layer Rotation Approach
Asked in
Apple 25 Microsoft 20 Amazon 18 Google 15
89.5K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen