In-Place Reversal
Arrays: lesson 5 of 8
Flip an array with one temp variable, not a copy.
Lesson 5 of 8 · 4 min
In-Place Reversal
Step 1 of 8
swaps0extra memoryO(1)
left
right
1
2
3
4
5
6
Reversal needs no second array — just trade the two ends and walk inward.
The Idea
Swap the first and last elements, then step both indexes inward and repeat. After n/2 swaps the whole array is reversed. Time is O(n) and extra space is O(1).
Real-World Example
Think of reversing the play queue on your phone. The app cannot afford a second copy of a 5,000-song queue in memory, so it swaps the ends inward until the order flips.
The Code
def reverse(nums):
left, right = 0, len(nums) - 1
while left < right:
# swap the two ends, then step inward
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
return nums
print(reverse([1, 2, 3, 4, 5])) # [5, 4, 3, 2, 1]
# n // 2 swaps, no second array -> O(n) time, O(1) space
Your turn
What does this print?
a = [1, 2, 3, 4]
l, r = 0, 3
while l < r:
a[l], a[r] = a[r], a[l]
l += 1
r -= 1
print(a)Mini quiz
1 / 3