Arrays: Left Rotation

  • + 1 comment

    The part I'm missing here is why use a loop (O(n)). Can't you take the array and find the effective rotation based on the shift amount (using the same modular arithemetic you're doing? (Which is now O(1) since the length of the array is a property)

    function rotLeft(a, d) {
    
      //calculate effective rotation (d % a.length)
      let effectiveRotation = d % a.length;
    
      // split a at index of effective rotation into left and right
      let leftPortion = a.slice(0, effectiveRotation);
      let rightPortion = a.slice(effectiveRotation); 
    	
      // concat left to right
      return rightPortion.concat(leftPortion)
    }
    
    • + 0 comments

      Can you explain how this is O(1) ? Please read about how slice and concatenation implemented in the language you are using. Also it uses extra memory.