Reverse Array using Two Pointers

Reverse Array using Two Pointers

Visualization

Algorithm Steps

  1. Initialize two pointers: one at the beginning (left) and one at the end (right) of the array.
  2. While left is less than right, swap the elements at these pointers.
  3. Increment left and decrement right to move towards the center of the array.
  4. Continue until left is no longer less than right.
  5. The array is now reversed.

Reverse Array using Two Pointers Program Code

Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
def reverse_array(arr):
    left, right = 0, len(arr) - 1
    while left < right:
        arr[left], arr[right] = arr[right], arr[left]
        left += 1
        right -= 1
    return arr

if __name__ == '__main__':
    arr = [1, 2, 3, 4, 5]
    print("Reversed array:", reverse_array(arr))

Detailed Step by Step Example

Let us take the following array and apply the Two Pointers Technique to reverse the array in-place.

{ "array": [6,3,8,2,7,4], "showIndices": true, "specialIndices": [] }

Pass 1

left = 0, right = 5

Swap elements at left index and right index.

{ "array": [6,3,8,2,7,4], "showIndices": true, "highlightIndices": [0, 5], "highlightIndicesGreen": [], "specialIndices": [], "labels": { "0": "left", "5": "right" } }

After swapping:

{ "array": [4,3,8,2,7,6], "showIndices": true, "highlightIndicesGreen": [0,5], "labels": { "0": "left", "5": "right" } }
Increment left pointer by one, and decrement right pointer by one.

Pass 2

left = 1, right = 4

Swap elements at left index and right index.

{ "array": [4,3,8,2,7,6], "showIndices": true, "highlightIndices": [1, 4], "highlightIndicesGreen": [0,5], "specialIndices": [], "labels": { "1": "left", "4": "right" } }

After swapping:

{ "array": [4,7,8,2,3,6], "showIndices": true, "highlightIndicesGreen": [0,1,4,5], "labels": { "1": "left", "4": "right" } }
Increment left pointer by one, and decrement right pointer by one.

Pass 3

left = 2, right = 3

Swap elements at left index and right index.

{ "array": [4,7,8,2,3,6], "showIndices": true, "highlightIndices": [2, 3], "highlightIndicesGreen": [0,1,4,5], "specialIndices": [], "labels": { "2": "left", "3": "right" } }

After swapping:

{ "array": [4,7,2,8,3,6], "showIndices": true, "highlightIndicesGreen": [0,1,2,3,4,5], "labels": { "2": "left", "3": "right" } }
Increment left pointer by one, and decrement right pointer by one.

left = 3, right = 2

left pointer crosses right pointer, end of loop.

Array is fully reversed.

{ "array": [4,7,2,8,3,6], "showIndices": true, "highlightIndicesGreen": [0,1,2,3,4,5], "specialIndices": [] }