CA 05 - Reverse the array
Problem Statement: arr[] = [1, 4, 3, 2, 6, 5] arr[] = [4, 5, 1, 2] Solution: Example: My approach: Using this we can solve the problem as follows: By using -1 in the step part, we get the array values in reverse. Output: [2, 1, 5, 4]
Jonah Blessy
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]
Found this useful? Share it!
Read the Full Story
Continue reading on Dev.to
Related Stories
Majority Element
about 2 hours ago
Building a SQL Tokenizer and Formatter From Scratch โ Supporting 6 Dialects
about 2 hours ago
Markdown Knowledge Graph for Humans and Agents
about 2 hours ago

Moving Beyond Disk: How Redis Supercharges Your App Performance
about 2 hours ago