DSA Factory
Free Arrays lessonsArrays · Stage 4 · Rotation · Step 1

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.

The last value wraps round: to the front.
Rotate right by one
1
0
2
1
3
2
4
3
i

Save the last value: last = 4.

Move 1 of 5

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.

Front to back: copies the first value everywhere.
Back to front: each value moves before it's overwritten.
In code
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 nums
Quick check

Why does the shifting loop run from the end towards the start?

  1. ASo each value moves before it's overwritten
  2. BBecause it's faster
  3. 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.

Your problem

Rotate right by one

Move every value one place to the right, in place. The last value moves to the front. Return the list.

Example
nums = [1, 2, 3, 4] → [4, 1, 2, 3]

0 ≤ n ≤ 1,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve