Rotate an array of n elements to the right by k steps.
For example, with
n = 7 and
k = 3, the array
[1,2,3,4,5,6,7] is rotated to
What the question really means
I have no idea what “rotate by k steps” means. But from LeetCode’s test cases it looks like this:
nums = [1, 2, 3, 4, 5],
k = 3, expected: keep the last k items, and move the front items to the end.
Another challenge is I have to do in-place mutation to the original array. So I need to use mutating functions such as:
- Get the real “k” by
k % nums.lengthbecause rotating n or n’s multiple steps doesn’t change the array.
Array.prototyp.spliceto remove the front items, and save the removed items to a variable.
- Loop the removed items array and add every items back to the end of the remaining array.