Learn-dsa..in 30 days!



























CC-11 : Rotate Array by n places.

Description:

Given an input integer array arr, the arr needs to be rotated rightwards by n places. Note that n is a positive number and can be greater than the size of input array also.

Test cases and expected outputs:

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

Pseudocode:

The java method should accept following input parameters: arr (int array), rotCnt (count of position rotation to be done).
rotCnt can be greater than arr.length, so we need to handle this special case.
When rotCnt=arr.length, the array elements return to its original position, so no rotation needs to be done. When (rotCnt > arr.length) we can calculate actual moves to be done by this formula: moveCnt= rotCnt % arr.length. We need to move arr elements only moveCnt places in this case.
To rotate arr by moveCnt places first we need to move the last moveCnt element of arr to a temporary array tempArray. This can be done by a for loop.
After above step, in array arr, move value at each index forward by moveCnt places. This can be done using a for loop.
Next, move moveCnt elements from tempArray to start of arr.
Now rotation by moveCnt places is complete and we can return the rotated array.

Code:

public int[] arrayRotateByNPlaces(int[] arr, int rotCnt) throws Exception{
	int moveCnt= rotCnt % arr.length;
	int[] tempArray=new int[moveCnt];
	int tempArrayIndex=moveCnt-1;
	for (int idx=arr.length-1; idx>arr.length-1-moveCnt; idx--) {
		tempArray[tempArrayIndex]=arr[idx];
		tempArrayIndex--;				
	}
	for (int idx=arr.length-1; idx>moveCnt-1; idx--) {
		arr[idx]=arr[idx-moveCnt];
	}
	for (int idx=0; idx<=tempArray.length-1; idx++) {
		arr[idx]=tempArray[idx];
	}
	return arr;
}

Click here to download and run code and test cases !