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. Stops when the indices meet or cross. Demonstrates the two-pointer pattern with the smallest possible state.
Algorithm
Canonical input [1, 2, 3, 4, 5, 6, 7] (odd length, middle element stays
put) yields three swap frames and reverses to [7, 6, 5, 4, 3, 2, 1].
two pointers
`left` starts at index `0`, `right` starts at `arr.length - 1`. Each loop iteration swaps `arr[left]` and `arr[right]` and moves the pointers toward each other.
Basic Implementation
basic.js
Replay: real traced execution (multi-file project)
const arr = [1, 2, 3, 4, 5, 6, 7];
let left = 0;
let right = arr.length - 1;
while (left < right) {
const tmp = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
left = left + 1;
right = right - 1;
}
console.log(JSON.stringify(arr));
arr ← [1, 2, 3, 4, 5, 6, 7]
1const arr = [1, 2, 3, 4, 5, 6, 7];2let left = 0;values this step[1, 2, 3, 4, 5, 6, 7]arrleft ← 0
1const arr = [1, 2, 3, 4, 5, 6, 7];2let left = 0;3let right = arr.length - 1;values this step0left[1, 2, 3, 4, 5, 6, 7]arrright ← 6
2let left = 0;3let right = arr.length - 1;4while (left < right) {values this step6right[1, 2, 3, 4, 5, 6, 7]arr0leftarr ← [7, 2, 3, 4, 5, 6, 1]
6arr[left] = arr[right];7arr[right] = tmp;8left = left + 1;values this step[1, 2, 3, 4, 5, 6, 7] → [7, 2, 3, 4, 5, 6, 1]arr0left6rightleft ← 1
7arr[right] = tmp;8left = left + 1;9right = right - 1;values this step0 → 1leftright ← 5
8 left = left + 1;9 right = right - 1;10}values this step6 → 5rightarr ← [7, 6, 3, 4, 5, 2, 1]
6arr[left] = arr[right];7arr[right] = tmp;8left = left + 1;values this step[7, 2, 3, 4, 5, 6, 1] → [7, 6, 3, 4, 5, 2, 1]arr1left5rightleft ← 2
7arr[right] = tmp;8left = left + 1;9right = right - 1;values this step1 → 2leftright ← 4
8 left = left + 1;9 right = right - 1;10}values this step5 → 4rightarr ← [7, 6, 5, 4, 3, 2, 1]
6arr[left] = arr[right];7arr[right] = tmp;8left = left + 1;values this step[7, 6, 3, 4, 5, 2, 1] → [7, 6, 5, 4, 3, 2, 1]arr2left4rightleft ← 3
7arr[right] = tmp;8left = left + 1;9right = right - 1;values this step2 → 3leftright ← 3
8 left = left + 1;9 right = right - 1;10}values this step4 → 3rightwhile (left < right)
3let right = arr.length - 1;4while (left < right) {5 const tmp = arr[left];values this step[7, 6, 5, 4, 3, 2, 1]arr3left3right
Complexity
- Time: O(n)
- Space: O(1)
Implementation notes
- JavaScript: use a temporary
const tmpto swap two array slots. - Never call
arr.reverse(); the lesson is teaching the two-pointer walk. - The replay shows both
leftandright, the values about to be swapped, and the array contents after the swap. The loop-exit frame is the moment the pointers meet.