Algorithm: Reverse an array without additional space

Quiz1

How do you reverse an array without additional space?

Answer1

You can use the built-in list.reverse method.

https://docs.python.org/3/library/stdtypes.html#sequence.reverse

Reverse the items of the sequence in place. This method maintains economy of space when reversing a large sequence.

So you can reverse in place without additional space.

arr = [1, 2, 3]
arr.reverse()
print(arr) # [3, 2, 1]

Quiz2

What if you cannot use list.reverse?

Answer2

We can do it like this.

l, r = 0, len(arr) - 1
while l < r:
  arr[l], arr[r] = arr[r], arr[l]
  l += 1
  r -= 1