PracticeNeetCode ↗LeetCode ↗
Given an n × n 2D matrix representing an image, rotate the image by 90 degrees clockwise, in place — without allocating a second matrix.
matrix[i][j] with matrix[j][i] for i < j — swapping the full range would undo itself.i < j, swap matrix[i][j] and matrix[j][i].Time: O(n²) — Space: O(1)
def rotate(matrix: list[list[int]]) -> None:
n = len(matrix)
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for row in matrix:
row.reverse()How the solution above works, piece by piece.
j > i (above the diagonal), swap matrix[i][j] and matrix[j][i]. Starting j at i + 1 ensures each pair is swapped once, not twice.row.reverse() mirrors every row.Running it on matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]:
matrix[i][j] with matrix[j][i] (the diagonal, amber, stays put). Reversing each row then turns that into a 90° clockwise rotation. Both steps work in place.