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: 90° Clockwise TransformationInput Matrix123456789Output Matrix74185296390° ClockwiseRows become columns (in reverse order)
Understanding the Visualization
1
Input
3×3 matrix with elements 1-9
2
Rotation
90° clockwise transformation
3
Output
Rotated matrix in-place
Key Takeaway
🎯 Key Insight: 90° rotation = transpose + reverse rows, or cycle 4 elements in layers
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