Arrays: Left Rotation

  • + 0 comments

    Is this cheating?

    function rotLeft(a, d) {

     d = d % a.length;
    
     if(d){
           for(let i=0; i<d; i++) a.push(a.shift());
     }
    
     return a;
    

    }

    d => so that I avoid unnecessary shifts
    

    Eg: 5 elements when rotated 12 times it's the same as rotating 2 times

    Hence instead of rotating 12 times we only rotate 2 times

    And if it has to be rotated 10 times it's the same as not rotating at all so return the original array