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.
DSA Animator › DSA Revision › Arrays › Rotate Array
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 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.
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.
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.
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.
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.
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.
Remember: rotate right by k means reverse all, reverse the first k, reverse the rest. Always take k mod n first.