Open In App

How to Left or Right rotate an Array in Java?

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of size N and D index, the task is to rotate the array by the D index. We have two flexibilities either to rotate them leftwards or rightwards via different ways which we are going to explore by implementing every way of rotating in both of the rotations.

Ways:

  1. Using temporary array
  2. Recursively rotating array one by one
  3. Using Juggling Algorithm

Left Rotation of Array

Illustration:

Input  : arr[] = {1, 2, 3, 4, 5} 
D = 2 
Output : 3 4 5 1 2 

Output explanation: 

  • The initial array [1, 2, 3, 4, 5]
  • rotate by first index [2, 3, 4, 5, 1]
  • rotate by second index [3, 4, 5, 1, 2]
Input : arr[] = {10, 34, 56, 23, 78, 12, 13, 65} 
D = 7 
Output: 65 10 34 56 23 78 12 13

Way 1: Using a temporary array

Approach:

In this method simply create a temporary array and copy the elements of the array arr[] from 0 to the (D-1)th index. After that move, the rest elements of the array arr[] from index D to N. Then move the temporary array elements to the original array.

Input arr[] = [1, 2, 3, 4, 5] 
D = 2 
  • Store the first d elements in a temp array: temp[] = [1, 2]
  • Shift rest of the arr[]: arr[] = [3, 4, 5]
  • Store back the D elements: arr[] = [3, 4, 5, 1, 2]

Example:

C++
// C++ program to Left Rotate an Array
// by D elements

#include <iostream>
using namespace std;

// Main class
class GFG {
  public:
  // Method 1
  // To left rotate arr[]
  // of size N by D
  void leftRotate(int arr[], int d, int n)
  {
    // Creating temp array of size d
    int temp[d];

    // Copying first d element in array temp
    for (int i = 0; i < d; i++)
      temp[i] = arr[i];

    // Moving the rest element to
    // index zero to N-d
    for (int i = d; i < n; i++)
      arr[i - d] = arr[i];

    // Copying the temp array element
    // in original array
    for (int i = 0; i < d; i++)
      arr[i + n - d] = temp[i];
  }

  // Method 2
  // To print an array
  void printArray(int arr[], int n)
  {
    for (int i = 0; i < n; i++)
      cout << arr[i] << " ";
  }
};

// Method 3
// Main driver method
int main()
{
  
  // Creating an object of class inside main()
  GFG rotate;

  // Custom input array
  int arr[] = { 1, 2, 3, 4, 5 };
  int size = sizeof(arr) / sizeof(arr[0]);

  // Calling method 1 and 2 as defined above
  rotate.leftRotate(arr, 2, size);
  rotate.printArray(arr, size);

  return 0;
}

// This code is contributed by akashish__
Java
// Java program to Left Rotate an Array
// by D elements

// Main class
class GFG {

    // Method 1
    // To left rotate arr[]
    // of size N by D
    void leftRotate(int arr[], int d, int n)
    {
        // Creating temp array of size d
        int temp[] = new int[d];

        // Copying first d element in array temp
        for (int i = 0; i < d; i++)
            temp[i] = arr[i];

        // Moving the rest element to index
        // zero to N-d
        for (int i = d; i < n; i++) {
            arr[i - d] = arr[i];
        }

        // Copying the temp array element
        // in original array
        for (int i = 0; i < d; i++) {
            arr[i + n - d] = temp[i];
        }
    }

    // Method 2
    // To print an array
    void printArray(int arr[], int n)
    {
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }

    // Method 3
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an object of class inside main()
        GFG rotate = new GFG();

        // Custom input array
        int arr[] = { 1, 2, 3, 4, 5 };

        // Calling method 1 and 2 as defined above
        rotate.leftRotate(arr, 2, arr.length);
        rotate.printArray(arr, arr.length);
    }
}

//code contributed by dhanshriborse
C#
using System;

class GFG
{
    // Method 1
    // To left rotate arr[]
    // of size N by D
    void LeftRotate(int[] arr, int d, int n)
    {
        // Creating temp array of size d
        int[] temp = new int[d];

        // Copying first d element in array temp
        for (int i = 0; i < d; i++)
            temp[i] = arr[i];

        // Moving the rest element to index
        // zero to N-d
        for (int i = d; i < n; i++)
        {
            arr[i - d] = arr[i];
        }

        // Copying the temp array element
        // in original array
        for (int i = 0; i < d; i++)
        {
            arr[i + n - d] = temp[i];
        }
    }

    // Method 2
    // To print an array
    void PrintArray(int[] arr, int n)
    {
        for (int i = 0; i < n; i++)
            Console.Write(arr[i] + " ");
    }

    // Method 3
    // Main driver method
    static void Main(string[] args)
    {
        // Creating an object of class inside main()
        GFG rotate = new GFG();

        // Custom input array
        int[] arr = { 1, 2, 3, 4, 5 };

        // Calling method 1 and 2 as defined above
        rotate.LeftRotate(arr, 2, arr.Length);
        rotate.PrintArray(arr, arr.Length);
    }
}
Javascript
// JavaScript 
// Main class
class GFG {
  // Method 1
  // To left rotate arr[]
  // of size N by D
  leftRotate(arr, d, n) {
    // Creating temp array of size d
    let temp = [];

    // Copying first d element in array temp
    for (let i = 0; i < d; i++)
      temp[i] = arr[i];

    // Moving the rest element to
    // index zero to N-d
    for (let i = d; i < n; i++)
      arr[i - d] = arr[i];

    // Copying the temp array element
    // in original array
    for (let i = 0; i < d; i++)
      arr[i + n - d] = temp[i];
  }

  // Method 2
  // To print an array
  printArray(arr, n) {
    for (let i = 0; i < n; i++)
      process.stdout.write(arr[i] + " ");
  }
}

// Method 3
// Main driver method
function main() {
  
  // Creating an object of class inside main()
  let rotate = new GFG();

  // Custom input array
  let arr = [ 1, 2, 3, 4, 5 ];
  let size = arr.length;

  // Calling method 1 and 2 as defined above
  rotate.leftRotate(arr, 2, size);
  rotate.printArray(arr, size);

  return 0;
}

main();
// This code is contributed by akashish__
Python3
# Python 3 program to Left Rotate an Array
# by D elements
# Main class
class GFG :
  
    # Method 1
    # To left rotate arr[]
    # of size N by D
    def leftRotate(self, arr,  d,  n) :
      
        # Creating temp array of size d
        temp = [0] * (d)
        
        # Copying first d element in array temp
        i = 0
        while (i < d) :
            temp[i] = arr[i]
            i += 1
            
        # Moving the rest element to index
        # zero to N-d
        i = d
        while (i < n) :
            arr[i - d] = arr[i]
            i += 1
            
        # Copying the temp array element
        # in original array
        i = 0
        while (i < d) :
            arr[i + n - d] = temp[i]
            i += 1
            
    # Method 2
    # To print an array
    def printArray(self, arr,  n) :
        i = 0
        while (i < n) :
            print(str(arr[i]) + " ", end ="")
            i += 1
            
    # Method 3
    # Main driver method
    @staticmethod
    def main( args) :
      
        # Creating an object of class inside main()
        rotate = GFG()
        
        # Custom input array
        arr = [1, 2, 3, 4, 5]
        
        # Calling method 1 and 2 as defined above
        rotate.leftRotate(arr, 2, len(arr))
        rotate.printArray(arr, len(arr))
    

if __name__=="__main__":
    GFG.main([])
    
    # This code is contributed by aadityaburujwale.

Output
3 4 5 1 2 

Time complexity: O(N) , 
Auxiliary Space: O(D)

Way 2: Rotate one by one

Approach:

Rotate the array recursively one by one element

Input arr[] = [1, 2, 3, 4, 5]
D = 21
  • Swap arr[0] to arr[1]
  • Swap arr[1] to arr[2]
  • Swap arr[N-1] to arr[N]
  • Repeat 1, 2, 3 to D times

In order to rotate by one, store arr[0] in a temporary variable temp, move arr[1] to arr[0], arr[2] to arr[1] …and finally temp to arr[n-1]

Illustration:

Let us take the same example arr[] = [1, 2, 3, 4, 5], d = 2 
Rotate arr[] by one 2 times 
We get [2, 3, 4, 5, 1] after first rotation and [ 3, 4, 5, 1, 2] after second rotation.

Example

C++
// C++ program to left rotate an array
// by Rotate one by one
#include <iostream>
void leftRotate(int arr[], int d, int n);
void leftRotatebyOne(int arr[], int n);
void printArray(int arr[], int n);
// Main class

// Method 1
// To rotate left by D elements
void leftRotate(int arr[], int d, int n)
{
    for (int i = 0; i < d; i++)
        leftRotatebyOne(arr, n);
}

// Method 2
// To rotate left one by one
void leftRotatebyOne(int arr[], int n)
{
    int i, temp;
    temp = arr[0];
    for (i = 0; i < n - 1; i++)
        arr[i] = arr[i + 1];
    arr[i] = temp;
}

// Method 3
// To print an array
void printArray(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        std::cout << arr[i] << " ";
}

// Method 4
// Main driver method
int main()
{

    // Custom input array
    int arr[] = { 1, 2, 3, 4, 5 };

    // Calling method to rotate array leftwards
    // and later printing the array elements
    leftRotate(arr, 2, 5);
    printArray(arr, 5);
    return 0;
}
// contributed by akashish__
Java
// Java program to left rotate an array
// by Rotate one by one

// Main class
class GFG {

    // Method 1
    // To rotate left by D elements
    void leftRotate(int arr[], int d, int n)
    {
        for (int i = 0; i < d; i++)
            leftRotatebyOne(arr, n);
    }

    // Method 2
    // To rotate left one by one
    void leftRotatebyOne(int arr[], int n)
    {
        int i, temp;
        temp = arr[0];
        for (i = 0; i < n - 1; i++)
            arr[i] = arr[i + 1];
        arr[i] = temp;
    }

    // Method 3
    // To print an array
    void printArray(int arr[], int n)
    {
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }

    // Method 4
    // Main driver method
    public static void main(String[] args)
    {
        // Creating object of class inside main()
        GFG rotate = new GFG();

        // Custom input array
        int arr[] = { 1, 2, 3, 4, 5 };

        // Calling method to rotate array leftwards
        // and later printing the array elements
        rotate.leftRotate(arr, 2, arr.length);
        rotate.printArray(arr, arr.length);
    }
}
C#
using System;

class Program
{
    
    // To rotate left by D elements
    static void LeftRotate(int[] arr, int d, int n)
    {
        for (int i = 0; i < d; i++)
            LeftRotateByOne(arr, n);
    }

    
    // To rotate left one by one
    static void LeftRotateByOne(int[] arr, int n)
    {
        int temp = arr[0];
        for (int i = 0; i < n - 1; i++)
            arr[i] = arr[i + 1];
        arr[n - 1] = temp;
    }

 
    // To print an array
    static void PrintArray(int[] arr)
    {
        for (int i = 0; i < arr.Length; i++)
            Console.Write(arr[i] + " ");
    }

    
    //  driver Code
    static void Main()
    {
        // Custom input array
        int[] arr = { 1, 2, 3, 4, 5 };

        // Calling method to rotate array leftwards
        // and later printing the array elements
        LeftRotate(arr, 2, 5);
        PrintArray(arr);
    }
}
Javascript
// Function to left rotate an array by d positions
function leftRotate(arr, d) {
    const n = arr.length;

    // Use a temporary array to store the rotated elements
    const temp = arr.slice(0, d);

    // Shift the remaining elements to the left
    for (let i = d; i < n; i++) {
        arr[i - d] = arr[i];
    }

    // Copy back the rotated elements from the temporary array
    for (let i = 0; i < d; i++) {
        arr[n - d + i] = temp[i];
    }
}

// Function to print an array
function printArray(arr) {
    for (let i = 0; i < arr.length; i++) {
        console.log(arr[i]);
    }
}

// Custom input array
const arr = [1, 2, 3, 4, 5];

// Calling the function to rotate the array leftwards
leftRotate(arr, 2);

// Printing the rotated array
printArray(arr);
Python3
# Python program to left rotate an array
# by Rotate one by one

# Main class
class GFG:

    # Method 1
    # To rotate left by D elements
    def leftRotate(self, arr, d, n):
        for i in range(d):
            self.leftRotatebyOne(arr, n)

    # Method 2
    # To rotate left one by one
    def leftRotatebyOne(self, arr, n):
        temp = arr[0]
        for i in range(n - 1):
            arr[i] = arr[i + 1]
        arr[n - 1] = temp

    # Method 3
    # To print an array
    def printArray(self, arr, n):
        for i in range(n):
            print(arr[i], end=" ")

    # Method 4
    # Main driver method
    def main(self):
        # Creating object of class inside main()
        rotate = GFG()

        # Custom input array
        arr = [1, 2, 3, 4, 5]

        # Calling method to rotate array leftwards
        # and later printing the array elements
        rotate.leftRotate(arr, 2, len(arr))
        rotate.printArray(arr, len(arr))


# Creating object of the class and calling the main method
gfg = GFG()
gfg.main()

Output
3 4 5 1 2 










Time complexity: O(N * D), 
Auxiliary Space: O(1) 

Way 3: Using Juggling Algorithm 

Approach: 

This is an extension of method 2. Instead of moving one by one, divide the array into different sets where the 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 above example array (n = 5 and d = 2), then elements will be moved within one set only, we just start with temp = arr[0] and keep moving arr[I+d] to arr[I] and finally store temp at the right place.

Example:

C++
#include<iostream>

class GFG {

    // Method 1
    // To left rotate arr[] of size N by D
    void leftRotate(int arr[], int d, int n) {
        // To handle if d >= n
        d = d % n;
        int i, j, k, temp;
        int g_c_d = gcd(d, n);

        for (i = 0; i < g_c_d; i++) {
            // move i-th values of blocks
            temp = arr[i];
            j = i;

            // Performing sets of operations if
            // condition holds true
            while (true) {
                k = j + d;
                if (k >= n)
                    k = k - n;
                if (k == i)
                    break;
                arr[j] = arr[k];
                j = k;
            }
            arr[j] = temp;
        }
    }

    // Method 2
    // To print an array
    void printArray(int arr[], int size) {
        int i;
        for (i = 0; i < size; i++)
            std::cout << arr[i] << " ";
    }

    // Method 3
    // To get gcd of a and b
    int gcd(int a, int b) {
        if (b == 0)
            return a;
        else
            return gcd(b, a % b);
    }

    // Method 4
    // main driver method
public:
    void rotateArray() {
        // Custom array elements
        int arr[] = { 1, 2, 3, 4, 5 };

        // Calling above methods inside main() to
        // left rotate and print the array elements
        leftRotate(arr, 2, sizeof(arr) / sizeof(arr[0]));
        printArray(arr, sizeof(arr) / sizeof(arr[0]));
    }
};

int main() {
    // Creating instance of class inside main() method
    GFG rotate;
    rotate.rotateArray();
    return 0;
}
Java
// Java program to left rotate an array by d elements
// using Juggling Algorithm

// Main class
class GFG {

    // Method 1
    // To left rotate arr[] of size N by D
    void leftRotate(int arr[], int d, int n)
    {
        // To handle if d >= n
        d = d % n;
        int i, j, k, temp;
        int g_c_d = gcd(d, n);

        for (i = 0; i < g_c_d; i++) {

            // move i-th values of blocks
            temp = arr[i];
            j = i;

            // Performing sets of operations if
            // condition holds true
            while (true) {
                k = j + d;
                if (k >= n)
                    k = k - n;
                if (k == i)
                    break;
                arr[j] = arr[k];
                j = k;
            }
            arr[j] = temp;
        }
    }

    // Method 2
    // To print an array
    void printArray(int arr[], int size)
    {
        int i;
        for (i = 0; i < size; i++)
            System.out.print(arr[i] + " ");
    }

    // Method 3
    // To get gcd of a and b
    int gcd(int a, int b)
    {
        if (b == 0)
            return a;
        else
            return gcd(b, a % b);
    }

    // Method 4
    // main driver method
    public static void main(String[] args)
    {
        // Creating instance of class inside main() method
        GFG rotate = new GFG();

        // Custom array elements
        int arr[] = { 1, 2, 3, 4, 5 };

        // Calling above methods inside main() to
        // left rotate and print the array elements
        rotate.leftRotate(arr, 2, arr.length);
        rotate.printArray(arr, arr.length);
    }
}
Python
class GFG:
    # Method 1
    # To left rotate arr[] of size N by D
    def left_rotate(self, arr, d, n):
        # To handle if d >= n
        d = d % n
        g_c_d = self.gcd(d, n)

        for i in range(g_c_d):
            # move i-th values of blocks
            temp = arr[i]
            j = i

            # Performing sets of operations if
            # condition holds true
            while True:
                k = j + d
                if k >= n:
                    k = k - n
                if k == i:
                    break
                arr[j] = arr[k]
                j = k
            arr[j] = temp

    # Method 2
    # To print an array
    def print_array(self, arr):
        for i in arr:
            print(i),

    # Method 3
    # To get gcd of a and b
    def gcd(self, a, b):
        if b == 0:
            return a
        else:
            return self.gcd(b, a % b)

    # Method 4
    # main driver method
    def rotate_array(self):
        # Custom array elements
        arr = [1, 2, 3, 4, 5]

        # Calling above methods inside main() to
        # left rotate and print the array elements
        self.left_rotate(arr, 2, len(arr))
        self.print_array(arr)


# Creating an instance of the class and calling rotate_array() method
rotate_instance = GFG()
rotate_instance.rotate_array()
C#
using System;

class GFG
{
    // Method 1
    // To left rotate arr[] of size N by D
    void LeftRotate(int[] arr, int d, int n)
    {
        // To handle if d >= n
        d = d % n;
        int i, j, k, temp;
        int g_c_d = GCD(d, n);

        for (i = 0; i < g_c_d; i++)
        {
            // move i-th values of blocks
            temp = arr[i];
            j = i;

            // Performing sets of operations if
            // condition holds true
            while (true)
            {
                k = j + d;
                if (k >= n)
                    k = k - n;
                if (k == i)
                    break;
                arr[j] = arr[k];
                j = k;
            }
            arr[j] = temp;
        }
    }

    // Method 2
    // To print an array
    void PrintArray(int[] arr, int size)
    {
        for (int i = 0; i < size; i++)
            Console.Write(arr[i] + " ");
    }

    // Method 3
    // To get gcd of a and b
    int GCD(int a, int b)
    {
        if (b == 0)
            return a;
        else
            return GCD(b, a % b);
    }

    // Method 4
    // main driver method
    public void RotateArray()
    {
        // Custom array elements
        int[] arr = { 1, 2, 3, 4, 5 };

        // Calling above methods inside main() to
        // left rotate and print the array elements
        LeftRotate(arr, 2, arr.Length);
        PrintArray(arr, arr.Length);
    }
}

class Program
{
    static void Main()
    {
        // Creating instance of class inside Main() method
        GFG rotate = new GFG();
        rotate.RotateArray();
    }
}
Javascript
class GFG {
    // Method to left rotate arr[] of size n by d
    leftRotate(arr, d, n) {
        // To handle if d >= n
        d = d % n;
        let temp, j, k;
        const g_c_d = this.gcd(d, n);

        for (let i = 0; i < g_c_d; i++) {
            // move i-th values of blocks
            temp = arr[i];
            j = i;

            // Performing sets of operations if
            // condition holds true
            while (true) {
                k = j + d;
                if (k >= n)
                    k = k - n;
                if (k === i)
                    break;
                arr[j] = arr[k];
                j = k;
            }
            arr[j] = temp;
        }
    }

    // Method to print an array
    printArray(arr) {
        console.log(arr.join(' '));
    }

    // Method to get gcd of a and b
    gcd(a, b) {
        if (b === 0)
            return a;
        else
            return this.gcd(b, a % b);
    }

    // Driver method
    rotateArray() {
        // Custom array elements
        const arr = [1, 2, 3, 4, 5];

        // Call leftRotate to left rotate the array by 2 positions
        this.leftRotate(arr, 2, arr.length);
        // Print the rotated array
        this.printArray(arr);
    }
}

// Creating an instance of the class and calling the rotateArray method
const rotate = new GFG();
rotate.rotateArray();
//this code is contribuited by Utkarsh

Output
3 4 5 1 2 





Time complexity: O(n) , Auxiliary Space: O(1) 

Right Rotation of Array


Illustration:

Input  : arr[] = {1, 2, 3, 4, 5} 
D = 2
Output : 4 5 1 2 3 

Output explanation:

  • The initial array [1, 2, 3, 4, 5]
  • rotate first index [2, 3, 4, 5, 1]
  • rotate second index [3, 4, 5, 1, 2]
  • rotate third index [4, 5, 1, 2, 3]
Input: arr[] : {10, 34, 56, 23, 78, 12, 13, 65} 
D = 5 
Output : 56 23 78 12 13 65 10 34 

Way 1: Using temp array

Approach:

In this method simply create a temporary array and copy the elements of the array arr[] from 0 to the N – D index. After that move, the rest elements of the array arr[] from index D to N. Then move the temporary array elements to the original array. It is as illustrated below illustration as follows:

Input arr[] = [1, 2, 3, 4, 5], D = 2
1) Store the first d elements in a temp array
temp[] = [1, 2, 3]
2) Shift rest of the arr[]
arr[] = [4, 5]
3) Store back the D elements
arr[] = [4, 5, 1, 2, 3]

Example:

C++
#include <iostream>

// Main class
class GFG {

    // Method 1
    // To right rotate arr[] of size N by D
    void rightRotate(int arr[], int d, int n)
    {

        // If arr is rotated n times then
        // you get the same array
        while (d > n) {
            d = d - n;
        }

        // Creating a temporary array of size d
        int temp[n - d];

        // Now copying first N-D element in array temp
        for (int i = 0; i < n - d; i++)
            temp[i] = arr[i];

        // Moving the rest element to index zero to D
        for (int i = n - d; i < n; i++) {
            arr[i - n + d] = arr[i];
        }

        // Copying the temp array element
        // in the original array
        for (int i = 0; i < n - d; i++) {
            arr[i + d] = temp[i];
        }
    }

    // Method 2
    // To print an array
    void printArray(int arr[], int n)
    {
        for (int i = 0; i < n; i++)

            // Printing elements of an array
            std::cout << arr[i] << " ";
    }

    // Method 3
    // Main driver method
public:
    static void main()
    {

        // Creating an object of class inside the main() method
        GFG rotate;

        // Custom input array
        int arr[] = { 1, 2, 3, 4, 5 };

        // Calling method1 to rotate array
        rotate.rightRotate(arr, 2, sizeof(arr) / sizeof(arr[0]));

        // Calling method 2 to print array
        rotate.printArray(arr, sizeof(arr) / sizeof(arr[0]));
    }
};

int main() {
    // Creating an object of the class and calling the main method
    GFG::main();

    return 0;
}
Java
// Java program to rotate an array by D elements

// Main class
class GFG {

    // Method 1
    // To right rotate arr[] of size N by D
    void rightRotate(int arr[], int d, int n)
    {

        // If arr is rotated n times then
        // you get the same array
        while (d > n) {
            d = d - n;
        }

        // Creating a temporary array of size d
        int temp[] = new int[n - d];

        // Now copying first N-D element in array temp
        for (int i = 0; i < n - d; i++)
            temp[i] = arr[i];

        // Moving the rest element to index zero to D
        for (int i = n - d; i < n; i++) {
            arr[i - n + d] = arr[i];
        }

        // Copying the temp array element
        // in original array
        for (int i = 0; i < n - d; i++) {
            arr[i + d] = temp[i];
        }
    }

    // Method 2
    // To print an array
    void printArray(int arr[], int n)
    {
        for (int i = 0; i < n; i++)

            // Printing elements of an array
            System.out.print(arr[i] + " ");
    }

    // Method 3
    // Main driver method
    public static void main(String[] args)
    {

        // Creating object of class inside main() method
        GFG rotate = new GFG();

        // Custom input array
        int arr[] = { 1, 2, 3, 4, 5 };

        // Calling method1 to rotate array
        rotate.rightRotate(arr, 2, arr.length);

        // Calling method 2 to print array
        rotate.printArray(arr, arr.length);
    }
}
C#
using System;

// Main class
class GFG {
    // Method 1
    // To right rotate arr[] of size N by D
    void RightRotate(int[] arr, int d, int n)
    {
        // If arr is rotated n times then
        // you get the same array
        while (d > n) {
            d = d - n;
        }

        // Creating a temporary array of size d
        int[] temp = new int[n - d];

        // Now copying first N-D element in array temp
        for (int i = 0; i < n - d; i++) {
            temp[i] = arr[i];
        }

        // Moving the rest element to index zero to D
        for (int i = n - d; i < n; i++) {
            arr[i - n + d] = arr[i];
        }

        // Copying the temp array element
        // in the original array
        for (int i = 0; i < n - d; i++) {
            arr[i + d] = temp[i];
        }
    }

    // Method 2
    // To print an array
    void PrintArray(int[] arr, int n)
    {
        for (int i = 0; i < n; i++) {
            // Printing elements of an array
            Console.Write(arr[i] + " ");
        }
    }

    // Main driver method
    public static void Main()
    {
        // Creating an object of class inside the Main()
        // method
        GFG rotate = new GFG();

        // Custom input array
        int[] arr = { 1, 2, 3, 4, 5 };

        // Calling Method1 to rotate array
        rotate.RightRotate(arr, 2, arr.Length);

        // Calling Method 2 to print array
        rotate.PrintArray(arr, arr.Length);
    }
}
Javascript
class GFG {
    // Method 1
    // To right rotate arr[] of size N by D
    rightRotate(arr, d, n) {
        // If arr is rotated n times then
        // you get the same array
        while (d > n) {
            d = d - n;
        }

        // Creating a temporary array of size d
        let temp = new Array(n - d);

        // Now copying first N-D element in array temp
        for (let i = 0; i < n - d; i++) {
            temp[i] = arr[i];
        }

        // Moving the rest element to index zero to D
        for (let i = n - d; i < n; i++) {
            arr[i - n + d] = arr[i];
        }

        // Copying the temp array element
        // in the original array
        for (let i = 0; i < n - d; i++) {
            arr[i + d] = temp[i];
        }
    }

    // Method 2
    // To print an array
    printArray(arr) {
        for (let i = 0; i < arr.length; i++) {
            // Printing elements of an array
            console.log(arr[i] + " ");
        }
    }

    // Method 3
    // Main driver method
    static main() {
        // Creating an object of class inside the main() method
        const rotate = new GFG();

        // Custom input array
        let arr = [1, 2, 3, 4, 5];

        // Calling method1 to rotate array
        rotate.rightRotate(arr, 2, arr.length);

        // Calling method 2 to print array
        rotate.printArray(arr);
    }
}

// Creating an object of the class and calling the main method
GFG.main();
Python3
# Main class
class GFG:

    # Method 1
    # To right rotate arr[] of size N by D
    def rightRotate(self, arr, d, n):
        # If arr is rotated n times then
        # you get the same array
        while d > n:
            d = d - n

        # Creating a temporary array of size d
        temp = arr[:n - d]

        # Moving the rest element to index zero to D
        arr[:d] = arr[n - d:n]

        # Copying the temp array element
        # in the original array
        arr[d:] = temp

    # Method 2
    # To print an array
    def printArray(self, arr, n):
        # Printing elements of an array
        for i in range(n):
            print(arr[i], end=" ")

    # Method 3
    # Main driver method
    @staticmethod
    def main():
        # Creating an object of class inside the main() method
        rotate = GFG()

        # Custom input array
        arr = [1, 2, 3, 4, 5]

        # Calling method1 to rotate array
        rotate.rightRotate(arr, 2, len(arr))

        # Calling method 2 to print array
        rotate.printArray(arr, len(arr))


# Creating an object of the class and calling the main method
GFG.main()
# This code is contributed by Prachi

Output
4 5 1 2 3 



Time complexity: O(N) , Auxiliary Space: O(D)

Way 2: Rotate one by one 

Approach: Rotate the array recursively one by one element

Input arr[] = [1, 2, 3, 4, 5], D = 2
  • swap arr[N] to arr[N-1]
  • swap arr[N-1] to arr[N-2]
  • swap arr[2] to arr[1]
  • Repeat 1, 2, 3 to D times

To rotate by one, store arr[N] in a temporary variable temp, move arr[N-1] to arr[N], arr[N-2] to arr[N-1] … and finally temp to arr[1].

Let us take the same example arr[] = [1, 2, 3, 4, 5], d = 2 
Rotate arr[] by one 2 times 
We get [5, 1, 2, 3, 4] after first rotation and [ 4, 5, 1, 2, 3] after second rotation.

 Example:

Java
// Java Program to Rotating Elements One by One 

// Main class
class GFG {

    // Method 1
    // To right rotate array of size n by d
    void rightRotate(int arr[], int d, int n)
    {
        // Iterating till we want
        for (int i = n; i > d; i--)

            // Recursively calling
            rightRotatebyOne(arr, n);
    }

    // Method 2
    // To rotate array by 1
    void rightRotatebyOne(int arr[], int n)
    {
        int i, temp;
        temp = arr[0];
        for (i = 0; i < n - 1; i++)
            arr[i] = arr[i + 1];
        arr[i] = temp;
    }

    // Method 3
    // To print an array
    void printArray(int arr[], int n)
    {
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }

    // Method 4
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an object of class inside main()
        GFG rotate = new GFG();

        // Custom input elements
        int arr[] = { 1, 2, 3, 4, 5 };

        // Calling method 1 and 2
        rotate.rightRotate(arr, 2, arr.length);
        rotate.printArray(arr, arr.length);
    }
}
Javascript
// JavaScript Class to Rotate Elements One by One
class RotateArray {

    // Method 1
    // To right rotate array of size n by d
    rightRotate(arr, d, n) {
        // Iterating till we want
        for (let i = n; i > d; i--) {
            // Recursively calling rightRotatebyOne
            this.rightRotatebyOne(arr, n);
        }
    }

    // Method 2
    // To rotate array by 1
    rightRotatebyOne(arr, n) {
        let temp = arr[0];
        for (let i = 0; i < n - 1; i++)
            arr[i] = arr[i + 1];
        arr[n - 1] = temp;
    }

    // Method 3
    // To print an array
    printArray(arr) {
        console.log(arr.join(' '));
    }

    // Main driver method
    static main() {
        // Creating an object of class inside main()
        const rotate = new RotateArray();

        // Custom input elements
        let arr = [1, 2, 3, 4, 5];

        // Calling method 1 and 2
        rotate.rightRotate(arr, 2, arr.length);
        rotate.printArray(arr);
    }
}

// Call the main method to execute the code
RotateArray.main();

Output
4 5 1 2 3 










Here we have rotated 2 elements one by one else if we would have had rotated by one element only then the array would have been [2,3,4,5,1]

Time complexity: O(N * D) , Auxiliary Space: O(1) 
 

Way 3: Juggling Algorithm 

Approach: This is an extension of method 2. Instead of moving one by one, divide the array into different sets where the 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 above example array (n = 5 and d =2), then elements will be moved within one set only, we just start with temp = arr[N] and keep moving arr[I+d] to arr[I] and finally store temp at the right place.
 

Java
// Java Program to Rotate Array Elements
// Using Juggling Algorithm

// Main class
class GFG {

    // Method 1
    // To right rotate arr[]
    // of size N by D
    void rightRotate(int arr[], int d, int n)
    {

        // To use as left rotation
        d = n - d;
        d = d % n;
        int i, j, k, temp;
        int g_c_d = gcd(d, n);

        for (i = 0; i < g_c_d; i++) {

            // Moving i-th values of blocks
            temp = arr[i];
            j = i;

            while (true) {
                k = j + d;
                if (k >= n)
                    k = k - n;
                if (k == i)
                    break;
                arr[j] = arr[k];
                j = k;
            }
            arr[j] = temp;
        }
    }

    // Method 2
    // To print an array
    void printArray(int arr[], int size)
    {

        int i;
        for (i = 0; i < size; i++)
            System.out.print(arr[i] + " ");
    }

    // Method 3
    // To get gcd of a and b
    int gcd(int a, int b)
    {

        if (b == 0)
            return a;
        else
            return gcd(b, a % b);
    }

    // Method 4
    // Main driver method
    public static void main(String[] args)
    {
        // Creating object of class inside main()
        GFG rotate = new GFG();

        // Custom input elements
        int arr[] = { 1, 2, 3, 4, 5 };

        // Calling methods 1 and 2
        rotate.rightRotate(arr, 2, arr.length);
        rotate.printArray(arr, arr.length);
    }
}

Output
4 5 1 2 3 










Time complexity: O(n) , Auxiliary Space: O(1) 



Last Updated : 11 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads