2026-09-26 — Rotate Image
Difficulty: 🟡 Medium Pattern: Matrix transpose + row reversal Time-box: 20 minutes
Problem
Given an n × n matrix, rotate it 90 degrees clockwise in place. Return nothing and do not allocate another n × n matrix.
Examples
[[1,2,3], [[7,4,1],
[4,5,6], -> [8,5,2],
[7,8,9]] [9,6,3]]
[[1]] -> [[1]]
Constraints
1 <= n <= 20; every row has exactlynelements.- Modify the input matrix in place using O(1) extra space.
Hint (open only if stuck after 10 minutes)
First transpose across the main diagonal. What simple operation on every row then creates a clockwise rotation?
Solution
def rotate(matrix: list[list[int]]) -> None:
n = len(matrix)
for row in range(n):
for col in range(row + 1, n):
matrix[row][col], matrix[col][row] = matrix[col][row], matrix[row][col]
for row in matrix:
row.reverse()
How it works. Transposition changes rows into columns. Reversing each transposed row moves the former bottom row to the rightmost column. Starting col at row + 1 swaps only one side of the diagonal; visiting both sides would undo every swap.
Complexity. Time: O(n²), because every cell is touched a constant number of times. Space: O(1), excluding loop variables.
Edge cases that matter. A 1×1 matrix is unchanged. A 2×2 matrix catches index mistakes. Repeated values can hide a broken swap, so test distinct values.
Common wrong answer. Transpose and reverse the order of rows. That rotates counter-clockwise. On [[1,2],[3,4]] it produces [[2,4],[1,3]]; clockwise is [[3,1],[4,2]].
Found a mistake? Edit this page on GitHub.