![]() |
VOOZH | about |
Given an array arr[], the task is to rotate the array by d positions to the left using juggling algorithm.
Examples:
Input: arr[] = {1, 2, 3, 4, 5, 6}, d = 2
Output: {3, 4, 5, 6, 1, 2}
Explanation: After first left rotation, arr[] becomes {2, 3, 4, 5, 6, 1} and after the second rotation, arr[] becomes {3, 4, 5, 6, 1, 2}Input: arr[] = {1, 2, 3}, d = 4
Output: {2, 3, 1}
Explanation: The array is rotated as follows:
- After first left rotation, arr[] = {2, 3, 1}
- After second left rotation, arr[] = {3, 1, 2}
- After third left rotation, arr[] = {1, 2, 3}
- After fourth left rotation, arr[] = {2, 3, 1}
Approach:
The idea behind Juggling Algorithm is that we can rotate all elements of array using cycles. Each cycle is independent and represents a group of elements that will shift among themselves during the rotation. If the starting index of a cycle is i, then next elements of the cycle will be present at indices (i + d) % n, (i + 2d) % n, (i + 3d) % n ... and so on till we reach back to index i.
So for any index i, we know that after rotation we will have arr[(i + d) % n] at index i. Now, for every index in the cycle, we will place the element which should be present at that index after the array is rotated.
How many independent cycles will be there if an array of size n is rotated by d positions?
If an array of size n is rotated by d places, then the number of independent cycles will be gcd(n, d). When we rotate the array, the cycle increments in steps of d and terminates when we reach the starting point. This means that the distance travelled in each cycle will be a multiple of n, which is defined as lcm(n, d). So, number of elements in each cycle = lcm(n, d)/d. Therefore, to cover all n elements, the total number of cycles will be n*d/lcm(n, d) = gcd(n, d).
Below is the implementation of the algorithm:
3 4 5 6 1 2
Time Complexity: O(n), as all the cycles are independent and we are not visiting any element more than once.
Auxiliary Space: O(1)
Related Articles: