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.
- temp
- empty
Box 0 holds 3 and box 3 holds 6. We want them to trade places.
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.
temp = nums[0] nums[0] = nums[len(nums) - 1] nums[len(nums) - 1] = temp return nums