Easy Two Pointers Arrays & Strings
In plain English: You're given a list of numbers and need to flip the order without creating a new list.
Two pointers converging from opposite ends is the go-to for symmetric array operations — each swap brings both ends closer to the center.
Prompt
Given an array a, reverse it in-place.
Try to write it from scratch before scrolling down.
Solution
def reverse(a):
l, r = 0, len(a) - 1
# converge from both ends
while l < r:
a[l], a[r] = a[r], a[l]
l += 1
r -= 1
return a
# Test: reverse([1,2,3,4,5]) == [5,4,3,2,1]