DEV Community

Sri Mahalakshmi
Sri Mahalakshmi

Posted on

Reversing an Array Using the Two Pointer Technique in Python

Problem Explanation

Reversing an array means rearranging its elements so that the first element becomes the last, the second becomes the second-last, and so on.

Example:

  • Input: arr = [1, 4, 3, 2, 6, 5]
    Output: [5, 6, 2, 3, 4, 1]

  • Input: arr = [4, 5, 1, 2]
    Output: [2, 1, 5, 4]


Method Used: Two Pointer Technique

This method uses two pointers:

  • One starting from the beginning (left)
  • One starting from the end (right)

We swap elements at these positions and move the pointers toward each other until they meet.


Why This Method?

  • Efficient with time complexity O(n)
  • Uses no extra space (O(1) space complexity)
  • Simple and clean logic

Compared to creating a new reversed array, this approach is more optimal.


Python Code

def reverse_array(arr):
    left = 0                      
    right = len(arr) - 1          

    while left < right:           
        arr[left], arr[right] = arr[right], arr[left]  
        left += 1                 
        right -= 1                

    return arr

arr = [1, 4, 3, 2, 6, 5]
print(reverse_array(arr))
Enter fullscreen mode Exit fullscreen mode

Code Explanation (Line by Line)

  • def reverse_array(arr):
    Defines a function to reverse the given array.

  • left = 0
    Initializes the left pointer at index 0.

  • right = len(arr) - 1
    Initializes the right pointer at the last index.

  • while left < right:
    Loop runs until both pointers meet.

  • arr[left], arr[right] = arr[right], arr[left]
    Swaps elements at the left and right indices.

  • left += 1
    Moves the left pointer one step forward.

  • right -= 1
    Moves the right pointer one step backward.

  • return arr
    Returns the reversed array.


Output

Input:

[1, 4, 3, 2, 6, 5]
Enter fullscreen mode Exit fullscreen mode

Output:

[5, 6, 2, 3, 4, 1]
Enter fullscreen mode Exit fullscreen mode

Key Takeaway

The Two Pointer Technique allows reversing an array efficiently in a single pass without using extra memory.


Top comments (0)