Reverse an Array

Easy
0/40
Average time to solve is 10m
profile
Contributed by
139 upvotes
Asked in companies
SamsungHealspan

Problem statement

Given an array 'arr' of size 'n'.


Return an array with all the elements placed in reverse order.


Note:
You don’t need to print anything. Just implement the given function.
Example:
Input: n = 6, arr = [5, 7, 8, 1, 6, 3]

Output: [3, 6, 1, 8, 7, 5]

Explanation: After reversing the array, it looks like this [3, 6, 1, 8, 7, 5].
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line contains an integer n, the size of the array
The second line contains n integers, the array.
Output format:
Return the reversed array.
Sample Input 1:
8
3 1 1 7 4 2 6 11
Sample Output 1:
11 6 2 4 7 1 1 3    
Explanation Of Sample Input 1 :
After reversing the array, it looks like this [11, 6, 2, 4, 7, 1, 1, 3].
Sample Input 2:
4
8 1 3 2
Sample Output 2:
2 3 1 8
Explanation Of Sample Input 2 :
After reversing the array, it looks like this [2, 3, 1, 8].
Expected time complexity
The expected time complexity is O(n).
Constraints:
1 <= 'n' <= 10^6
-10^9 <= 'arr[i]' <=10^9
Hint

Use an extra array.

Approaches (4)
Using an extra array

Approach:

  • Create a new array, say,  ‘arr1’.
  • Iterate from index ‘0’ to ‘n-1’ and arr1[i]  = arr[n-1-i]

Algorithm:

  • Create a new array arr1 of size n
  • For ‘i’ from 0 to n-1
    • arr1[i] =arr[n-1-i];
  • Return arr1;


 

Time Complexity

O(n), Where n is the size of the array

 

We are iterating through the array once. 

 

Hence the time complexity would be O(n).

Space Complexity

O(n) where n is the size of the array

 

Since we are creating a new array of size n. 

 

Hence the space complexity would be O(n).

Code Solution
(100% EXP penalty)
Reverse an Array
Full screen
Console