DEV Community

Jonah Blessy
Jonah Blessy

Posted on • Edited on

Reverse the array

Problem Statement:
Reverse an array . Reversing an array means the elements such that the element becomes the , the element becomes and so on.

arr[] = [1, 4, 3, 2, 6, 5]
[5, 6, 2, 3, 4, 1]
The first element moves to last position, the second element moves to second-last and so on.

arr[] = [4, 5, 1, 2]
[2, 1, 5, 4]
The first element moves to last position, the second element moves to second last and so on.

Solution:
I came up with 2 methods. One is what I learnt to do while i started coding which is the brute force method. We create a new empty array and append each value from the original array one by one in reverse order using for loop.

Example:

arr= [4, 5, 1, 2]
n=len(arr)
rev_arr=[]
for i in range (n-1,-1,-1):
    rev_arr.append(arr[i])
print(rev_arr)
Enter fullscreen mode Exit fullscreen mode

My approach:
My preferred method of solving this problem would be to use the slicing concept. Slicing has the following syntax: array[start: end: step].

Using this we can solve the problem as follows:

arr= [4, 5, 1, 2]
print(arr[::-1])
Enter fullscreen mode Exit fullscreen mode

By using -1 in the step part, we get the array values in reverse.

Output:
[2, 1, 5, 4]

Top comments (0)