Array & Data-Structure Operations
Reverse an Array
Reverses an array in place with two pointers: swap the outermost pair, move both pointers inward, and stop when they meet.
1Detailed explanation
Two pointers start at both ends of the array. Swap the elements they point to, move left one step right and right one step left, and repeat until the pointers meet or cross.
Each swap fixes two positions, so ⌊n/2⌋ swaps reverse the whole array in place with O(1) extra memory.
The same two-pointer pattern solves palindrome checks, reversing a string, and many 'pair from both ends' problems.
2Pseudocode
procedure reverse(A)
left ← 0
right ← length(A) − 1
while left < right
swap A[left] and A[right]
left ← left + 1
right ← right − 1
return A3Interactive visualization
Reverses an array in place with two pointers: swap the outermost pair, move both pointers inward, and stop when they meet.
4Implementations
Equivalent implementations in four languages — the same code the visualizer highlights line by line. Each is a complete program.
5Time and space complexity
Time: Each swap fixes two positions, so exactly ⌊n/2⌋ swaps are made → O(n).
Space: Only the two indexes left and right are stored → O(1) auxiliary space (in place).
6Common interview variations
- Reverse only a sub-range [l, r].
- Rotate an array by k positions using three reversals.
- Check whether a string is a palindrome.
- Reverse words in a sentence.