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].
Basic Implementation
basic.ts
const arr: number[] = [1, 2, 3, 4, 5, 6, 7];
let left: number = 0;
let right: number = arr.length - 1;
while (left < right) {
const tmp: number = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
left = left + 1;
right = right - 1;
}
console.log(JSON.stringify(arr));
Complexity
- Time: O(n)
- Space: O(1)
Implementation notes
- TypeScript: use a temporary
const tmp: numberto swap two array slots. Never callarr.reverse(); the lesson is teaching the two-pointer walk. - Annotate
leftandrightas: numberso the index discipline is visible to the reader. - 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.
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.