METHOD (A Juggling Algorithm) Divide the array in different sets where number of sets is equal to GCD of n and d and move the elements within sets. If GCD is 1 as is for the abo
The for loop in the function:
leftRotate(int arr[], int d, int n)
is going to make exatcly gcd(d, n)
iterations. Now lets look at what is happening inside the loop: it takes all the cells arr[k]
which fulfill: k % gcd(d, n) == i
and swaps them. Of course there are exactly: n / gcd(d, n)
of them and that is how many swaps the function will make in one iteration of the loop. Therefore the whole asymptotic time complexity of the function is going to be O(gcd(d, n) * n / gcd(d, n)) == O(n)
. The rest of the code does not have an impact on the time complexity and is pretty much self explainatory.