Math & Geometry
Matrix tricks and number facts: find the simple rule (transpose, reverse, layers) instead of moving things one by one.
Spot it
Signals in the questionRotate, spiral or set zeroes in a matrix.
Digits, powers, overflow: number properties do the work.
Points on a plane: lines, distances, angles.
The idea
O(n²) time · O(1) spaceRotating a square matrix 90° clockwise is two easy moves: transpose it (swap across the diagonal), then reverse each row. Both are done in place.
Template · Transpose, then reverse rows
1def rotate(matrix):2 n = len(matrix)3 for i in range(n):4 for j in range(i + 1, n):5 matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] # transpose6 for row in matrix:7 row.reverse() # mirror8 return matrix
The template, filled in for Rotate Image. The highlighted lines are the part every problem of this kind shares.
The best, free
One of eachPractice set
Loading your mission…
Common mistakes
1Transposing every pair (j from 0), which swaps each pair twice and undoes itself.
2Reversing columns instead of rows (that rotates the other way).
3Ignoring overflow in number problems (Java/C++ int limits).
Check yourself
Question 1 of 2Rotate 90° counter-clockwise in place: