Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Rotate Image

LeetCode #48Medium
90° in place · transpose+reverse or 4-cycles

Given an n x n matrix representing an image, rotate it 90 degrees clockwise in place, modifying the matrix directly without allocating another 2D array.

Asked atAmazonMicrosoftApple
step 1 / 18
3 × 3 image
1
2
3
4
5
6
7
8
9
Transpose + reverse rows
1given matrix (n × n)
2// phase 1: transpose
3for r in 0..n−1: for c in r+1..n−1:
4 swap M[r][c], M[c][r]
5// phase 2: reverse each row
6for each row:
7 swap M[r][c], M[r][n−1−c]
8done
state
  • plantranspose → reverse rows

line 1Rotate the image 90° clockwise IN PLACE (no second matrix). A clean two-step recipe: first TRANSPOSE (mirror across the main diagonal), then REVERSE each row. Together that equals a clockwise quarter-turn.