Reverse an array of integers using the two-pointer technique. This approach swaps elements from both ends of the array, moving toward the center until the pointers meet.
arr = [1, 2, 3, 4, 5][5, 4, 3, 2, 1]def reverse_array(arr: list) -> list:
"""
Reverse an array using the two-pointer technique.
This approach swaps elements from both ends moving
toward the center, achieving O(n) time complexity.
Args:
arr: The input array to reverse
Returns:
A new reversed array
"""
# Create a copy to avoid modifying original
result = arr.copy()
# Initialize two pointers
left = 0
right = len(result) - 1
# Swap elements until pointers meet
while left < right:
# Swap elements at left and right positions
result[left], result[right] = result[right], result[left]
left += 1
right -= 1
return result
# Example usage
numbers = [1, 2, 3, 4, 5]
reversed_arr = reverse_array(numbers)
print(f"Original: {numbers}") # [1, 2, 3, 4, 5]
print(f"Reversed: {reversed_arr}") # [5, 4, 3, 2, 1]The two-pointer technique is optimal for in-place reversal. We start with pointers at both ends and swap elements while moving toward the center. Python's tuple unpacking makes swapping elegant. Time complexity: O(n/2) ≈ O(n). Space complexity: O(n) for the copy, or O(1) if modifying in-place.