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

Two boxes, one problem

Say a holds 3 and b holds 8, and you want them to trade places. The obvious try is to copy b into a, then copy a into b.

The first line works: a now holds 8. But the 3 that used to be in a was thrown away. The second line copies 8 into b, and now both boxes hold 8. The 3 is lost for good.

Overwriting a box: throws the old value away.
In code
a = b
b = a   # too late: a was already changed

The spare box

Think about swapping the juice in two glasses. You can't pour one into the other while both are full. You grab an empty third glass first.

In code, the empty glass is a spare variable, often called temp. Save one value there, overwrite that box, then put the saved value into the other box. Three lines, and nothing is lost.

Save first, overwrite second, then use the saved value.
In code
temp = a
a = b
b = temp
Swapping a and b
a: 3
0
b: 8
1
temp: ?
2
line
a
3
b
8

Start: a holds 3, b holds 8, and the spare box is empty.

Move 1 of 4