Changing a value in place
Swap the first and last values. About 6 minutes.
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
The array is 3, 8, 1, 6. Someone swaps the ends without a spare: first they copy the last box into the first, then the first into the last. What's left?
- A6, 8, 1, 3
- B6, 8, 1, 6
- C3, 8, 1, 3
Show the answer
6, 8, 1, 6. The first copy puts 6 in box 0 and the 3 is gone. The second copy moves that 6 back. That's why a swap needs a spare.
Swap the ends
You get a list of numbers. Swap the first and last values, then return the list. Everything in between stays where it is.
nums = [3, 8, 1, 6] → [6, 8, 1, 3]
1 ≤ n ≤ 100 · with one value, swapping it with itself changes nothing