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)
  1. arr ← [1, 2, 3, 4, 5, 6, 7]

    1arr = [1, 2, 3, 4, 5, 6, 7]2left = 0
    values this step[1, 2, 3, 4, 5, 6, 7]arr
  2. left ← 0

    1arr = [1, 2, 3, 4, 5, 6, 7]2left = 03right = len(arr) - 1
    values this step0left[1, 2, 3, 4, 5, 6, 7]arr
  3. right ← 6

    2left = 03right = len(arr) - 14while left < right:
    values this step6right[1, 2, 3, 4, 5, 6, 7]arr0left
  4. arr ← [7, 2, 3, 4, 5, 6, 1]

    4while left < right:5    arr[left], arr[right] = arr[right], arr[left]6    left = left + 1
    values this step[1, 2, 3, 4, 5, 6, 7] [7, 2, 3, 4, 5, 6, 1]arr0left6right
  5. left ← 1

    5arr[left], arr[right] = arr[right], arr[left]6left = left + 17right = right - 1
    values this step0 1left
  6. right ← 5

    6    left = left + 17    right = right - 18print(arr)
    values this step6 5right
  7. arr ← [7, 6, 3, 4, 5, 2, 1]

    4while left < right:5    arr[left], arr[right] = arr[right], arr[left]6    left = left + 1
    values this step[7, 2, 3, 4, 5, 6, 1] [7, 6, 3, 4, 5, 2, 1]arr1left5right
  8. left ← 2

    5arr[left], arr[right] = arr[right], arr[left]6left = left + 17right = right - 1
    values this step1 2left
  9. right ← 4

    6    left = left + 17    right = right - 18print(arr)
    values this step5 4right
  10. arr ← [7, 6, 5, 4, 3, 2, 1]

    4while left < right:5    arr[left], arr[right] = arr[right], arr[left]6    left = left + 1
    values this step[7, 6, 3, 4, 5, 2, 1] [7, 6, 5, 4, 3, 2, 1]arr2left4right
  11. left ← 3

    5arr[left], arr[right] = arr[right], arr[left]6left = left + 17right = right - 1
    values this step2 3left
  12. right ← 3

    6    left = left + 17    right = right - 18print(arr)
    values this step4 3right
  13. while 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. Avoid arr.reverse() or arr[::-1]; both hide the step-by-step pointer walk the lesson is teaching.
  • Replay highlights both left and right per frame plus the new array contents after each swap, matching the lesson spec.