DEV Community

Jonah Blessy
Jonah Blessy

Posted on

CA 05 - 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:
A brute force method to reverse the given array would be to 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)

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])

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

Output:
[2, 1, 5, 4]

Top comments (0)