DSA Factory
Free lessonsProgramming basics · Stage 0 · Names for values · Step 3

Swapping two values

Swap what two boxes hold, with the help of a spare box. About 8 minutes.

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
Quick check

a holds 3 and b holds 8. You run a = b and then b = a, with no spare box. What do a and b hold?

  1. Aa holds 8 and b holds 8
  2. Ba holds 8 and b holds 3
  3. Ca holds 3 and b holds 8
Show the answer

a holds 8 and b holds 8. After the first line a holds 8, and the 3 is gone. The second line copies that 8 into b.

Your problem

Swap the pair

Swap the two numbers using a spare variable, then return them as a list: first the new a, then the new b.

Example
a = 3, b = 8 → [8, 3]

−1,000 ≤ a, b ≤ 1,000

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding