Medium Transpose + Reverse Math & Geometry
In plain English: Rotate a square grid of numbers 90 degrees clockwise without using extra space.
Transpose (swap rows and columns) then reverse each row. This two-step trick works because a 90-degree clockwise rotation = transpose + horizontal flip.
Prompt
Given an n x n 2D matrix, rotate the image by 90 degrees clockwise in-place.
Try to write it from scratch before scrolling down.
Solution
def rotate(matrix):
n = len(matrix)
# Step 1: Transpose (swap matrix[i][j] with matrix[j][i])
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Step 2: Reverse each row
for row in matrix:
row.reverse()
return matrix
# Test: rotate([[1,2,3],[4,5,6],[7,8,9]])
# == [[7,4,1],[8,5,2],[9,6,3]]