Given an integer array nums, rotate the array to the right by k steps, where k is non-negative. Must be done in-place with O(1) extra space.
nums = [1,2,3,4,5,6,7], k = 3[5,6,7,1,2,3,4]Rotating right by k is equivalent to bringing the last k elements to the front. Reversing all elements flips the order. Reversing the first k elements fixes the "last k" portion into sorted order. Reversing the remaining n−k elements fixes the "first n−k" portion. Three in-place reversals = one rotation.
Rotating one step at a time, k times, is O(n) times k. Copying into a new array works in O(n) time, but uses O(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.
Rotate right by k means reverse all, reverse the first k, reverse the rest. Always take k mod n first.
Run the animation above on your own input, or watch the 1:24 video explanation of Rotate Array with a dry run and Java code.