Data Structures · Visualization
Reverse Array
Array
Reversing an array flips the order of all its elements so the last becomes first and the first becomes last. Time: O(n). Space: O(1) extra space (in-place with two pointers).
Big-O: Random access O(1); insert/delete in the middle O(n).
Reverse Array
ArrayReversing an array flips the order of all its elements so the last becomes first and the first becomes last. The classic trick uses two pointers, one starting at each end, and swaps the pair of values they point to, then moves both pointers toward the middle.
How Reverse Array Works
- Place one pointer at the start (left) and one at the end (right) of the array.
- Swap the values at the left and right pointers.
- Move the left pointer one step forward and the right pointer one step backward.
- Repeat until the two pointers meet or cross.
Reverse Array Worked Example
Input: [1, 2, 3, 4, 5]
- left=0(1), right=4(5) → swap → [5, 2, 3, 4, 1]
- left=1(2), right=3(4) → swap → [5, 4, 3, 2, 1]
- left=2, right=2 → pointers meet, stop
Output: [5, 4, 3, 2, 1]
Press ▶ Run to watch it step by step.
def reverse(arr):
i, j = 0, len(arr) - 1
while i < j:
arr[i], arr[j] = arr[j], arr[i] # swap
i += 1
j -= 1
a = [1, 2, 3, 4, 5]
reverse(a) # [4, 3, 2, 1]
# example: reverse on [1, 2, 3, 4, 5]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Reverse Array Time & Space Complexity
When to Use Reverse Array
- Reversing text or a sequence of moves (undo history)
- Preparing data for algorithms that read it back-to-front
- A frequent building block in string and array interview problems
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.