Problem Statement
Rotate Image
You are given an n x n grid of numbers, which stands for an image. Your job is to turn the whole grid 90 degrees clockwise, like rotating a photo a quarter turn to the right. You have to do it "in-place," which means you change the same grid instead of building a new one. Here is the trick. A 90-degree clockwise turn is the same as doing two simpler moves in a row. First you "transpose" the grid, then you reverse each row. Transpose means you flip the grid across its main diagonal (the line from the top-left corner to the bottom-right corner), so the rows become columns and the columns become rows. After the transpose, you just flip each row back-to-front. That gives you the rotated image, and it is easier to get right than trying to spin the numbers all at once.
Signals to notice
Brute force first
Create new matrix, copy rotated positions. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.
The key insight
Transpose the matrix (swap rows and columns), then reverse each row. Or rotate layer by layer with four-way swaps. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.
Trace it on matrix=[[1,2,3],[4,5,6],[7,8,9]]
n=3. Transpose pass swaps only j>i (upper triangle), so each pair is touched once. i=0,j=1: swap (0,1)<->(1,0) -> [[1,4,3],[2,5,6],[7,8,9]] i=0,j=2: swap (0,2)<->(2,0) -> [[1,4,7],[2,5,6],[3,8,9]] i=1,j=2: swap (1,2)<->(2,1) -> [[1,4,7],[2,5,8],[3,6,9]] (transpose done) reverse row 0: [1,4,7]->[7,4,1] -> [[7,4,1],[2,5,8],[3,6,9]] reverse row 1: [2,5,8]->[8,5,2] -> [[7,4,1],[8,5,2],[3,6,9]] reverse row 2: [3,6,9]->[9,6,3] -> [[7,4,1],[8,5,2],[9,6,3]] return (in-place): [[7,4,1],[8,5,2],[9,6,3]]
What must stay true
90° clockwise rotation = transpose (swap matrix[i][j] with matrix[j][i]) followed by horizontal flip (reverse each row). These two operations compose to produce the rotation. As long as that statement keeps holding, you can trust the steps built on top of it.
Shape of the loop
n = len(matrix)
for i in 0..n-1: # transpose upper triangle only
for j in i+1..n-1:
swap(matrix[i][j], matrix[j][i])
for each row in matrix: # horizontal flip
reverse(row)Pseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Transposing the full matrix instead of just the upper triangle — swapping (i,j) and (j,i) twice puts them back. Only swap when i < j. The fix is usually to return to the meaning of each move, not just the steps themselves.