algorithmfree
Reverse an array in place
Swap the two ends and walk inward. No second array needed.
- time
- O(n)
- space
- O(1)
// step through it
step 1 / 6
1function reverseInPlace(nums) {2 let lo = 0, hi = nums.length - 1;3 while (lo < hi) {4 [nums[lo], nums[hi]] = [nums[hi], nums[lo]];5 lo++;6 hi--;7 }8 return nums;9}- 3lo
- 8
- 1
- 9
- 4hi
lo starts at the first item and hi at the last.
How it works
Put one pointer at each end. Swap the two items, then move both pointers one step toward the middle. When they meet, every item has moved to its mirror position. Each item is touched once, so it is O(n) time, and only two index variables are used, so it is O(1) extra space.
Practice spotting this pattern →