DSA AnimatorREVISION VIDEOS
← Back to problems
New

Rotate Image — LeetCode 48 video explanation

Rotate an n by n matrix by 90 degrees clockwise. Do it in place, without a second matrix.

Loading videos…

DSA Animator › DSA Revision › Matrix › Rotate Image

Key moments in the Rotate Image video

0:03Problem0:10Example0:16Brute force0:28Key idea0:39Dry run0:54Code1:08Takeaway

What you will learn

Remember: clockwise rotation equals transpose, then reverse each row. Counter-clockwise is transpose, then reverse each column. The video solves Rotate Image (LeetCode 48, Medium) with the Transpose + Reverse pattern from the Matrix topic, and you can replay every step in the interactive Rotate Image animation.

Rotate Image video transcript

Problem

Rotate an n by n matrix by 90 degrees clockwise. Do it in place, without a second matrix.

Example

1 2 3, 4 5 6, 7 8 9 becomes 7 4 1, 8 5 2, 9 6 3.

Brute force

Copying into a new matrix, where row i becomes column n minus 1 minus i, is easy but uses O of n squared space. Two simple in-place steps do the same thing.

Key idea

First transpose: swap every cell across the main diagonal, so rows become columns. Then reverse each row. Together, those two steps are a 90 degree clockwise rotation.

Dry run

Transposing swaps 2 with 4, 3 with 7, and 6 with 8. The matrix is now 1 4 7, 2 5 8, 3 6 9. Reverse each row: 7 4 1, 8 5 2, 9 6 3. That is the rotated image.

Code

In code, loop over the upper triangle and swap each cell with its mirror across the diagonal. Then reverse every row with two pointers. Each cell moves a constant number of times, so it's O of n squared time and O of 1 space.

Takeaway

Remember: clockwise rotation equals transpose, then reverse each row. Counter-clockwise is transpose, then reverse each column.

More Matrix revision videos

← All 185 DSA revision videos