1. Problem statement
Given an array A of integers, reverse this array A in linear running time using constant memory.
2. Solution
The steps to reverse an array can be shown with the help of following figure:

3. Program
Following is the program to reverse the array.
import java.util.Arrays; public class ReverseArray { public int[] reverse(int[] nums) { // initialize low and high index int lowIndex = 0; int highIndex = nums.length - 1; // while lowIndex is less than high index while (lowIndex < highIndex) { // swap low index and high index swap(nums, lowIndex, highIndex); //increment low index and decrement high index lowIndex++; highIndex--; } return nums; } private void swap(int[] nums, int index1, int index2) { int temp = nums[index1]; nums[index1] = nums[index2]; nums[index2] = temp; } public static void main(String[] args){ int[] nums = {1,2,3,4,5}; ReverseArray reverseArray = new ReverseArray(); int[] reversedArray = reverseArray.reverse(nums); System.out.println(Arrays.toString(reversedArray)); } }
Output:
[5, 4, 3, 2, 1]
Approach 2
import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; public class ReverseArray { public static void main(String[] args) { Integer[] numbers = {1, 2, 3, 4, 5}; // Example array List<Integer> reversedList = Arrays.stream(numbers) // Convert to stream .collect(Collectors.toList()); // Convert to list Collections.reverse(reversedList); // Reverse the list Integer[] reversedArray = reversedList.toArray(new Integer[0]); // Convert back to array System.out.println("Reversed Array: " + Arrays.toString(reversedArray)); } }