Given an integer array of size n, our task is to write a Python code to print the elements of the array in reverse order.
Example:
Input: arr = [1, 2, 3, 4, 5] Output: Reverse order = 5, 4, 3, 2, 1 Input: arr = [10, 5, -1, 4] Output: Reverse Order = 4, -1, 5, 10
Reverse the Given Array in Python.
We can reverse any given array by iterating through the array, swapping the first and last elements, then the second and second-to-last, and so on. We continue the swap process until we reach the middle of the array. We will need two variables initially pointing to the first and last element of the array for swapping.
Python Code to Reverse Array Elements.
# Python code to Reverse given array def reverse_array(arr): start, end = 0, len(arr) - 1 # Print original array print("Original Array:", arr) while start < end: # Swap elements at start and end indices arr[start], arr[end] = arr[end], arr[start] start += 1 end -= 1 # Print reversed array print("Reversed Array:", arr) return arr # Example Usage original_array = [1, 2, 3, 4, 5] reversed_array = reverse_array(original_array.copy())
Original Array: [1, 2, 3, 4, 5]
Reversed Array: [5, 4, 3, 2, 1]
- Time Complexity: O(n)
- Space Complexity: O(1)
Reverse an Array Using Python Slicing Method.
We can also use the Python Slicing technique to reverse an array. In this method, the slice notation [::-1] is used to reverse the array. It starts from the end and moves towards the beginning with a step of -1.
Python Code:
# Python code to reverse an array using slicing def reverse_array(arr): reversed_arr = arr[::-1] return reversed_arr # Example usage original_array = [1, 2, 9, 3, 5] reversed_array = reverse_array(original_array) # Print the result print("Original Array:", original_array) print("Reversed Array:", reversed_array)
Output:
Original Array: [1, 2, 9, 3, 5]
Reversed Array: [5, 3, 9, 2, 1]
- Time Complexity: O(n) where n is the length of the array
- Space Complexity: O(n) because slicing creates a new array.
So these are two methods to reverse any given array in Python and my favorite is the slicing method because is just one line of code and easy to remember but it is not good in terms of space complexity.
No comments:
Post a Comment