DSA Factory
Free lessonsArrays · Stage 0 · What an array is · Step 3

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.

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

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?

  1. A6, 8, 1, 3
  2. B6, 8, 1, 6
  3. 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.

Your problem

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.

Example
nums = [3, 8, 1, 6] → [6, 8, 1, 3]

1 ≤ n ≤ 100 · with one value, swapping it with itself changes nothing

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