1.

Write a program in Java to Reverse an Array without using extra space.

Answer»

We keep to variables i and j at both the ends of the array as shown below.

 

Now, swap the element at index i with the element at index j increment the i variable, and decrement the j variable. Keep doing this till i is less than j. This is shown in the image below.

import java.util.*;
class Main {
public static void main(String args[]) {
// Your code goes here
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int[] arr = new int[n];

for(int i=0;i<n;i++) {
arr[i] = scn.nextInt();
}

System.out.println("The reversed array is");
int i = 0;
int j = arr.length - 1;

while(i < j) {
//swapping ith and jth index elements
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}

//displaying the array
for(int it=0;it<arr.length;it++) {
System.out.print(arr[it] + " ");
}
}
}

Sample Output

Input:
5
1 2 3 4 5

Output:
The reversed array is
5 4 3 2 1


  • Time complexity: O(N) as we are traversing the array.


  • Auxiliary Space: O(1) as we have not used any extra space.




Discussion

No Comment Found