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.
Positions 0 and 4 are mirrors.
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.
n = len(nums)
for i in range(n // 2):
j = n - 1 - i
nums[i], nums[j] = nums[j], nums[i]
return numsA loop swaps every box with its mirror, all the way from the first box to the last. What happens to 1, 2, 3?
- AIt stays 1, 2, 3
- BIt becomes 3, 2, 1
- 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.
Reverse in place
Reverse the list by changing it in place, then return it. Don't build a second list.
nums = [1, 2, 3, 4, 5] → [5, 4, 3, 2, 1]
0 ≤ n ≤ 1,000,000