Arrays: Left Rotation

  • + 1 comment

    Great solution. Any tips on how to know if you need to use modulus in your algorithm? I solved this problem using 2 for loops...

    • + 4 comments

      I figured it out by saying, I don't need to loop through this array over and over to know what the final state of the array should be. What I need to figure out is what the first element of the new array will be after I've rotated X amount of times. So if I divide the number of rotations (X) by the length of the array (lenArr) I should get the amount of times the array has been fully rotated. I don't need that, I need what the first element will be after this division operation. For that I need the remainder of that divison (the modulus). This is because after all of the full array loops are done, the remaining rotations determine what the first element in the new array will be.

      So you take that remainder (modulus) and that's the first element's index in the old array. For example, 24 rotations in a 5 element long array means that the first element in the new array is in the 4th index of the old array. (24 % 5 = 4)

      So rotate through [3, 4, 5, 6, 7] 24 times and the first element will be 7. So just take that and put it before the other elements. ([7. 3, 4, 5, 6])


      Another good tip is always look for repeating patterns. It's a sign that you can simplify your code. The for loop method is just repeating the state of the array over and over: [3, 4, 5, 6, 7] [4, 5, 6, 7, 3,] [5, 6, 7, 3, 4,] [6, 7, 3, 4, 5,] [7, 3, 4, 5, 6,] [3, 4, 5, 6, 7] [4, 5, 6, 7, 3,] [5, 6, 7, 3, 4,]...

      You only really need to know what's happening in the final few rotations, after the last full loop.

      • + 0 comments

        great explanation!

      • + 0 comments

        thank you. this is my aha moment. :)

      • + 0 comments

        Superb explanation, now I jnow why Data Structures are imp.

        Your approach shows how things should be done. I ll be soon implementing this on Python and post the same, dats gonna help many developers

      • + 0 comments

        Great analysis !