Rotate Image
LeetCode 48 · Medium · solution, intuition & step-by-step walkthrough
Transpose, then mirror each row.
This is how I solved Rotate Image (LeetCode 48), a medium problem from the Matrix pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
A 90° clockwise rotation equals a transpose (swap across the main diagonal) followed by reversing each row. Both steps are in-place swaps.
Approach
- 1
Swap matrix[i][j] with matrix[j][i] for j ≥ i.
- 2
Reverse every row by swapping its ends inward.
How I solved it
Transpose + reflectPythonO(n²) time · O(1) space
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
"""
#transpose
[1][4][7]
[2][5][8]
[3][6][9]
#reflect
[7][4][1]
[8][5][2]
[9][6][3]
"""
m = len(matrix)
n = len(matrix[0])
for i in range(m):
for j in range(i,n):
matrix[i][j],matrix[j][i]=matrix[j][i],matrix[i][j]
for i in range(m):
for j in range(n//2):
matrix[i][j],matrix[i][n-j-1]=matrix[i][n-j-1],matrix[i][j]
Rotate Image — FAQ
What is the intuition behind Rotate Image?
A 90° clockwise rotation equals a transpose (swap across the main diagonal) followed by reversing each row. Both steps are in-place swaps.
How do you solve Rotate Image (LeetCode 48)?
1. Swap matrix[i][j] with matrix[j][i] for j ≥ i. 2. Reverse every row by swapping its ends inward.
What is the time and space complexity of Rotate Image?
Time: O(n²). Space: O(1). (Accepted approach: Transpose + reflect.)
What are common mistakes in Rotate Image?
Start the transpose inner loop at j = i, or every pair is swapped twice (back to the original).