Rotate right by one
The last value moves to the front; everything else shifts right. About 7 minutes.
Everyone shuffles one seat along
Picture people on a row of chairs. Everyone moves one chair to the right, and the person on the last chair walks round to the first. That's rotating right by one: 1, 2, 3, 4 becomes 4, 1, 2, 3.
In an array, "moving along" means copying each value into the box to its right. The value that falls off the end needs to be saved first, because its box is about to be overwritten.
Save the last value: last = 4.
Shift from the back, not the front
Save the last value. Then copy values one box to the right, starting at the end and working towards the front. Finally, put the saved value in the first box.
Why from the back? If you start at the front, the first value gets copied into the second box, then that copy into the third, and so on. Every box ends up holding the first value. Working from the back moves each value before its box gets overwritten.
if not nums:
return nums
last = nums[-1]
for i in range(len(nums) - 1, 0, -1):
nums[i] = nums[i - 1]
nums[0] = last
return numsWhy does the shifting loop run from the end towards the start?
- ASo each value moves before it's overwritten
- BBecause it's faster
- CEither direction works
Show the answer
So each value moves before it's overwritten. Going backwards, the box on the left still holds its original value when it's copied right.
Rotate right by one
Move every value one place to the right, in place. The last value moves to the front. Return the list.
nums = [1, 2, 3, 4] → [4, 1, 2, 3]
0 ≤ n ≤ 1,000