Program for rotate given array of integers for number of times in java
February 27, 2021
Problem Statement:- Write program to rotate a given array for given number of rotation times.
Solution: To solve this problem we will create a temp array with the size of old array + rotation number and then we will insert element in new element .In this new array we will insert element with index less than rotation number in the end of new array .After that copy that new temp array in old array again to remove elements
Steps:-
- get new temp array size = old array size + rotation number
- initialize temp array with new size .
- insert element with index less than rotation number in the end of new temp array and rest of element in the start of new temp array .
- now copy this new temp array to old array to reduce the element places that we have shifted.
private static int[] rotateArray(int[] arr,int k){
if(arr.length>0) {
int[] newArr = new int[arr.length +k]; // create new array with size of array + no of rotation
for (int i = 0; i <arr.length ; i++) {
if(i<k) // while index is less than rotation insert starting array to end of new array
newArr[arr.length+i] = arr[i];
else
newArr[i] = arr[i];
}
for (int i = 0; i < arr.length; i++) {
arr[i]=newArr[i+k]; // copy again to reduce space before rotation index
}
}
return arr;
}
Time Complexity : O(n) + O(n) = 2O(n) = O(n)
__________________________________________________________
output:-
You can found the full program on below link - array rotation
Thanks .