Array ( [0] => [1] => questions [2] => Strings [3] => Reverse-Array )
Given an array of integers, you need to print the elements in the reverse order.
First line contains the size of the array. Next line contains the n integers separated by the spaces.
Array elements in the reverse order.
5 1 1 1 1 1
1 1 1 1 1
3 1 2 2
2 2 1
6 2 5 5 4 1 3
3 1 4 5 5 2
Login to see Discussion
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.
Login to see Solution