Learn-dsa..in 30 days!



























CC-2 : Reverse elements of array in place, without using a new array.

Description:

Given an input integer array arr, we want to reverse the order of the elements. The first element should become last element. The second element should become second last element and so on.

Test cases and expected outputs:

Input Parameters Expected outputs
arr={1,2,3,4,5,6,7,8} 8,7,6,5,4,3,2,1
arr={-3,-2,-1,0,1,2,3 } 3,2,1,0,-1,-2,-3
arr={4,5} 5,4
arr={4,4 } 4,4
arr={1} 1

Asked by: , , Leetcode #344

Summary Algorithm:

This algorithm performs an in-place reversal of an array by iterating to its midpoint and using a temporary variable to swap symmetric elements from the beginning and end.

Pseudocode:

The java method should accept following input parameters: arr (int array).
Initialize integer variable endIdx to (arr.length-1) (this is the last index of the array).
Iterate through arr using a for loop, using variable startIdx as loop counter. Start value of startIdx is 0 and end value of startIdx should be less than (arr.length/2). As we want to reverse the array, when we reach (arr.length/2), the reversal process is complete.
Interchange the array elements at index startIdx and index endIdx using a temporary variable temp;
Decrement endIdx by 1.
At the end of the for loop execution, return the reversed array.

Code:

public int[] arrayReversal(int[] arr) throws Exception{
	int endIdx=arr.length-1;
	int temp=0;
	for (int startIdx=0; startIdx < arr.length/2; startIdx++) {
		temp=arr[startIdx];
		arr[startIdx]=arr[endIdx];
		arr[endIdx]=temp;
		endIdx--;
	}
	return arr;			
}
Time Complexity Space Complexiy
O(n) O(1)

Click here for execution trace to understand the code better.

Click here to download and run code and test cases !