Array ( [0] => [1] => questions [2] => Popular-Algorithms [3] => Reverse-Array ) Arrays | Reverse Array | THE INQUISITIVE





Reverse Array

LEVEL:Beginner

Description

Given an array of integers, you need to print the elements in the reverse order.

Input Format

First line contains the size of the array. Next line contains the n integers separated by the spaces.

Output Format

Array elements in the reverse order.


Example 1:

Input
5
1 1 1 1 1
Output
1 1 1 1 1
Example 2:

Input
3
1 2 2
Output
2 2 1
Example 3:

Input
6
2 5 5 4 1 3
Output
3 1 4 5 5 2

oops

Login to see Discussion




Approach

Approach1: Using other array

Step-i) Initialize a new array of same size.
Step-ii) Iterate the array from the last.
Step-iii) Assign the i th element of the old array to n-i-1 th element of new array.
Step-iv) Return the new array.

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

Approach2: Swapping elements

Step-i) Iterate array from 0 to length/2.
Step-ii) In the first iteration, swap the first and last elements.
Step-iii) In the next iteration, swap the second and last but one element.
Step-iv) Similarly swap i th and n-i-1 th elements.
Step-v) Return the array.

Time Complexity: O(n) (actually n/2 iterations)
Space Complexity: O(n)


Note :

Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.

oops

Login to see Solution