Reverse an array in place (two pointers)
Easy TimeO(n) SpaceO(1)
Given an array arr, reverse the order of its elements in place, with no second array, so [1, 2, 3, 4, 5, 6] becomes [6, 5, 4, 3, 2, 1]. Every element ends at the mirror of the position it started in, which leaves the middle element of an odd-length array exactly where it was.
Examples
Example 1
- Input
- arr = [1, 2, 3, 4, 5, 6]
- Output
- Six values, each ending at the mirror of where it started.
[6,5,4,3,2,1]
Example 2
- Input
- arr = [1, 2, 3]
- Output
- An odd length, so the
[3,2,1]2in the middle is its own mirror and never moves.
The Code
function reverse(arr) {
let lo = 0;
let hi = arr.length - 1;
while (lo < hi) {
const tmp = arr[lo];
arr[lo] = arr[hi];
arr[hi] = tmp;
lo++;
hi--;
}
return arr;
}
reverse([1, 2, 3, 4, 5, 6]);Done
More like this
All two pointers examples (9) →- Two sum Walk two pointers inward until the pair sums to the target.
- Most water Widest gap first; always move the shorter wall inward.
- Valid palindrome March inward from both ends, comparing as you go.
- 3Sum Fix one number, then two-pointer the rest toward zero.
- Sort colors Three pointers sweep 0s to the front and 2s to the back in one pass.
- Remove duplicates A fast reader and a slow writer compact the array in place.