LeetCode 48: Rotate Image — Step-by-Step Visual Trace
Medium — Array | Matrix | Math | Simulation
The Problem
Given an n x n 2D matrix representing an image, rotate the image by 90 degrees clockwise in-place without using extra space.
Approach
The solution uses a two-step mathematical approach: first transpose the matrix by swapping elements across the main diagonal, then reverse each row to achieve the 90-degree clockwise rotation.
Time: O(n²) · Space: O(1)
Code
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for i in range(n):
matrix[i].reverse()
Watch It Run
Try it yourself: Open TraceLit and step through every line.
Built with TraceLit — the visual algorithm tracer for LeetCode practice.
Comments