Imagine you have a row of letters lined up in boxes, like this:
[a, e, i, o, u]
Your goal is to flip the whole row around so the last letter comes first and the first letter comes last:
[u, o, i, e, a]
This is called reversing the array. Let's learn a clean, efficient way to do it.
Think of two people walking toward each other from the two ends of the row. One starts at the front, the other at the back. Each time they meet a pair, they trade places (swap), then they each take one step toward the middle.
These pairs (front and back, then one step in, and so on) are what the problem calls equidistant elements — they are the same distance away from the center.
Let's walk through [a, e, i, o, u]:
0 (a) with position 4 (u) → [u, e, i, o, a]1 (e) with position 3 (o) → [u, o, i, e, a]i stays where it is. Done!Result: [u, o, i, e, a] ✅
The problem asks you to reverse the array in-place. This means: don't create a second array to hold the answer. Just rearrange the letters inside the same array you were given.
When we say O(1) space complexity, it means the extra memory you use does not grow with the size of the array. Even if the array had a million letters, you only need a tiny bit of extra room — enough to hold one letter for a moment while you swap two of them. That's it.
To swap two boxes, you need a temporary spot to hold one value, or the language can do it for you. The classic way:
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
Here temp is the "holding hand" so you don't lose a letter while moving the other one in.
Use two markers, left starting at the very front and right starting at the very back. While left is still before right, swap their letters, then move left one step forward and right one step backward.
void flipCharacters(vector<char> &arr) {
int left = 0;
int right = arr.size() - 1;
while (left < right) {
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
n letters, you do about n/2 swaps, so the work grows in step with the array size — this is O(n) time.temp), no matter how big the array is — this is O(1) space, exactly what the problem wants.This two-pointer "swap from both ends" pattern is a tool you'll reuse again and again in array problems, so it's worth understanding well.