We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
To solve this, I've shifted the elements in the array in O(n) time and O(n) memory (vs O(2n)). Not as easy on the eyes, though :(
functionprocessData(input){// get `n` and `d` from inputconstlines=input.split('\n');constfirstLine=lines[0].split(' ').map(Number);constn=firstLine[0];constd=firstLine[1];// process each linelines.slice(1,lines.length).forEach(line=>{// no need to shift in these casesif(n===1||d===n){console.info(line);}else{// shift digitsconsta=line.split(' ').map(Number);letlastLastItem=null;letcount=0;leti=0;while(count<n){i++;conststart=i;letj=start;do{count++;letlastItem=lastLastItem;lastLastItem=a[j];a[j]=lastItem;j=shiftLeft(n,d,j);}while(j!==start);a[start]=lastLastItem;}console.info(a.reduce((acc,value)=>{returnacc+' '+value;}));}});}/** * @param {Number} n total number of elements * @param {Number} d number of shifts to left * @param {Number} i index to begin shifting from * @returns {Number} new index after shifting to left */functionshiftLeft(n,d,i){return(n-d+i)%n;}
I'm ignoring the processing time on input string manipulation and such. This examples assumes they gave us an existing array to manipulate.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Left Rotation
You are viewing a single comment's thread. Return to all comments →
To solve this, I've shifted the elements in the array in O(n) time and O(n) memory (vs O(2n)). Not as easy on the eyes, though :(
I'm ignoring the processing time on input string manipulation and such. This examples assumes they gave us an existing array to manipulate.