DSA Factory
Free Arrays lessonsArrays · Stage 3 · In-place changes · Step 2

Reverse in place

Swap mirror pairs until you reach the middle. About 8 minutes.

Every box has a mirror

Reversing a row of books on a shelf, you'd swap the first and last, then the second and second-last, and work your way in. You never need a second shelf.

Arrays are the same. The first box pairs with the last, the second with the second-last, and so on. Each box and its mirror swap places, using the three-step swap you already know.

Pair the ends: and work inwards.
Swap mirror pairs
1
0
2
1
3
2
4
3
5
4
imirror

Positions 0 and 4 are mirrors.

Move 1 of 4

Stop at the middle

Only walk the first half of the array. Each swap already moves two boxes, so by the middle every book is in place.

If you kept going to the end, the second half would swap every pair back again, and you'd end up exactly where you started. It's a very convincing bug: the code runs with no error and changes nothing.

Stop at the middle: each pair is swapped once.
Go past it: and every pair swaps back.
In code
n = len(nums)
for i in range(n // 2):
    j = n - 1 - i
    nums[i], nums[j] = nums[j], nums[i]
return nums
Quick check

A loop swaps every box with its mirror, all the way from the first box to the last. What happens to 1, 2, 3?

  1. AIt stays 1, 2, 3
  2. BIt becomes 3, 2, 1
  3. CAn error
Show the answer

It stays 1, 2, 3. Each pair is swapped twice: once on the way to the middle and once after it. Stop at the middle.

Your problem

Reverse in place

Reverse the list by changing it in place, then return it. Don't build a second list.

Example
nums = [1, 2, 3, 4, 5] → [5, 4, 3, 2, 1]

0 ≤ n ≤ 1,000,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve