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)
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)
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)
Output:
[5, 6, 2, 3, 4, 1]
United States
NORTH AMERICA
Related News
Jeff Bezos Seeking $100 Billion to Buy Manufacturing Companies, 'Transform' Them With AI
9h ago
Firefox Announces Built-In VPN and Other New Features - and Introduces Its New Mascot
9h ago
Can Private Space Companies Replace the ISS Before 2030?
9h ago
Juicier Steaks Soon? The UK Approves Testing of Gene-Edited Cow Feed
9h ago
White House Unveils National AI Policy Framework To Limit State Power
9h ago