#48

Rotate Image

Medium Transpose + reverse rows

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Rotate an n × n matrix 90 degrees clockwise, in place.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: turn the picture 90° clockwise without a second matrix.

Why this works: transpose (mirror across the diagonal), then reverse each row. Together that's a clockwise turn.

Example: [[1,2,3],[4,5,6],[7,8,9]]

transpose → [[1,4,7],[2,5,8],[3,6,9]]reverse rows → [[7,4,1],[8,5,2],[9,6,3]]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Transposing with j starting at 0, which swaps every pair twice and undoes the work.

Solve on LeetCode ↗
Complexity
  • Time: O(n²).
  • Space: O(1).
Topic: 2D Arrays & Matrix
🎬 Episode 14: video coming soon