Rotate Image
mediumLeetCode Top 100mathmatrixarrays
Problem
Given an n by n matrix representing an image, rotate it ninety degrees clockwise in place without allocating another matrix.
Examples
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]
The grid is turned a quarter clockwise.
Constraints
- • 1 <= n <= 20
- • -1000 <= cell value <= 1000
- • Rotate in place
Hints(tap to reveal)
- 1. Transpose the matrix, then reverse each row.
- 2. Both steps can run in place.
Optimal approach(spoiler)
- Transpose the matrix by swapping cell (i, j) with (j, i) for the upper triangle.
- Reverse each row so columns become correctly ordered.
- These two in-place steps compose into a clockwise rotation.
- No auxiliary matrix is needed.
- O(n^2) time, O(1) extra space.
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor