Python – Reverse an Array
Reversing an array is a fundamental problem in data structures and algorithms (DSA). In this tutorial, we will explore different ways to reverse an array in Python and discuss the steps involved in solving this problem.
Problem Statement
Given an array arr
of size n
, reverse the elements of the array so that the first element becomes the last, the second element becomes the second last, and so on.
Sample Input and Output
Example 1:
Input: arr = [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]
Example 2:
Input: arr = [10, 20, 30, 40]
Output: [40, 30, 20, 10]
Solution Approach
We can solve this problem in multiple ways. Below are three common approaches:
- Using Python’s Built-in Reverse Function: The
reverse()
method reverses the list in-place. - Using Slicing: Python slicing can be used to create a reversed copy of the array.
- Using Two-Pointer Approach: Swap elements from start to end until the middle is reached.
Python Program
Method 1: Using the Built-in reverse()
Method
# Function to reverse an array using reverse() method
def reverse_array_builtin(arr):
arr.reverse()
return arr
# Sample Input
arr1 = [1, 2, 3, 4, 5]
print("Reversed Array:", reverse_array_builtin(arr1))
Output:
Reversed Array: [5, 4, 3, 2, 1]
This method modifies the array in place and is the simplest way to reverse a list in Python.
Method 2: Using Slicing
# Function to reverse an array using slicing
def reverse_array_slicing(arr):
return arr[::-1]
# Sample Input
arr2 = [10, 20, 30, 40]
print("Reversed Array:", reverse_array_slicing(arr2))
Output:
Reversed Array: [40, 30, 20, 10]
The slicing method creates a new reversed array instead of modifying the original.
Method 3: Using Two-Pointer Approach
The two-pointer technique swaps elements from the beginning and end, gradually moving towards the center.
# Function to reverse an array using the two-pointer approach
def reverse_array_two_pointer(arr):
left, right = 0, len(arr) - 1
while left < right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
return arr
# Sample Input
arr3 = [1, 2, 3, 4, 5]
print("Reversed Array:", reverse_array_two_pointer(arr3))
Output:
Reversed Array: [5, 4, 3, 2, 1]
This method works efficiently in-place with O(n) time complexity and O(1) space complexity.
Conclusion
We explored three different methods to reverse an array:
- Built-in
reverse()
method: Easiest, modifies the list in-place. - Slicing: Creates a new reversed list, concise but uses extra memory.
- Two-pointer approach: Best for in-place reversal with minimal memory usage.
For interviews, the two-pointer approach is preferred due to its efficiency in terms of space complexity.