DSA AnimatorREVISION VIDEOS
← Back to problems
New

Rotate Array — LeetCode 189 video explanation

Rotate the array to the right by k steps. Each step moves the last element to the front. Do it in place, with constant extra space.

Loading videos…

DSA Animator › DSA Revision › Arrays › Rotate Array

Key moments in the Rotate Array video

0:03Problem0:11Example0:20Brute force0:30Key idea0:41Dry run0:58Code1:15Takeaway

What you will learn

Remember: rotate right by k means reverse all, reverse the first k, reverse the rest. Always take k mod n first. The video solves Rotate Array (LeetCode 189, Medium) with the Reversal pattern from the Arrays topic, and you can replay every step in the interactive Rotate Array animation.

Rotate Array video transcript

Problem

Rotate the array to the right by k steps. Each step moves the last element to the front. Do it in place, with constant extra space.

Example

For 1 to 7 with k equal to 3, the answer is 5, 6, 7, 1, 2, 3, 4. The last three numbers move to the front.

Brute force

Rotating one step at a time, k times, is O of n times k. Copying into a new array works in O of n time, but uses O of n space.

Key idea

Three reversals do the whole rotation in place. Reverse the whole array, then reverse the first k numbers, then reverse the rest. If k is larger than the length, use k mod n first.

Dry run

Reversing everything turns 1 to 7 into 7, 6, 5, 4, 3, 2, 1. Reversing the first 3 numbers gives 5, 6, 7 at the front. Reversing the remaining 4 numbers gives 1, 2, 3, 4. The array is now 5, 6, 7, 1, 2, 3, 4.

Code

In code, first set k to k mod n. Then call a reverse helper three times: on the whole array, on the first k, and on the rest. The helper swaps from both ends and moves inward. Every element is swapped a constant number of times, so it's O of n time and O of 1 space.

Takeaway

Remember: rotate right by k means reverse all, reverse the first k, reverse the rest. Always take k mod n first.

More Arrays revision videos

← All 185 DSA revision videos