Reverse an Array
The idea
Think of a line of people who need to face the other way without leaving their spots empty. The first and last person swap places, then the second and second-to-last, and so on — two walkers closing in from both ends until they meet in the middle.
The problem
You have a row of numbers and you want the whole row in the opposite order — the last element first, the first element last. The trick is to do it in place: no second array, just swaps. Put one pointer at each end, swap what they point at, and walk them toward each other.
Why it's slow
This is as fast as reversing can be: every element must move to a new position, so touching each one once is unavoidable. The two-pointer walk does exactly n/2 swaps and stops the moment the pointers meet — there is no wasted work to remove. What interviews probe is whether you reach for a second array (costing extra memory) when two pointers do it in place.
Pseudocode
-
set lo to the first index, hi to the last
Explain this line
Two pointers mark the working ends: lo starts at position 0, hi at the last position.
-
while lo is left of hi
Explain this line
Keep going while the pointers have not met or crossed — everything outside them is already reversed.
-
swap a[lo] and a[hi]
Explain this line
The swap puts both values in their final, mirrored positions in one move.
-
move lo right and hi left
Explain this line
Step both pointers inward: the reversed zone grows from both ends toward the middle.
-
done — the array is reversed
Explain this line
When the pointers meet, every element has been mirrored — an odd-length middle element stays put.
Complexity
| Best | Average | Worst | Space |
|---|---|---|---|
| O(n) | O(n) | O(n) | O(1) |
n/2 swaps, no extra array — the two-pointer walk is optimal because every element must move exactly once.
Code
python
def reverse_array(a):
lo, hi = 0, len(a) - 1
while lo < hi:
a[lo], a[hi] = a[hi], a[lo]
lo += 1
hi -= 1
return a
java
static void reverseArray(int[] a) {
int lo = 0, hi = a.length - 1;
while (lo < hi) {
int tmp = a[lo];
a[lo] = a[hi];
a[hi] = tmp;
lo++;
hi--;
}
}
cpp
void reverseArray(std::vector<int>& a) {
int lo = 0, hi = (int)a.size() - 1;
while (lo < hi) {
std::swap(a[lo], a[hi]);
++lo;
--hi;
}
}
javascript
function reverseArray(a) {
let lo = 0, hi = a.length - 1;
while (lo < hi) {
[a[lo], a[hi]] = [a[hi], a[lo]];
lo++;
hi--;
}
return a;
}
dart
void reverseArray(List<int> a) {
var lo = 0, hi = a.length - 1;
while (lo < hi) {
final tmp = a[lo];
a[lo] = a[hi];
a[hi] = tmp;
lo++;
hi--;
}
}