Juggling Algorithm for Array Rotation
Last Updated :
09 Nov, 2024
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/lcm(n, d) = gcd(n, d).
Below is the implementation of the algorithm:
C++
// C++ Program to left rotate the array by d positions
// using Juggling Algorithm
#include <bits/stdc++.h>
using namespace std;
// Function to rotate vector
void rotateArr(vector<int> &arr, int d) {
int n = arr.size();
// Handle the case where d > size of array
d %= n;
// Calculate the number of cycles in the rotation
int cycles = __gcd(n, d);
// Process each cycle
for (int i = 0; i < cycles; i++) {
// Start element of current cycle
int startEle = arr[i];
// Start index of current cycle
int currIdx = i, nextIdx;
// Rotate elements till we reach the start of cycle
while(true) {
nextIdx = (currIdx + d) % n;
if(nextIdx == i)
break;
// Update the next index with the current element
arr[currIdx] = arr[nextIdx];
currIdx = nextIdx;
}
// Copy the start element of current cycle at the last
// index of the cycle
arr[currIdx] = startEle;
}
}
int main()
{
vector<int> arr = {1, 2, 3, 4, 5, 6};
int d = 2;
rotateArr(arr, d);
// Print the rotated array
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
return 0;
}
C
// C Program to left rotate the array by d positions
// using Juggling Algorithm
#include <stdio.h>
#include <stdlib.h>
// Function to compute GCD
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
// Function to rotate array
void rotateArr(int arr[], int n, int d) {
// Handle the case where d > size of array
d %= n;
// Calculate the number of cycles in the rotation
int cycles = gcd(n, d);
// Process each cycle
for (int i = 0; i < cycles; i++) {
// Start element of current cycle
int startEle = arr[i];
// Start index of current cycle
int currIdx = i, nextIdx;
// Rotate elements till we reach the start of cycle
while (1) {
nextIdx = (currIdx + d) % n;
if (nextIdx == i)
break;
// Update the next index with the current element
arr[currIdx] = arr[nextIdx];
currIdx = nextIdx;
}
// Copy the start element of current cycle at the last index of the cycle
arr[currIdx] = startEle;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
int d = 2;
rotateArr(arr, n, d);
// Print the rotated array
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Java
// Java Program to left rotate the array by d positions
// using Juggling Algorithm
import java.util.Arrays;
class GfG {
// Function to rotate array
static void rotateArr(int[] arr, int d) {
int n = arr.length;
// Handle the case where d > size of array
d %= n;
// Calculate the number of cycles in the rotation
int cycles = gcd(n, d);
// Process each cycle
for (int i = 0; i < cycles; i++) {
// Start element of current cycle
int startEle = arr[i];
// Start index of current cycle
int currIdx = i, nextIdx;
// Rotate elements till we reach the start of cycle
while (true) {
nextIdx = (currIdx + d) % n;
if (nextIdx == i)
break;
// Update the next index with the current element
arr[currIdx] = arr[nextIdx];
currIdx = nextIdx;
}
// Copy the start element of current cycle at the last
// index of the cycle
arr[currIdx] = startEle;
}
}
// function to compute GCD
static int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6};
int d = 2;
rotateArr(arr, d);
// Print the rotated array
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");
}
}
Python
# Python Program to left rotate the array by d positions
# using Juggling Algorithm
import math
# Function to rotate array
def rotateArr(arr, d):
n = len(arr)
# Handle the case where d > size of array
d %= n
# Calculate the number of cycles in the rotation
cycles = math.gcd(n, d)
# Process each cycle
for i in range(cycles):
# Start element of current cycle
startEle = arr[i]
# Start index of current cycle
currIdx = i
# Rotate elements till we reach the start of cycle
while True:
nextIdx = (currIdx + d) % n
if nextIdx == i:
break
# Update the next index with the current element
arr[currIdx] = arr[nextIdx]
currIdx = nextIdx
# Copy the start element of current cycle at the last
# index of the cycle
arr[currIdx] = startEle
if __name__ == "__main__":
arr = [1, 2, 3, 4, 5, 6]
d = 2
rotateArr(arr, d)
# Print the rotated array
for i in range(len(arr)):
print(arr[i], end=" ")
C#
// C# Program to left rotate the array by d positions
// using Juggling Algorithm
using System;
class GfG {
// Function to rotate array
static void rotateArr(int[] arr, int d) {
int n = arr.Length;
// Handle the case where d > size of array
d %= n;
// Calculate the number of cycles in the rotation
int cycles = gcd(n, d);
// Process each cycle
for (int i = 0; i < cycles; i++) {
// Start element of current cycle
int startEle = arr[i];
// Start index of current cycle
int currIdx = i, nextIdx;
// Rotate elements till we reach the start of cycle
while (true) {
nextIdx = (currIdx + d) % n;
if (nextIdx == i)
break;
// Update the next index with the current element
arr[currIdx] = arr[nextIdx];
currIdx = nextIdx;
}
// Copy the start element of current cycle at the last
// index of the cycle
arr[currIdx] = startEle;
}
}
// function to compute GCD
static int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
static void Main(string[] args) {
int[] arr = { 1, 2, 3, 4, 5, 6 };
int d = 2;
rotateArr(arr, d);
// Print the rotated array
for (int i = 0; i < arr.Length; i++)
Console.Write(arr[i] + " ");
}
}
JavaScript
// JavaScript Program to left rotate the array by d positions
// using Juggling Algorithm
// Function to rotate array
function rotateArr(arr, d) {
let n = arr.length;
// Handle the case where d > size of array
d %= n;
// Calculate the number of cycles in the rotation
let cycles = gcd(n, d);
// Process each cycle
for (let i = 0; i < cycles; i++) {
// Start element of current cycle
let startEle = arr[i];
// Start index of current cycle
let currIdx = i, nextIdx;
// Rotate elements till we reach the start of cycle
while (true) {
nextIdx = (currIdx + d) % n;
if (nextIdx === i)
break;
// Update the next index with the current element
arr[currIdx] = arr[nextIdx];
currIdx = nextIdx;
}
// Copy the start element of current cycle at the last
// index of the cycle
arr[currIdx] = startEle;
}
}
// Helper function to compute GCD
function gcd(a, b) {
while (b !== 0) {
let temp = b;
b = a % b;
a = temp;
}
return a;
}
let arr = [1, 2, 3, 4, 5, 6];
let d = 2;
rotateArr(arr, d);
// Print the rotated array
console.log(arr.join(" "));
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:
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read