Putar array oleh D Elements JavaScript
// Program for arr rotation by d elements.
// Approch-1 (using temp arr)
function arrayRotate1(arr, d){
let temp =[];
let j=0;
for(let i=0; i<d; i++){
temp.push(arr[i]);
}
for(let i=0;i<arr.length-d;i++){
arr[i]=arr[i+d];
}
for(let i=arr.length-d;i<arr.length;i++){
arr[i]=temp[j++];
}
return arr;
}
/**
* Time Complexity -> O(n)
* Space Complexity -> O(d)
*/
// Approch-2 (Rotate by one by one)
function leftRotateByOne(arr){
let temp = arr[0];
for(let i=0;i<arr.length;i++){
arr[i] = arr[i+1];
}
arr[arr.length-1] = temp;
}
function arrayRotate2(arr, d){
for(let i=0;i<d;i++){
leftRotateByOne(arr);
}
return arr;
}
/**
* Time Complexity ->O(n*d)
* Space Complexity -> O(1)
*/
const arr = [1,2,3,4,5,6,7];
const d=2;
console.log(arrayRotate2(arr,d));
/**
* output->
* [ 3, 4, 5, 6,7, 1, 2]
*/
Aayush