Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Reversal algorithm for Array rotation
Next article icon

Juggling Algorithm for Array Rotation

Last Updated : 09 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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(" ")); 

Output
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:

  • Rotate an Array – Data Structure and Algorithms Tutorial
  • Rotate an array by d positions
  • Reversal algorithm for Array rotation

Next Article
Reversal algorithm for Array rotation

M

mrityuanjay8vae
Improve
Article Tags :
  • DSA
  • Arrays
  • rotation
Practice Tags :
  • Arrays

Similar Reads

  • Reversal algorithm for Array rotation
    Given an array arr[] of size N, the task is to rotate the array by d position to the left. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7}, d = 2Output: 3, 4, 5, 6, 7, 1, 2Explanation: If the array is rotated by 1 position to the left, it becomes {2, 3, 4, 5, 6, 7, 1}.When it is rotated further by 1
    15 min read
  • Reversal algorithm for right rotation of an array
    Given an array, right rotate it by k elements. After K=3 rotation Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} k = 3 Output: 8 9 10 1 2 3 4 5 6 7 Input: arr[] = {121, 232, 33, 43 ,5} k = 2 Output: 43 5 121 232 33 Note : In the below solution, k is assumed to be smaller than or equal to n
    6 min read
  • Javascript Program for Reversal algorithm for array rotation
    Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements. Example : Input : arr[] = [1, 2, 3, 4, 5, 6, 7] d = 2 Output : arr[] = [3, 4, 5, 6, 7, 1, 2] Rotation of the above array by 2 will make array Recommended: Please solve it on “PRACTICE ” first, before moving on to the so
    3 min read
  • Javascript Program for Block swap algorithm for array rotation
    Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements. Rotation of the above array by 2 will make array Algorithm : Initialize A = arr[0..d-1] and B = arr[d..n-1] 1) Do following until size of A is equal to size of B a) If A is shorter, divide B into Bl and Br such that Br i
    3 min read
  • Javascript Program for Reversal algorithm for right rotation of an array
    Given an array, right rotate it by k elements.   After K=3 rotation  Examples:  Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} k = 3Output: 8 9 10 1 2 3 4 5 6 7Input: arr[] = {121, 232, 33, 43 ,5} k = 2Output: 43 5 121 232 33Note : In the below solution, k is assumed to be smaller than or equal to n
    2 min read
  • Naive Partition Algorithm
    Given an array arr[], the task is to partition the array by assuming last element as pivot element. The partition of an array must satisfy the following two conditions: Elements smaller than or equal to the pivot element appear before pivot in the array.Elements larger than the pivot element appear
    7 min read
  • Lomuto Partition Algorithm
    Given an array arr[], the task is to partition the array by assuming last element as pivot element. The partition of an array must satisfy the following two conditions: Elements smaller than the pivot element appear before pivot in the array.Elements larger than or equal to the pivot element appear
    7 min read
  • Hoare's Partition Algorithm
    Given an array arr[], the task is to partition the array by assuming first element as pivot element. The partition of an array must satisfy the following two conditions: Elements smaller than pivot element must appear at index less than or equal to partition index.Elements larger than or equal to pi
    7 min read
  • Print all possible rotations of a given Array
    Given an integer array arr[] of size N, the task is to print all possible rotations of the array.Examples: Input: arr[] = {1, 2, 3, 4} Output: {1, 2, 3, 4}, {4, 1, 2, 3}, {3, 4, 1, 2}, {2, 3, 4, 1} Explanation: Initial arr[] = {1, 2, 3, 4} After first rotation arr[] = {4, 1, 2, 3} After second rotat
    8 min read
  • Rotation Count in a Rotated Sorted array
    Given an array arr[] having distinct numbers sorted in increasing order and the array has been right rotated (i.e, the last element will be cyclically shifted to the starting position of the array) k number of times, the task is to find the value of k. Examples: Input: arr[] = {15, 18, 2, 3, 6, 12}O
    13 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences