Given an array of integers arr[] of size N and an integer, the task is to rotate the array elements to the left by d positions.
Examples:
Input:
arr[] = {1, 2, 3, 4, 5, 6, 7}, d = 2
Output: 3 4 5 6 7 1 2Input: arr[] = {3, 4, 5, 6, 7, 1, 2}, d=2
Output: 5 6 7 1 2 3 4
Approach 1 (Using temp array): This problem can be solved using the below idea:
After rotating d positions to the left, the first d elements become the last d elements of the array
- First store the elements from index d to N-1 into the temp array.
- Then store the first d elements of the original array into the temp array.
- Copy back the elements of the temp array into the original array
Illustration:
Suppose the give array is arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2.
First Step:
=> Store the elements from 2nd index to the last.
=> temp[] = [3, 4, 5, 6, 7]Second Step:
=> Now store the first 2 elements into the temp[] array.
=> temp[] = [3, 4, 5, 6, 7, 1, 2]Third Steps:
=> Copy the elements of the temp[] array into the original array.
=> arr[] = temp[] So arr[] = [3, 4, 5, 6, 7, 1, 2]
Follow the steps below to solve the given problem.
- Initialize a temporary array(temp[n]) of length same as the original array
- Initialize an integer(k) to keep a track of the current index
- Store the elements from the position d to n-1 in the temporary array
- Now, store 0 to d-1 elements of the original array in the temporary array
- Lastly, copy back the temporary array to the original array
Below is the implementation of the above approach :
C++
| #include <bits/stdc++.h>usingnamespacestd;// Function to rotate arrayvoidRotate(intarr[], intd, intn){    // Storing rotated version of array    inttemp[n];    // Keeping track of the current index    // of temp[]    intk = 0;    // Storing the n - d elements of    // array arr[] to the front of temp[]    for(inti = d; i < n; i++) {        temp[k] = arr[i];        k++;    }    // Storing the first d elements of array arr[]    //  into temp    for(inti = 0; i < d; i++) {        temp[k] = arr[i];        k++;    }    // Copying the elements of temp[] in arr[]    // to get the final rotated array    for(inti = 0; i < n; i++) {        arr[i] = temp[i];    }}// Function to print elements of arrayvoidPrintTheArray(intarr[], intn){    for(inti = 0; i < n; i++) {        cout << arr[i] << " ";    }}// Driver codeintmain(){    intarr[] = { 1, 2, 3, 4, 5, 6, 7 };    intN = sizeof(arr) / sizeof(arr[0]);    intd = 2;    // Function calling    Rotate(arr, d, N);    PrintTheArray(arr, N);    return0;} | 
Java
| /*package whatever //do not write package name here */importjava.io.*;classGFG {    // Function to rotate arraystaticvoidRotate(intarr[], intd, intn){    // Storing rotated version of array    inttemp[] = newint[n];    // Keeping track of the current index    // of temp[]    intk = 0;    // Storing the n - d elements of    // array arr[] to the front of temp[]    for(inti = d; i < n; i++) {        temp[k] = arr[i];        k++;    }    // Storing the first d elements of array arr[]    //  into temp    for(inti = 0; i < d; i++) {        temp[k] = arr[i];        k++;    }    // Copying the elements of temp[] in arr[]    // to get the final rotated array    for(inti = 0; i < n; i++) {        arr[i] = temp[i];    }}// Function to print elements of arraystaticvoidPrintTheArray(intarr[], intn){    for(inti = 0; i < n; i++) {        System.out.print(arr[i]+" ");    }}    publicstaticvoidmain (String[] args) {        intarr[] = { 1, 2, 3, 4, 5, 6, 7};        intN = arr.length;        intd = 2;        // Function calling        Rotate(arr, d, N);        PrintTheArray(arr, N);    }}// This code is contributed by ishankhandelwals. | 
Python3
| defrotate(L, d, n):    k =L.index(d)    new_lis =[]    new_lis =L[k+1:]+L[0:k+1]    returnnew_lisif__name__ =='__main__':    arr =[1, 2, 3, 4, 5, 6, 7]    d =2    N =len(arr)    # Function call    arr =rotate(arr, d, N)    fori inarr:        print(i, end=" ") | 
C#
| // Include namespace systemusingSystem;publicclassGFG{  // Function to rotate array  publicstaticvoidRotate(int[] arr, intd, intn)  {    // Storing rotated version of array    int[] temp = newint[n];    // Keeping track of the current index    // of temp[]    vark = 0;    // Storing the n - d elements of    // array arr[] to the front of temp[]    for(inti = d; i < n; i++)    {      temp[k] = arr[i];      k++;    }    // Storing the first d elements of array arr[]    //  into temp    for(inti = 0; i < d; i++)    {      temp[k] = arr[i];      k++;    }    // Copying the elements of temp[] in arr[]    // to get the final rotated array    for(inti = 0; i < n; i++)    {      arr[i] = temp[i];    }  }  // Function to print elements of array  publicstaticvoidPrintTheArray(int[] arr, intn)  {    for(inti = 0; i < n; i++)    {      Console.Write(arr[i].ToString() + " ");    }  }  publicstaticvoidMain(String[] args)  {    int[] arr = {1, 2, 3, 4, 5, 6, 7};    varN = arr.Length;    vard = 2;    // Function calling    GFG.Rotate(arr, d, N);    GFG.PrintTheArray(arr, N);  }}// This code is contributed by ishankhandelwals. | 
Javascript
| functionRotate_and_Print(arr,d,n) {     //Initializing array temp with size n     vartemp=newArray(n);         let k = 0;    // Storing the n - d elements of    // array arr[] to the front of temp[]    for(let i = d; i < n; i++) {        temp[k] = arr[i];        k++;    }    // Storing the first d elements of array arr[]    //  into temp    for(let i = 0; i < d; i++) {        temp[k] = arr[i];        k++;    }    //Printing the temp array which stores the result    for(let i = 0; i < n; i++) {        console.log(temp[i]+" ");    } }let arr = [ 1, 2, 3, 4, 5, 6, 7 ];let n = arr.length;let d = 2; //number of times rotating the arrayRotate_and_Print(arr, d, n);//contributed by keerthikarathan123 | 
3 4 5 6 7 1 2
Time complexity: O(N) 
Auxiliary Space: O(N)
Approach 2 (Rotate one by one): This problem can be solved using the below idea:
- At each iteration, shift the elements by one position to the left circularly (i.e., first element becomes the last).
- Perform this operation d times to rotate the elements to the left by d position.
Illustration:
Let us take arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2.
First Step:
=> Rotate to left by one position.
=> arr[] = {2, 3, 4, 5, 6, 7, 1}Second Step:
=> Rotate again to left by one position
=> arr[] = {3, 4, 5, 6, 7, 1, 2}Rotation is done by 2 times.
So the array becomes arr[] = {3, 4, 5, 6, 7, 1, 2}
Follow the steps below to solve the given problem.
- Rotate the array to left by one position. For that do the following:
- Store the first element of the array in a temporary variable.
- Shift the rest of the elements in the original array by one place.
- Update the last index of the array with the temporary variable.
 
- Repeat the above steps for the number of left rotations required.
Below is the implementation of the above approach:
C++
| // C++ program to rotate an array by// d elements#include <bits/stdc++.h>usingnamespacestd;/*Function to left rotate arr[] of size n by d*/voidRotate(intarr[], intd, intn){    intp = 1;    while(p <= d) {        intlast = arr[0];        for(inti = 0; i < n - 1; i++) {            arr[i] = arr[i + 1];        }        arr[n - 1] = last;        p++;    }}// Function to print an arrayvoidprintArray(intarr[], intsize){    for(inti = 0; i < size; i++)        cout << arr[i] << " ";}// Driver codeintmain(){    intarr[] = { 1, 2, 3, 4, 5, 6, 7 };    intN = sizeof(arr) / sizeof(arr[0]);    intd = 2;      // Function calling    Rotate(arr, d, N);    printArray(arr, N);    return0;} | 
Java
| /*package whatever //do not write package name here */importjava.io.*;classGFG {        publicstaticvoidrotate(intarr[], intd, intn)    {        intp = 1;        while(p <= d) {            intlast = arr[0];            for(inti = 0; i < n - 1; i++) {                arr[i] = arr[i + 1];            }            arr[n - 1] = last;            p++;        }        for(inti = 0; i < n; i++) {            System.out.print(arr[i] + " ");        }    }        publicstaticvoidmain(String[] args)    {        intarr[] = { 1, 2, 3, 4, 5, 6, 7};        intN = arr.length;        // Rotate 2 times        intd = 2;        // Function call        rotate(arr, d, N);    }}// contributed by keerthikarathan123 | 
Python3
| # Python program to rotate an array by d elements# Function to left rotate arr[] of size n by ddefRotate(arr, d, n):  p =1  while(p <=d):    last =arr[0]    fori inrange(n -1):      arr[i] =arr[i +1]    arr[n -1] =last    p =p +1    # Function to print an arraydefprintArray(arr, size):  fori inrange(size):    print(arr[i] ,end =" ")    # Driver codearr =[1, 2, 3, 4, 5, 6, 7]N =len(arr)d =2# Function callingRotate(arr, d, N)printArray(arr, N)# This code is contributed by Atul_kumar_Shrivastava | 
C#
| // Include namespace systemusingSystem;publicclassGFG{    publicstaticvoidrotate(int[] arr, intd, intn)    {        varp = 1;        while(p <= d)        {            varlast = arr[0];            for(inti = 0; i < n - 1; i++)            {                arr[i] = arr[i + 1];            }            arr[n - 1] = last;            p++;        }        for(inti = 0; i < n; i++)        {            Console.Write(arr[i].ToString() + " ");        }    }    publicstaticvoidMain(String[] args)    {        int[] arr = {1, 2, 3, 4, 5, 6, 7};        varN = arr.Length;        // Rotate 2 times        vard = 2;        // Function call        GFG.rotate(arr, d, N);    }} | 
Javascript
| functionprintArray(arr,n,d){    let p = 1;        while(p <= d) {            let last = arr[0];            for(let i = 0; i < n - 1; i++) {                arr[i] = arr[i + 1];            }            arr[n - 1] = last;            p++;        }         for(let i = 0; i < n; i++) {            console.log(arr[i] + " ");        }}let arr = [ 1, 2, 3, 4, 5, 6, 7 ];let n = arr.length;let d=2; //number of times rotating the array// Function callingprintArray(arr, n,d);//contributed by keerthikarathan123 | 
3 4 5 6 7 1 2
Time Complexity: O(N * d)
Auxiliary Space: O(1)
Approach 3 (A Juggling Algorithm): 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 the GCD of N and d (say X. So the elements which are X distance apart are part of a set) and rotate the elements within sets by 1 position to the left.
- Calculate the GCD between the length and the distance to be moved.
- The elements are only shifted within the sets.
- We start with temp = arr[0] and keep moving arr[I+d] to arr[I] and finally store temp at the right place.
Follow the below illustration for a better understanding
Illustration:
Each steps looks like following:
Let arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14} and d = 10
First step:
=> First set is {0, 5, 10}.
=> Rotate this set by d position in cyclic order
=> arr[0] = arr[0+10]
=> arr[10] = arr[(10+10)%15]
=> arr[5] = arr[0]
=> This set becomes {10,0,5}
=> Array arr[] = {10, 1, 2, 3, 4, 0, 6, 7, 8, 9, 5, 11, 12, 13, 14}Second step:
=> Second set is {1, 6, 11}.
=> Rotate this set by d position in cyclic order.
=> This set becomes {11, 1, 6}
=> Array arr[] = {10, 11, 2, 3, 4, 0, 1, 7, 8, 9, 5, 6, 12, 13, 14}Third step:
=> Second set is {2, 7, 12}.
=> Rotate this set by d position in cyclic order.
=> This set becomes {12, 2, 7}
=> Array arr[] = {10, 11, 12, 3, 4, 0, 1, 2, 8, 9, 5, 6, 7, 13, 14}Fourth step:
=> Second set is {3, 8, 13}.
=> Rotate this set by d position in cyclic order.
=> This set becomes {13, 3, 8}
=> Array arr[] = {10, 11, 12, 13, 4, 0, 1, 2, 3, 9, 5, 6, 7, 8, 14}Fifth step:
=> Second set is {4, 9, 14}.
=> Rotate this set by d position in cyclic order.
=> This set becomes {14, 4, 9}
=> Array arr[] = {10, 11, 12, 13, 14, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
Follow the steps below to solve the given problem.
- Perform d%n in order to keep the value of d within the range of the array where d is the number of times the array is rotated and N is the size of the array.
- Calculate the GCD(N, d) to divide the array into sets.
- Run a for loop from 0 to the value obtained from GCD.
- Store the value of arr[i] in a temporary variable (the value of i denotes the set number).
- Run a while loop to update the values according to the set.
 
- After exiting the while loop assign the value of arr[j] as the value of the temporary variable (the value of j denotes the last element of the ith set).
Below is the implementation of the above approach :
C++
| // C++ program to rotate an array by// d elements#include <bits/stdc++.h>usingnamespacestd;/*Function to get gcd of a and b*/intgcd(inta, intb){    if(b == 0)        returna;    else        returngcd(b, a % b);}/*Function to left rotate arr[] of size n by d*/voidleftRotate(intarr[], intd, intn){    /* To handle if d >= n */    d = d % n;    intg_c_d = gcd(d, n);    for(inti = 0; i < g_c_d; i++) {        /* move i-th values of blocks */        inttemp = arr[i];        intj = i;        while(1) {            intk = j + d;            if(k >= n)                k = k - n;            if(k == i)                break;            arr[j] = arr[k];            j = k;        }        arr[j] = temp;    }}// Function to print an arrayvoidprintArray(intarr[], intsize){    for(inti = 0; i < size; i++)        cout << arr[i] << " ";}/* Driver program to test above functions */intmain(){    intarr[] = { 1, 2, 3, 4, 5, 6, 7 };    intn = sizeof(arr) / sizeof(arr[0]);    // Function calling    leftRotate(arr, 2, n);    printArray(arr, n);    return0;} | 
C
| // C program to rotate an array by// d elements#include <stdio.h>/* function to print an array */voidprintArray(intarr[], intsize);/*Function to get gcd of a and b*/intgcd(inta, intb);/*Function to left rotate arr[] of size n by d*/voidleftRotate(intarr[], intd, intn){    inti, j, k, temp;    /* To handle if d >= n */    d = d % n;    intg_c_d = gcd(d, n);    for(i = 0; i < g_c_d; i++) {        /* move i-th values of blocks */        temp = arr[i];        j = i;        while(1) {            k = j + d;            if(k >= n)                k = k - n;            if(k == i)                break;            arr[j] = arr[k];            j = k;        }        arr[j] = temp;    }}/*UTILITY FUNCTIONS*//* function to print an array */voidprintArray(intarr[], intn){    inti;    for(i = 0; i < n; i++)        printf("%d ", arr[i]);}/*Function to get gcd of a and b*/intgcd(inta, intb){    if(b == 0)        returna;    else        returngcd(b, a % b);}/* Driver program to test above functions */intmain(){    intarr[] = { 1, 2, 3, 4, 5, 6, 7 };    leftRotate(arr, 2, 7);    printArray(arr, 7);    getchar();    return0;} | 
Java
| // Java program to rotate an array by// d elementsimportjava.io.*;classRotateArray {    /*Function to left rotate arr[] of size n by d*/    voidleftRotate(intarr[], intd, intn)    {        /* To handle if d >= n */        d = d % n;        inti, j, k, temp;        intg_c_d = gcd(d, n);        for(i = 0; i < g_c_d; i++) {            /* move 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;        }    }    /*UTILITY FUNCTIONS*/    /* function to print an array */    voidprintArray(intarr[], intsize)    {        inti;        for(i = 0; i < size; i++)            System.out.print(arr[i] + " ");    }    /*Function to get gcd of a and b*/    intgcd(inta, intb)    {        if(b == 0)            returna;        else            returngcd(b, a % b);    }    // Driver program to test above functions    publicstaticvoidmain(String[] args)    {        RotateArray rotate = newRotateArray();        intarr[] = { 1, 2, 3, 4, 5, 6, 7};        rotate.leftRotate(arr, 2, 7);        rotate.printArray(arr, 7);    }}// This code has been contributed by Mayank Jaiswal | 
Python3
| # Python3 program to rotate an array by# d elements# Function to left rotate arr[] of size n by ddefleftRotate(arr, d, n):    d =d %n    g_c_d =gcd(d, n)    fori inrange(g_c_d):        # move i-th values of blocks        temp =arr[i]        j =i        while1:            k =j +d            ifk >=n:                k =k -n            ifk ==i:                break            arr[j] =arr[k]            j =k        arr[j] =temp# UTILITY FUNCTIONS# function to print an arraydefprintArray(arr, size):    fori inrange(size):        print("% d"%arr[i], end=" ")# Function to get gcd of a and bdefgcd(a, b):    ifb ==0:        returna    else:        returngcd(b, a %b)# Driver program to test above functionsarr =[1, 2, 3, 4, 5, 6, 7]n =len(arr)d =2leftRotate(arr, d, n)printArray(arr, n)# This code is contributed by Shreyanshi Arun | 
C#
| // C# program for array rotationusingSystem;classGFG {    /* Function to left rotate arr[]    of size n by d*/    staticvoidleftRotate(int[] arr, intd, intn)    {        inti, j, k, temp;        /* To handle if d >= n */        d = d % n;        intg_c_d = gcd(d, n);        for(i = 0; i < g_c_d; i++) {            /* move 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;        }    }    /*UTILITY FUNCTIONS*/    /* Function to print an array */    staticvoidprintArray(int[] arr, intsize)    {        for(inti = 0; i < size; i++)            Console.Write(arr[i] + " ");    }    /* Function to get gcd of a and b*/    staticintgcd(inta, intb)    {        if(b == 0)            returna;        else            returngcd(b, a % b);    }    // Driver code    publicstaticvoidMain()    {        int[] arr = { 1, 2, 3, 4, 5, 6, 7 };        leftRotate(arr, 2, 7);        printArray(arr, 7);    }}// This code is contributed by Sam007 | 
Javascript
| <script>// JavaScript program to rotate an array by// d elements/*Function to get gcd of a and b*/functiongcd( a, b){    if(b == 0)        returna;    else        returngcd(b, a % b);}/*Function to left rotate arr[] of size n by d*/functionleftRotate(arr, d, n){    /* To handle if d >= n */    d = d % n;    let g_c_d = gcd(d, n);    for(let i = 0; i < g_c_d; i++) {        /* move i-th values of blocks */        let temp = arr[i];        let j = i;        while(1) {            let k = j + d;            if(k >= n)                k = k - n;            if(k == i)                break;            arr[j] = arr[k];            j = k;        }        arr[j] = temp;    }}// Function to print an arrayfunctionprintArray(arr, size){    for(let i = 0; i < size; i++)        document.write(arr[i] +" ");}/* Driver program to test above functions */let arr = [ 1, 2, 3, 4, 5, 6, 7 ];let n = arr.length;// Function callingleftRotate(arr, 2, n);printArray(arr, n);</script> | 
3 4 5 6 7 1 2
Time complexity : O(N) 
Auxiliary Space : O(1)
Please see the following posts for other methods of array rotation: 
Block swap algorithm for array rotation 
Reversal algorithm for array rotation
Please write comments if you find any bugs in the above programs/algorithms.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!


 
                                    








