Array Reversal In-Place
What you'll learn: How to reverse an array's elements without using extra memory by swapping elements from opposite ends.
The Core Idea
Imagine you have a row of books on a shelf and want to reverse their order. Instead of getting a second shelf (extra memory), you can simply swap the first book with the last, the second with the second-to-last, and so on, working your way toward the middle. This is exactly how in-place array reversal works!
The Two-Pointer Technique
You use two "pointers" (really just index variables):
- One starts at the beginning of the array (index
0) - One starts at the end (index
length - 1)
At each step:
- Swap the elements at these two positions
- Move the left pointer one step right
- Move the right pointer one step left
- Stop when the pointers meet or cross
Why It Matters
This approach achieves O(1) space complexity—it uses only a constant amount of extra memory (just the two index variables and one temporary variable for swapping). You're modifying the original array directly rather than creating a new reversed copy.
For example, reversing [1, 2, 3, 4, 5]:
- Swap
1and5→[5, 2, 3, 4, 1] - Swap
2and4→[5, 4, 3, 2, 1] - Middle element
3stays (pointers met)
You iterate through roughly half the array, making this O(n) time complexity with minimal memory overhead.
Key Takeaway: In-place array reversal uses the two-pointer technique to swap elements from opposite ends, meeting in the middle, achieving O(1) space complexity without allocating additional memory.