Visualize

Pattern visualizer

Reverse the Array

Reversing doesn't need a second array or repeated shifting — swap the first and last elements, then the second and second-to-last, and so on, moving two pointers toward each other from opposite ends. Once they meet (or cross), every pair has been swapped exactly once. Animated on: arr = [1,2,3,4,5] — reverse the array in place..

Two pointers swap inward from both ends

time O(n)space O(1)step 1 / 5
1
[0]
2
[1]
3
[2]
4
[3]
5
[4]
line 2

l=0, r=4: swap the outermost pair first, then move both pointers inward until they meet.

Pseudocode
1FUNCTION reverseArray(arr):
2 l = 0, r = (the length of arr) - 1
3 WHILE l < r:
4 swap arr[l] and arr[r]
5 move l one step right; move r one step left
6 RETURN arr

← / → step · space play · Home restart

Where to practice Arrays