DEV Community

Sharmila devi
Sharmila devi

Posted on

Reverse the array

Problem
Reverse an array arr[]. Reversing means the first element becomes last, the second becomes second-last, and so on.

Example 1:
Input: arr = [1, 4, 3, 2, 6, 5]
Output: [5, 6, 2, 3, 4, 1]

Example 2:
Input: arr = [4, 5, 1, 2]
Output: [2, 1, 5, 4]

Approaches
Using Two Pointers (O(n) time, O(1) space)
Swap elements from start and end until you reach the middle.

def reverse_array(arr):
left, right = 0, len(arr) - 1
while left < right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1

arr = [1, 4, 3, 2, 6, 5]
reverse_array(arr)
print(arr)


Enter fullscreen mode Exit fullscreen mode

Output:
[5, 6, 2, 3, 4, 1]

Swapping Elements by Index (O(n) time, O(1) space)
Iterate through the first half and swap with corresponding elements from the end.

def reverse_array(arr):
n = len(arr)
for i in range(n // 2):
arr[i], arr[n - i - 1] = arr[n - i - 1], arr[i]

arr = [1, 4, 3, 2, 6, 5]
reverse_array(arr)
print(arr)


Enter fullscreen mode Exit fullscreen mode

Output:
[5, 6, 2, 3, 4, 1]

Using Inbuilt Method (O(n) time, O(1) space) def reverse_array(arr):

arr.reverse()
arr = [1, 4, 3, 2, 6, 5]
reverse_array(arr)
print(arr)

Enter fullscreen mode Exit fullscreen mode

Output:
[5, 6, 2, 3, 4, 1]

Top comments (0)