DEV Community

Santhoshi Mary A
Santhoshi Mary A

Posted on

Reverse an array.

Problem Statement

Reverse an array.

Reversing an array means rearranging the elements such that:

The first element becomes the last
The second element becomes the second-last
The third element becomes the third-last
And so on
Example 1

Input:

arr[] = [1, 4, 3, 2, 6, 5]

Output:

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

Explanation:

1 moves to last position
4 moves to second-last
3 moves to third-last
2 moves to fourth-last
6 moves to second position
5 moves to first position
Example 2

Input:

arr[] = [4, 5, 1, 2]

Output:

[2, 1, 5, 4]

Explanation:

4 moves to last
5 moves to second-last
1 moves to second
2 moves to first
Logical Thinking Behind Reversing an Array

To reverse an array, we need to:

Swap the first element with the last element
Swap the second element with the second-last element
Continue this process until we reach the middle

This ensures the array is reversed completely.

Method 1 – Using Swapping (Two Pointer Approach)

This is the most logical and efficient way.

Python Code
arr = [1, 4, 3, 2, 6, 5]

start = 0
end = len(arr) - 1

while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1

print(arr)
Explanation
start points to the first element
end points to the last element
Swap both values
Move start forward
Move end backward
Stop when both meet

Time Complexity: O(n)
Space Complexity: O(1)

Top comments (0)