05. Reverse an Array In-Place
Reverse the order of elements in an array without using extra memory allocations.
How It Works & Algorithmic Design
This demonstrates the Two Pointers Technique:
- Pointer Setup: Position a
leftpointer at index0and arightpointer at indexarr.length - 1. - Symmetric Swapping: While
left < right:- Swap the elements at
arr[left]andarr[right]. - Increment
left(left++). - Decrement
right(right--).
- Swap the elements at
- Termination: When
left >= right, the pointers meet or cross in the middle, confirming all elements have been mirrored.
Why This Approach Works Best
Creating a duplicate reversed array requires $O(n)$ auxiliary space. The two-pointer in-place swap modifies the original array directly, achieving $O(n/2) = O(n)$ time complexity and true $O(1)$ space complexity.
Example Walkthrough
Input:
[10, 20, 30, 40, 50]Original array.
Step 1:
Swap index 0 (10) & 4 (50) -> [50, 20, 30, 40, 10]left=1, right=3.
Step 2:
Swap index 1 (20) & 3 (40) -> [50, 40, 30, 20, 10]left=2, right=2. Loop terminates.
Output:
[50, 40, 30, 20, 10]Array reversed in place.
Answer: Reverse in-place using two pointers
function reverse(arr) {
let left = 0, right = arr.length - 1;
while (left < right) {
let temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
return arr;
}💡 Swap symmetric elements from opposite ends using converging pointers.
Key Takeaways
- Two-pointer technique avoids extra memory overhead.
- Only $n/2$ iterations are needed to reverse an array of size $n$.
- In-place algorithm design modifies the input reference directly.