Last Updated: 9 Jun, 2023

Reverse an Array

Easy
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].
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.

Approaches

01 Approach

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;


 

02 Approach

Approach:

  • Initialize two pointers, start pointing to the first element of the array, and end pointing to the last element of the array.
  • Swap the elements at the start and end indices, increment the start pointer, and decrement the end pointer.
  • Repeat the swap until the start pointer crosses the end pointer.
  • The array will be reversed in-place.

Algorithm:

  • int i = 0 , j = n-1;
  • while(i<=j)
    • swap(arr[i] , arr[j]);
    • i++;
    • j–;
  • Return arr;

03 Approach

Approach:

  • Implement a recursive function to reverse the array.
  • Base case: If the start index is greater than or equal to the end index, return.
  • Swap the elements at the start and end indices.
  • Recursively call the reverse function with start+1 and end-1.
  • The array will be reversed in-place.

Algorithm:

  • Void reverse(int arr[], int i, int j)
    • if(i > j) return;
    • swap(arr[i], arr[j]);
    • return reverse(arr , i+1 , j-1);

04 Approach

Approach:

In C++:

  • Include the algorithm header file to access the std::reverse function.
  • Use the std::reverse function with the range specified by the bidirectional iterators 'first' and 'last' to reverse the elements in the array.
  • Syntax: std::reverse(array_name.begin(), array_name.end())
  • Note: The range includes the first element but excludes the last element.

 

In Java:

  • Import the reverse method from the Collections class in java.util package.
  • Convert the array into a list object using the asList method, as Java collections require wrapper classes instead of primitive data types.
  • Use the Collections.reverse method to reverse the list object.
  • Syntax: Collections.reverse(Arrays.asList(array_name))
  • Note: If the array contains integer values, use the Integer wrapper class instead of the int data type.