DSA Tracker

Visualize

Reverse Array

Two pointers swap inward from both ends

time O(n)space O(1)

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.

Details

Animated on: arr = [1,2,3,4,5] — reverse the array in place.

Problem:Reverse ArrayEasy

Two pointers swap inward from both ends

step 1 / 5

1
[0]
2
[1]
3
[2]
4
[3]
5
[4]

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

  • l=0· arr[0] = 1
  • r=4· arr[4] = 5
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

Every step in words

Show all 5 steps
  1. l=0, r=4: swap the outermost pair first, then move both pointers inward until they meet.
  2. Swap arr[0] and arr[4] -> [5, 2, 3, 4, 1].
  3. Move inward: l=1, r=3.
  4. Swap arr[1] and arr[3] -> [5, 4, 3, 2, 1].
  5. l meets r at the middle (idx 2) — that element never needed to move. Final array: [5, 4, 3, 2, 1].

Now solve it yourself

Watching is the first half. The second is writing it without the animation.