Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

rotate array by 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]
 */
Comment

PREVIOUS NEXT
Code Example
Javascript :: express add delay 
Javascript :: CocoaPods could not find compatible versions for pod "React/Core": In Podfile: react-native-fetch-blob (from `../node_modules/react-native-fetch-blob`) was resolved to 0.10.6, which depends on React/Cor 
Javascript :: JavaScript string encryption and decryption 
Javascript :: jquery add to array with key 
Javascript :: node.js name of file 
Javascript :: ajax mdn 
Javascript :: nodejs spawn set env variable 
Javascript :: react 360 
Javascript :: useeffect 
Javascript :: react-native-infinite-scroll-with-flatlist 
Javascript :: reverse a string in javascript 
Javascript :: deep copy in angular 12 
Javascript :: javascript unselect radio 
Javascript :: function component in react 
Javascript :: javascript resize window 
Javascript :: moment.js 
Javascript :: javascript redirection 
Javascript :: window change detect 
Javascript :: javascript fetch get data from promise 
Javascript :: remove first and last element from array javascript and seprated by comma 
Javascript :: javascript combine objects 
Javascript :: innertext js 
Javascript :: mongodb mongoose match by ids 
Javascript :: adding function to objects js 
Javascript :: static variable in javascript 
Javascript :: usecallback react 
Javascript :: js binary search 
Javascript :: anagram js 
Javascript :: react - min & max for dates 
Javascript :: react functional components 
ADD CONTENT
Topic
Content
Source link
Name
1+2 =