Array Reversal

Visualization

1
2
3
4
5
[0]
[1]
[2]
[3]
[4]
Step: 0/2
Click 'Run' to start
Two-Pointer Algorithm
1. left = 0, right = n-1
2. While left < right:
3. Swap arr[left] ↔ arr[right]
4. left++, right--
5. Return reversed array
2

Array Reversal

EasyArrays

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.

Input:arr = [1, 2, 3, 4, 5]
Output:[5, 4, 3, 2, 1]
Solutions
solution.py
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]

Explanation

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.