Problem
Given an array arr[], the task is to reverse the array.
Reversing means:
The first element becomes the last
The second element becomes the second-last
And so on...
Output
Example 1
Output: [5, 6, 2, 3, 4, 1]
Example 2
Output: [2, 1, 5, 4]
My Approach
To solve this problem, I used the two-pointer technique.
I start with two pointers:
One at the beginning (left)
One at the end (right)
Then I swap the elements at these positions
After swapping:
Move left forward
Move right backward
Continue this until both pointers meet
This works because we are swapping elements from opposite ends step by step.
This approach is efficient because:
It only requires one traversal
It uses constant extra space (in-place)
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
Top comments (0)