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.
two pointers
Indices walk toward each other and swap.
Basic Implementation
basic.py
Replay: real traced execution (multi-file project)
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)
arr ← [1, 2, 3, 4, 5, 6, 7]
1arr = [1, 2, 3, 4, 5, 6, 7]2left = 0values this step[1, 2, 3, 4, 5, 6, 7]arrleft ← 0
1arr = [1, 2, 3, 4, 5, 6, 7]2left = 03right = len(arr) - 1values this step0left[1, 2, 3, 4, 5, 6, 7]arrright ← 6
2left = 03right = len(arr) - 14while left < right:values this step6right[1, 2, 3, 4, 5, 6, 7]arr0leftarr ← [7, 2, 3, 4, 5, 6, 1]
4while left < right:5 arr[left], arr[right] = arr[right], arr[left]6 left = left + 1values this step[1, 2, 3, 4, 5, 6, 7] → [7, 2, 3, 4, 5, 6, 1]arr0left6rightleft ← 1
5arr[left], arr[right] = arr[right], arr[left]6left = left + 17right = right - 1values this step0 → 1leftright ← 5
6 left = left + 17 right = right - 18print(arr)values this step6 → 5rightarr ← [7, 6, 3, 4, 5, 2, 1]
4while left < right:5 arr[left], arr[right] = arr[right], arr[left]6 left = left + 1values this step[7, 2, 3, 4, 5, 6, 1] → [7, 6, 3, 4, 5, 2, 1]arr1left5rightleft ← 2
5arr[left], arr[right] = arr[right], arr[left]6left = left + 17right = right - 1values this step1 → 2leftright ← 4
6 left = left + 17 right = right - 18print(arr)values this step5 → 4rightarr ← [7, 6, 5, 4, 3, 2, 1]
4while left < right:5 arr[left], arr[right] = arr[right], arr[left]6 left = left + 1values this step[7, 6, 3, 4, 5, 2, 1] → [7, 6, 5, 4, 3, 2, 1]arr2left4rightleft ← 3
5arr[left], arr[right] = arr[right], arr[left]6left = left + 17right = right - 1values this step2 → 3leftright ← 3
6 left = left + 17 right = right - 18print(arr)values this step4 → 3rightwhile left < right:
3right = len(arr) - 14while left < right:5 arr[left], arr[right] = arr[right], arr[left]values this step[7, 6, 5, 4, 3, 2, 1]arr3left3right
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.