Skip to content
mlmentorship

Rotate Image

Rotate a square matrix 90 degrees clockwise in place.

Published · 3 min read ·Core ·Mixed

30-second answer map

Visual first · depth when needed

Reverse row order, then swap every above-diagonal cell with its reflected below-diagonal partner.

Preparing the visual…

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

How practice works

ML breadth · closed-book attempt

Rotate Image

Explain the mechanism, why it works, when it fails, and one alternative.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

Rotate a square matrix 90 degrees clockwise in place.

Start with the concrete trace below. It shows the state the algorithm must carry as it runs.

Problem trace

Rotate Image: Reverse row order, then swap every above-diagonal cell with its reflected below-diagonal partner.

Input and goalRotate a square matrix 90 degrees clockwise in place.
Start with the original coordinatesThe 3x3 input is [[1,2,3],[4,5,6],[7,8,9]] before any in-place mutation.
1value 12value 23value 34value 45value 56value 67value 78value 89value 9
actioninitialize

Recognize it
Use this transformation for a square matrix that must rotate 90 degrees clockwise without allocating a second matrix.
Keep true
After row reversal, values have moved from (r,c) to (n-1-r,c); after transposition, each reaches (c,n-1-r), exactly its clockwise coordinate.
Reuse it
Derive a target coordinate mapping, then factor it into simple reversible transforms whose in-place loops visit each swap pair exactly once.
Read it this way: The 3x3 input is [[1,2,3],[4,5,6],[7,8,9]] before any in-place mutation. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.

Pattern: Reverse rows, then transpose.

Simple idea: Reversing row order moves the bottom to the top. Swapping across the main diagonal then puts every value in its clockwise position.

def rotate_image(matrix: list[list[int]]) -> None:
   matrix.reverse()
   for row in range(len(matrix)):
      for col in range(row + 1, len(matrix)):
         matrix[row][col], matrix[col][row] = matrix[col][row], matrix[row][col]

Cost: time and space.