Fetching latest headlines…
Reverse an Array
NORTH AMERICA
πŸ‡ΊπŸ‡Έ United Statesβ€’March 22, 2026

Reverse an Array

0 views0 likes0 comments
Originally published byDev.to

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

  1. 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]

  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]

  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]

Comments (0)

Sign in to join the discussion

Be the first to comment!