All coding questions

Rotate Image

medium
LeetCode 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)
  1. Transpose the matrix by swapping cell (i, j) with (j, i) for the upper triangle.
  2. Reverse each row so columns become correctly ordered.
  3. These two in-place steps compose into a clockwise rotation.
  4. No auxiliary matrix is needed.
  5. 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