Arrays and Iteration
Reverse Array In Place (Two Pointers)
Walk two indices toward each other from the ends of the array, swapping at each step. The two-pointer pattern with the smallest possible state. The loop stops when the indices meet or cross.
Algorithm
The canonical input [1, 2, 3, 4, 5, 6, 7] reverses to
[7, 6, 5, 4, 3, 2, 1] after three swaps. The middle element at index 3
is untouched because the pointers meet there.
Basic Implementation
basic.py
arr = [1, 2, 3, 4, 5, 6, 7]
left = 0
right = len(arr) - 1
while left < right:
arr[left], arr[right] = arr[right], arr[left]
left = left + 1
right = right - 1
print(arr)
Complexity
- Time: O(n)
- Space: O(1)
Implementation notes
- Python:
arr[left], arr[right] = arr[right], arr[left]reads as a single swap statement. Avoidarr.reverse()orarr[::-1]; both hide the step-by-step pointer walk the lesson is teaching. - Replay highlights both
leftandrightper frame plus the new array contents after each swap, matching the lesson spec.
two pointers
Indices walk toward each other and swap.