Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

The two-cup problem

You have a cup of tea and a cup of coffee, and you want to swap what's in them. You can't just pour the tea into the coffee cup: it's full, and you'd lose the coffee. You need a third, empty cup to hold one drink for a moment.

Swapping two boxes in an array is exactly the same. Copy box A into box B and box B's old value is gone. So first pour one value into a spare variable, usually called temp.

A swap needs a spare: save one value before you overwrite it.
Swapping the ends of [3, 8, 1, 6]
3
0
8
1
1
2
6
3
firstlast
temp
empty

Box 0 holds 3 and box 3 holds 6. We want them to trade places.

Move 1 of 4

Save, copy, put back

The swap is always three moves. Save the first value in the spare. Copy the last value into the first box. Then put the saved value into the last box.

Step through the picture below to watch the 3 sit safely in the spare while its box is overwritten. The boxes in the middle are never touched.

Three moves: save, copy, put back.
Skip the save: and both boxes end up with the same value.
In code
temp = nums[0]
nums[0] = nums[len(nums) - 1]
nums[len(nums) - 1] = temp
return nums