The Wayback Machine - https://web.archive.org/web/20240818172445/https://www.geeksforgeeks.org/complete-guide-on-array-rotations/
Open In App

Rotate an Array – Data Structure and Algorithms Tutorial

Last Updated : 17 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Rotations in the array is defined as the process of rearranging the elements in an array by shifting each element to a new position. This is mostly done by rotating the elements of the array clockwise or counterclockwise.

Types of Rotations in Array:

1. Right Rotation (or Clockwise)

Here, The array elements are shifted towards the right. 

Rotating array elements towards right by 2 places

2. Left Rotation (Or Counter Clockwise)

Here, The array elements are shifted towards the left.

Rotating array elements towards left by 2 places

How to implement rotations in an Array?

There are several ways to implement array rotations. Some of the approaches are mentioned below.

1:  Rotate one by one

Here we are considering left rotation. The movements will be just the opposite for right rotation.

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], d = 2.

First Step:
        => Rotate to left by one position.
        => arr[] = {2, 3, 4, 5, 6, 1}
Second Step:
        => Rotate again to left by one position
        => arr[] = {3, 4, 5, 6, 1, 2}
Rotation is done 2 times.
So the array becomes arr[] = {3, 4, 5, 6, 1, 2}

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

/*Function to left rotate arr by d positions*/
void rotate(vector<int>& arr, int d)
{
    int n = arr.size();
  
    for (int count = 0; count < d; count++) {
      
        // Rotate by one
        int first = arr[0];
        for (int i = 0; i < n - 1; i++) {
            arr[i] = arr[i + 1];
        }
        arr[n - 1] = first;      
    }
}

// Driver's code
int main()
{
    vector<int> arr = { 1, 2, 3, 4, 5, 6 };
    int d = 2;

    rotate(arr, d);

    // Print the modified array
    for (int val : arr)
        cout << val << " ";

    return 0;
}
C
#include <stdio.h>

/* Function to left rotate arr by d positions */
void rotate(int arr[], int d, int n)
{
    for (int count = 0; count < d; count++) {
      
        // Rotate by one
        int first = arr[0];
        for (int i = 0; i < n - 1; i++) {
            arr[i] = arr[i + 1];
        }
        arr[n - 1] = first;      
    }
}

// Driver's code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int d = 2;

    rotate(arr, d, n);

    // Print the modified array
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);

    return 0;
}
Java
import java.util.Arrays;

public class GfG {

    /* Function to left rotate arr by d positions */
    static void rotate(int[] arr, int d) {
        int n = arr.length;
        
        for (int count = 0; count < d; count++) {
          
            // Rotate by one
            int first = arr[0];
            for (int i = 0; i < n - 1; i++) {
                arr[i] = arr[i + 1];
            }
            arr[n - 1] = first;      
        }
    }

    // Driver's code
    public static void main(String[] args) {
        int[] arr = { 1, 2, 3, 4, 5, 6 };
        int d = 2;

        rotate(arr, d);

        // Print the modified array
        System.out.println(Arrays.toString(arr));
    }
}
Python
def rotate(arr, d):
    n = len(arr)
    
    for count in range(d):
      
        # Rotate by one
        first = arr[0]
        for i in range(n - 1):
            arr[i] = arr[i + 1]
        arr[n - 1] = first

# Driver's code
if __name__ == "__main__":
    arr = [1, 2, 3, 4, 5, 6]
    d = 2

    rotate(arr, d)

    # Print the modified array
    print(arr)
C#
using System;

class GfG {

    /* Function to left rotate arr by d positions */
    static void Rotate(int[] arr, int d) {
        int n = arr.Length;
        
        for (int count = 0; count < d; count++) {
          
            // Rotate by one
            int first = arr[0];
            for (int i = 0; i < n - 1; i++) {
                arr[i] = arr[i + 1];
            }
            arr[n - 1] = first;      
        }
    }

    // Driver's code
    static void Main() {
        int[] arr = { 1, 2, 3, 4, 5, 6 };
        int d = 2;

        Rotate(arr, d);

        // Print the modified array
        Console.WriteLine(string.Join(" ", arr));
    }
}
JavaScript
// Function to left rotate arr by d positions
function rotate(arr, d) {
    const n = arr.length;
    
    for (let count = 0; count < d; count++) {
        
        // Rotate by one
        const first = arr[0];
        for (let i = 0; i < n - 1; i++) {
            arr[i] = arr[i + 1];
        }
        arr[n - 1] = first;
    }
}

// Driver's code
const arr = [1, 2, 3, 4, 5, 6];
const d = 2;

rotate(arr, d);

// Print the modified array
console.log(arr);

Output
3 4 5 6 1 2 

Time Complexity: O(N * d)
Auxiliary Space: O(1)

2. Using temporary Array:

We create a temporary array of size n, where n is the length of the original array. If we rotate the array by d positions to right, the last d elements will be in the front. So, copy the last d elements of the original array into the first d positions of the temporary array and copy the remaining elements in the remaining positions. Finally, copy the elements of the temporary array back into the original array starting at position 0.

Illustration:

  • Initialize an empty temp array, to store the final rotated state of the original array.
Example of array

Example of array

  • Copy all elements from (n-d) to the end of the original to the front of the temp array.
Copy last 'd' elements to the front in temp[]

Copy last ‘d’ elements to the front in temp[]

  • Now copy the rest elements from the front to the back of the temp[].
Copy the remaining elements to the end

Copy the remaining elements to the end

Below are the steps to solve using the above approach:

  • Initializing a temporary array (temp[n]) of length same as the original array.
  • Initialize ( j ) to keep track of the current index.
  • Store elements from position d to n-1 in the temp array.
  • Now, store 0 to d-1 in the temp array from the original array.
  • Lastly, copy back temp[] to the original as the final output.

Below is the implementation of the above approach

C++
#include <bits/stdc++.h>
using namespace std;

// Function to rotate vector
void rotate(vector<int>& arr, int d)
{
    int n = arr.size();

    // Storing rotated version of vector
    vector<int> temp(n);

    // Keeping track of the current index
    // of temp
    int j = 0;

    // Storing the n - d elements of
    // vector arr to the front of temp
    for (int i = d; i < n; i++) {
        temp[j] = arr[i];
        j++;
    }

    // Storing the first d elements of vector arr
    // into temp
    for (int i = 0; i < d; i++) {
        temp[j] = arr[i];
        j++;
    }

    // Copying the elements of temp in arr
    // to get the final rotated vector
    for (int i = 0; i < n; i++) {
        arr[i] = temp[i];
    }
}

// Driver's code
int main()
{
    vector<int> arr = { 1, 2, 3, 4, 5, 6 };
    int d = 2;

    // Function calling
    rotate(arr, d);

    // Print the rotated vector
    for (int val : arr) {
        cout << val << " ";
    }

    return 0;
}
C
#include <stdio.h>

// Function to rotate array
void rotate(int arr[], int d, int n)
{
    // Storing rotated version of array
    int temp[n];

    // Keeping track of the current index
    // of temp[]
    int j = 0;

    // Storing the n - d elements of
    // array arr[] to the front of temp[]
    for (int i = d; i < n; i++) {
        temp[j] = arr[i];
        j++;
    }

    // Storing the first d elements of array arr[]
    // into temp
    for (int i = 0; i < d; i++) {
        temp[j] = arr[i];
        j++;
    }

    // Copying the elements of temp[] in arr[]
    // to get the final rotated array
    for (int i = 0; i < n; i++) {
        arr[i] = temp[i];
    }
}

// Function to print elements of array
void printTheArray(int arr[], int n)
{
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
}

// Driver's code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int d = 2;

    // Function calling
    rotate(arr, d, N);
    printTheArray(arr, N);

    return 0;
}
Java
// Java code to implement the above approach
import java.io.*;

class GFG {

    // Function to rotate array
    static void rotate(int arr[], int d, int n)
    {
        // Storing rotated version of array
        int temp[] = new int[n];

        // Keeping track of the current index
        // of temp[]
        int j = 0;

        // Storing the n - d elements of
        // array arr[] to the front of temp[]
        for (int i = d; i < n; i++) {
            temp[j] = arr[i];
            j++;
        }

        // Storing the first d elements of array arr[]
        // into temp
        for (int i = 0; i < d; i++) {
            temp[j] = arr[i];
            j++;
        }

        // Copying the elements of temp[] in arr[]
        // to get the final rotated array
        for (int i = 0; i < n; i++) {
            arr[i] = temp[i];
        }
    }

    // Function to print elements of array
    static void printTheArray(int arr[], int n)
    {
        for (int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
    }
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 3, 4, 5, 6 };
        int N = arr.length;
        int d = 2;

        // Function calling
        rotate(arr, d, N);
        printTheArray(arr, N);
    }
}
Python
# Python code to implement the above approach
def rotate(L, d, n):
    new_lis = []
    new_lis =  L[d:]+L[0:d] 
    return new_lis


if __name__ == '__main__':
    arr = [1, 7, 3, 4, 5, 6]
    d = 2
    N = len(arr)

    # Function call
    arr = rotate(arr, d, N)
    for i in arr:
        print(i, end=" ")
C#
// C# code for the approach

using System;

class GFG {
      // Driver code
    static void Main(string[] args)
    {
          // Input array
        int[] arr = { 1, 2, 3, 4, 5, 6 };
        int N = arr.Length;
        int d = 2;
      
        // Storing rotated version of array
        int[] temp = new int[N];

        // Keeping track of the current index
        // of temp[]
        int j = 0;

        // Storing the n - d elements of
        // array arr[] to the front of temp[]
        for (int i = d; i < N; i++) {
            temp[j] = arr[i];
            j++;
        }

        // Storing the first d elements of array arr[]
        // into temp
        for (int i = 0; i < d; i++) {
            temp[j] = arr[i];
            j++;
        }

        // Copying the elements of temp[] in arr[]
        // to get the final rotated array
        for (int i = 0; i < N; i++) {
            arr[i] = temp[i];
        }

        // Function to print elements of array
        foreach(int element in arr)
        {
            Console.Write(element + " ");
        }
    }
}
JavaScript
function rotateArray(arr, d, n) {
// Storing rotated version of array
let temp = [];

// Keeping track of the current index
// of temp[]
let j = 0;

// Storing the n - d elements of
// array arr[] to the front of temp[]
for (let i = d; i < n; i++) {
temp[j] = arr[i];
j++;
}

// Storing the first d elements of array arr[]
// into temp
for (let i = 0; i < d; i++) {
temp[j] = arr[i];
j++;
}

// Copying the elements of temp[] in arr[]
// to get the final rotated array
for (let i = 0; i < n; i++) {
arr[i] = temp[i];
}
}

// Function to print elements of array
function printArray(arr) {
console.log(arr.join(' '));
}

// Driver's code
let arr = [1, 2, 3, 4, 5, 6];
let N = arr.length;
let d = 2;

// Function calling
rotateArray(arr, d, N);
printArray(arr);

Output
3 4 5 6 1 2 

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

3:  Juggling Algorithm

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.

Juggling Algorithm

Juggling Algorithm

Illustration:

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}

Below are the steps to solve using the above approach: 

  • 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++
#include <bits/stdc++.h>
using namespace std;

/*Function to get gcd of a and b*/
int gcd(int a, int b)
{
    return (b == 0)? a : gcd(b, a % b);
}

/*Function to left rotate arr of size n by d*/
void leftRotate(vector<int>& arr, int d)
{
    int n = arr.size();

    /* To handle if d >= n */
    d = d % n;
    int g_c_d = gcd(d, n);
    for (int i = 0; i < g_c_d; i++) {
        /* move i-th values of blocks */
        int temp = arr[i];
        int j = i;

        while (1) {
            int k = j + d;
            if (k >= n)
                k = k - n;

            if (k == i)
                break;

            arr[j] = arr[k];
            j = k;
        }
        arr[j] = temp;
    }
}

// Driver's code
int main()
{
    vector<int> arr = { 1, 2, 3, 4, 5, 6 };
    int d = 2;
    
    // Function calling
    leftRotate(arr, d);

    // Print the vector
    for (int val : arr)
        cout << val << " ";

    return 0;
}
C
#include <stdio.h>

/* Function to get gcd of a and b using a ternary operator */
int gcd(int a, int b) {
    return (b == 0) ? a : gcd(b, a % b);
}

/* Function 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 g_c_d = gcd(d, n);
    for (int i = 0; i < g_c_d; i++) {
        /* move i-th values of blocks */
        int temp = arr[i];
        int j = i;

        while (1) {
            int 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 array */
void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++)
        printf("%d ", arr[i]);
}

/* Driver's code */
int main() {
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int d = 2;

    // Function calling
    leftRotate(arr, d, n);
    printArray(arr, n);

    return 0;
}
Java
// Java program to implement the above approach
import java.io.*;

class RotateArray {
    /*Function to left rotate arr[] of siz 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;
            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 */
    void printArray(int arr[], int size)
    {
        int i;
        for (i = 0; i < size; i++)
            System.out.print(arr[i] + " ");
    }

    /*Function to get gcd of a and b*/
    int gcd(int a, int b)
    {
        if (b == 0)
            return a;
        else
            return gcd(b, a % b);
    }

    // Driver's code
    public static void main(String[] args)
    {
        RotateArray rotate = new RotateArray();
        int arr[] = { 1, 2, 3, 4, 5, 6 };
        int n = 6;
        int d = 2;
        rotate.leftRotate(arr, d, n);
        rotate.printArray(arr, n);
    }
}
Python
# Python code to implement the above approach


# Function to rotate the array left by d positions
def leftRotate(arr, d, n):
    d = d % n
    g_c_d = gcd(d, n)
    for i in range(g_c_d):

        # 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


# function to print an array
def printArray(arr, size):
    for i in range(size):
        print(arr[i], end=" ")


# Function to get gcd of a and b
def gcd(a, b):
    if b == 0:
        return a
    else:
        return gcd(b, a % b)


# Driver code
if __name__ == '__main__':
    arr = [1, 2, 3, 4, 5, 6]
    n = len(arr)
    d = 2
    leftRotate(arr, d, n)
    printArray(arr, n)
C#
using System;

namespace LeftRotation
{
  class Program
  {
    // Function to get gcd of a and b
    static int gcd(int a, int b)
    {
      if (b == 0)
        return a;
      else
        return gcd(b, a % b);
    }

    // Function to left rotate arr[] of size n by d
    static void leftRotate(int[] arr, int d, int n)
    {
      // To handle if d >= n
      d = d % n;
      int g_c_d = gcd(d, n);
      for (int i = 0; i < g_c_d; i++)
      {
        // move i-th values of blocks
        int temp = arr[i];
        int j = i;

        while (true)
        {
          int 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 array
    static void printArray(int[] arr, int size)
    {
      for (int i = 0; i < size; i++)
        Console.Write(arr[i] + " ");
    }

    // Driver's code
    static public void Main(string[] args)
    {
      int[] arr = { 1, 2, 3, 4, 5, 6 };
      int n = arr.Length;
      int d = 2;
      // Function calling
      leftRotate(arr, d, n);
      printArray(arr, n);
    }
  }
}
JavaScript
// Function to left rotate arr[] of size n by d
function leftRotate(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 gcd(a, b)
{
    if (b == 0) {
        return a;
    }
    else {
        return gcd(b, a % b);
    }
}

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

// Driver's code
let arr = [ 1, 2, 3, 4, 5, 6 ];
let n = arr.length;
let d = 2;

// Function calling
leftRotate(arr, d, n);
printArray(arr);

Output
3 4 5 6 1 2 

Time complexity : O(N) 
Auxiliary Space : O(1)

4. The Reversal Algorithm

  • Reverse the first ‘d’ elements
  • Reverse last (N-d) elements
  • Reverse the whole array.

Illustration:

Take the original array as it is.

Example of Array

Example of Array

  • Separate it out into first ‘d’ elements and ‘n-d’ elements.
Separate array into first 'd' and (n-d) segment

Separate array into first ‘d’ and (n-d) segment

  • Reverse first ‘d’ elements.
Reverse the first 'd' elements

Reverse the first ‘d’ elements

  • Reverse the next ‘n-d’ elements.
Reverse the next (n-d) elements

Reverse the next (n-d) elements

  • Next, reverse the whole array. We have the final array rotated by d elements to left.
Reverse the whole array

Reverse the whole array

Below is the implementation of the above approach:

C++
// C++ code to implement the above approach
#include <bits/stdc++.h>

using namespace std;

// Function to rotate an array by k elements to the left
void rotateArray(vector<int>& arr, int d)
{
    // Find the size of the array
    int n = arr.size();

    // Mod k with the size of the array
    // To handle the case where d is greater
    //  than the size of the array
    d %= n;

    // Reverse the first k elements
    reverse(arr.begin(), arr.begin() + d);

    // Reverse the remaining n-k elements
    reverse(arr.begin() + d, arr.end());

    // Reverse the entire array
    reverse(arr.begin(), arr.end());
}

int main()
{
    vector<int> arr = { 1, 2, 3, 4, 5, 6 };
    int d = 2;
    rotateArray(arr, d);
    for (int i : arr) {
        cout << i << " ";
    }
    return 0;
}
C
#include <stdio.h>

/* Function to reverse a portion of the array */
void reverse(int arr[], int start, int end) {
    while (start < end) {
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}

/* Function to rotate an array by d elements to the left */
void rotateArray(int arr[], int d, int n) {
    // Mod d with the size of the array
    // To handle the case where d is greater than the size of the array
    d %= n;

    // Reverse the first d elements
    reverse(arr, 0, d - 1);

    // Reverse the remaining n-d elements
    reverse(arr, d, n - 1);

    // Reverse the entire array
    reverse(arr, 0, n - 1);
}

int main() {
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int d = 2;
    
    rotateArray(arr, d, n);

    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    
    return 0;
}
Java
// Java program to implement the above approach
import java.io.*;

class LeftRotate {
    /* Function to left rotate arr[] of size n by d */
    static void leftRotate(int arr[], int d)
    {

        if (d == 0)
            return;

        int n = arr.length;
        // in case the rotating factor is
        // greater than array length
        d = d % n;
        reverseArray(arr, 0, d - 1);
        reverseArray(arr, d, n - 1);
        reverseArray(arr, 0, n - 1);
    }

    /*Function to reverse arr[] from index start to end*/
    static void reverseArray(int arr[], int start, int end)
    {
        int temp;
        while (start < end) {
            temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            start++;
            end--;
        }
    }

    /*UTILITY FUNCTIONS*/
    /* function to print an array */
    static void printArray(int arr[])
    {
        for (int i = 0; i < arr.length; i++)
            System.out.print(arr[i] + " ");
    }

    /* Driver program to test above functions */
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 3, 4, 5, 6 };
        int n = arr.length;
        int d = 2;

        leftRotate(arr, d); // Rotate array by d
        printArray(arr);
    }
}
Python
# Python code to implement the above approach


# Function to reverse start to end of array
def reverseArray(arr, start, end):
    while (start < end):
        temp = arr[start]
        arr[start] = arr[end]
        arr[end] = temp
        start += 1
        end = end-1


# Function to left rotate arr[] of size n by d
def leftRotate(arr, d):

    if d == 0:
        return
    n = len(arr)
    # in case the rotating factor is
    # greater than array length
    d = d % n
    reverseArray(arr, 0, d-1)
    reverseArray(arr, d, n-1)
    reverseArray(arr, 0, n-1)


# Function to print an array
def printArray(arr):
    for i in range(0, len(arr)):
        print(arr[i], end=' ')


# Driver code
if __name__ == '__main__':
    arr = [1, 2, 3, 4, 5, 6]
    n = len(arr)
    d = 2
    leftRotate(arr, d)
    printArray(arr)
C#
// C# program to implement the above approach
using System;

class LeftRotate {
    /* Function to left rotate arr[] of size n by d */
    static void leftRotate(int[] arr, int d)
    {

        if (d == 0)
            return;

        int n = arr.Length;
        // in case the rotating factor is
        // greater than array length
        d = d % n;
        reverseArray(arr, 0, d - 1);
        reverseArray(arr, d, n - 1);
        reverseArray(arr, 0, n - 1);
    }

    /*Function to reverse arr[] from index start to end*/
    static void reverseArray(int[] arr, int start, int end)
    {
        int temp;
        while (start < end) {
            temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            start++;
            end--;
        }
    }

    /*UTILITY FUNCTIONS*/
    /* function to print an array */
    static void printArray(int[] arr)
    {
        for (int i = 0; i < arr.Length; i++)
            Console.Write(arr[i] + " ");
    }

    /* Driver program to test above functions */
    public static void Main()
    {
        int[] arr = { 1, 2, 3, 4, 5, 6 };
        int n = arr.Length;
        int d = 2;

        leftRotate(arr, d); // Rotate array by d
        printArray(arr);
    }
}


// This code is contributed by Vaibhav Nandan
JavaScript
 /*Function to reverse arr[] from index start to end*/
      function reverseArray(arr, s, e) {
        while (s < e) {
          var temp = arr[s];
          arr[s] = arr[e];
          arr[e] = temp;
          s++;
          e--;
        }
      }
 
      /* Function to left rotate arr[] of size n by d */
      function leftRotate(arr, d, n) {
        if (d == 0) return;
        // in case the rotating factor is
        // greater than array length
        d = d % n;
 
        reverseArray(arr, 0, d - 1);
        reverseArray(arr, d, n - 1);
        reverseArray(arr, 0, n - 1);
      }
 
      // Function to print an array
      function printArray(arr, size)
      {
        console.log(arr.join(' '));
      }
 
      /* Driver program to test above functions */
 
      var arr = [1, 2, 3, 4, 5, 6, 7];
      var n = arr.length;
      var d = 2;
 
      // Function calling
      leftRotate(arr, d, n);
      printArray(arr, n);

Output
3 4 5 6 1 2 

Time Complexity: O(N)
Auxiliary Space: O(1)

Some FAQs regarding Array Rotation:

1. Can Array Rotation be used to implement any data structures?

It can be used to implement several data structures such as circular buffers and circular queues. In a circular buffer, array rotation is used to move the read and write pointers around the buffer, while in a circular queue, array rotation is used to remove the oldest element and add the newest element.

2. Is Array Rotation in place or takes extra space?

Array rotation can be performed in place, which means that the original array is modified directly without using any additional memory. This can be useful in situations where memory usage is a concern.

3. Is there any relation between modular-arithmetic and array rotation?

Array rotation is closely related to the concept of modular arithmetic, which is used to perform arithmetic operations on integers that are defined modulo a given number. In the case of array rotation, the modulo operation is used to calculate the new position of each element in the array after rotation.

Some other Important Problems/Articles on the same



Similar Reads

Static Data Structure vs Dynamic Data Structure
Data structure is a way of storing and organizing data efficiently such that the required operations on them can be performed be efficient with respect to time as well as memory. Simply, Data Structure are used to reduce complexity (mostly the time complexity) of the code. Data structures can be two types : 1. Static Data Structure 2. Dynamic Data
4 min read
Top 100 Data Structure and Algorithms DSA Interview Questions Topic-wise
DSA has been one of the most popular go-to topics for any interview, be it college placements, software developer roles, or any other technical roles for freshers and experienced to land a decent job. If you are among them, you already know that it is not easy to find the best DSA interview questions among the vast pool of available problems. So he
4 min read
Maths for Data Structure and Algorithms (DSA) | A Complete Guide
Maths is a fundamental component of learning Data Structure and Algorithms, just like in programming. Maths is primarily used to evaluate the effectiveness of different algorithms. However, there are situations when the answer requires some mathematical understanding or the problem has mathematical characteristics and certain problems demand more t
15+ min read
Graph Data Structure And Algorithms
Graph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. Graph algorithms are methods used to manipulate and analyze graphs, solving various problems like finding the shortest path or detecting cycles. Table of Content What is Graph Data Structure?Components of a GraphBasic O
7 min read
Top 12 Data Structure Algorithms to Implement in Practical Applications in 2021
New Year...New Beginning...!!! What's your plan for this year??? (Being a programmer) Of course, if you're a programmer then this year you will also write the code, build the projects and you will solve a lot of coding questions. Let's talk about Data Structures and Algorithms... Heart of computer science and the programmer's breath to live in the
14 min read
Is array a Data Type or Data Structure?
What is Data Type? In computer programming, a data type is a classification of data that determines the type of values that can be stored, manipulated, and processed. It tells the computer what kind of data a particular variable or constant can hold, and what operations can be performed on that data. Common data types include integers, floating-poi
8 min read
Python3 Program to Rotate all odd numbers right and all even numbers left in an Array of 1 to N
Given a permutation arrays A[] consisting of N numbers in range [1, N], the task is to left rotate all the even numbers and right rotate all the odd numbers of the permutation and print the updated permutation. Note: N is always even.Examples:  Input: A = {1, 2, 3, 4, 5, 6, 7, 8} Output: {7, 4, 1, 6, 3, 8, 5, 2} Explanation: Even element = {2, 4, 6
2 min read
Javascript Program to Rotate all odd numbers right and all even numbers left in an Array of 1 to N
Given a permutation arrays A[] consisting of N numbers in range [1, N], the task is to left rotate all the even numbers and right rotate all the odd numbers of the permutation and print the updated permutation. Note: N is always even.Examples:  Input: A = {1, 2, 3, 4, 5, 6, 7, 8} Output: {7, 4, 1, 6, 3, 8, 5, 2} Explanation: Even element = {2, 4, 6
2 min read
Right rotate given Array K times using Pointers
Given an array arr[] of size N and an integer K, the task is to right rotate the array K times. Examples: Input: arr[] = {1, 3, 5, 7, 9}, K = 2Output: 7 9 1 3 5Explanation: After 1st rotation - {9, 1, 3, 5, 7}After 2nd rotation - {7, 9, 1, 3, 5} Input: {1, 2, 3, 4, 5, 6}, K = 2Output: 5 6 1 2 3 4 Approach: The naive approach and approach based on r
6 min read
Javascript Program for Program to cyclically rotate an array by one
Given an array, cyclically rotate the array clockwise by one. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: arr[] = {5, 1, 2, 3, 4}Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Following are steps. 1) Store last element in a variable say x. 2) Shift all elements one position ahead. 3) Replace first element o
2 min read
Program to cyclically rotate an array by one
Given an array, the task is to cyclically rotate the array clockwise by one time. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: arr[] = {5, 1, 2, 3, 4} Input: arr[] = {2, 3, 4, 5, 1}Output: {1, 2, 3, 4, 5} Recommended ProblemCyclically rotate an array by oneSolve Problem Assign every element with its previous element and first element with the l
13 min read
Rotate an array by d positions
Given an array of integers arr[] of size N and an integer d, the task is to rotate the array elements to the left by d positions. Examples:   Input:  d = 2 , arr[] = {1, 2, 3, 4, 5, 6, 7}Output: 3 4 5 6 7 1 2 Input:  d = 4, arr[] = {3, 4, 5},Output: 4 5 3Rotating an array 4 times is effectively same as rotating it 4 - 3 = 1 time. Table of Content A
15+ min read
Data Structure Alignment : How data is arranged and accessed in Computer Memory?
Data structure alignment is the way data is arranged and accessed in computer memory. Data alignment and Data structure padding are two different issues but are related to each other and together known as Data Structure alignment. Data alignment: Data alignment means putting the data in memory at an address equal to some multiple of the word size.
4 min read
Difference between data type and data structure
Data Type A data type is the most basic and the most common classification of data. It is this through which the compiler gets to know the form or the type of information that will be used throughout the code. So basically data type is a type of information transmitted between the programmer and the compiler where the programmer informs the compile
4 min read
Does a Data Scientist/Machine Learning Engineer require in depth knowledge of Data Structures and Algorithms?
In today's world, data scientists and machine learning engineers play a crucial role in analyzing data and building intelligent systems. As technology continues to advance, the demand for these experts is growing rapidly. Real-world data problems are complex, requiring strong skills in handling data and creating efficient algorithms. In this articl
10 min read
Greedy Algorithms (General Structure and Applications)
The general structure of a greedy algorithm can be summarized in the following steps:Identify the problem as an optimization problem where we need to find the best solution among a set of possible solutions.Determine the set of feasible solutions for the problem.Identify the optimal substructure of the problem, meaning that the optimal solution to
9 min read
Differences between Array and Dictionary Data Structure
Arrays:The array is a collection of the same type of elements at contiguous memory locations under the same name. It is easier to access the element in the case of an array. The size is the key issue in the case of an array which must be known in advance so as to store the elements in it. Insertion and deletion operations are costly in the case of
5 min read
Rotate a Matrix by 180 degree
Given a square matrix, the task is that we turn it by 180 degrees in an anti-clockwise direction without using any extra space. Examples : Input : 1 2 3 4 5 6 7 8 9 Output : 9 8 7 6 5 4 3 2 1 Input : 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 Output : 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 Method: 1 (Only prints rotated matrix) The solution of this problem is that t
15+ min read
Javascript Program for Rotate the matrix right by K times
Given a matrix of size N*M, and a number K. We have to rotate the matrix K times to the right side. Examples: Input : N = 3, M = 3, K = 2 12 23 34 45 56 67 78 89 91 Output : 23 34 12 56 67 45 89 91 78 Input : N = 2, M = 2, K = 2 1 2 3 4 Output : 1 2 3 4 A simple yet effective approach is to consider each row of the matrix as an array and perform an
2 min read
String slicing in Python to Rotate a String
Given a string of size n, write functions to perform following operations on string. Left (Or anticlockwise) rotate the given string by d elements (where d &lt;= n).Right (Or clockwise) rotate the given string by d elements (where d &lt;= n).Examples: Input : s = "GeeksforGeeks" d = 2Output : Left Rotation : "eksforGeeksGe" Right Rotation : "ksGeek
3 min read
Rotate the matrix right by K times
Given a matrix of size N*M, and a number K. We have to rotate the matrix K times to the right side. Examples: Input : N = 3, M = 3, K = 2 12 23 34 45 56 67 78 89 91 Output : 23 34 12 56 67 45 89 91 78 Input : N = 2, M = 2, K = 2 1 2 3 4 Output : 1 2 3 4 A simple yet effective approach is to consider each row of the matrix as an array and perform an
9 min read
Rotate a matrix by 90 degree in clockwise direction without using any extra space
Given a square matrix, turn it by 90 degrees in a clockwise direction without using any extra space. Examples: Input: 1 2 3 4 5 6 7 8 9 Output: 7 4 1 8 5 2 9 6 3 Input: 1 2 3 4 Output: 3 1 4 2 Method 1 Approach: The approach is similar to Inplace rotate square matrix by 90 degrees | Set 1. The only thing that is different is to print the elements o
15+ min read
Rotate the sub-list of a linked list from position M to N to the right by K places
Given a linked list and two positions 'm' and 'n'. The task is to rotate the sublist from position m to n, to the right by k places.Examples: Input: list = 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6, m = 2, n = 5, k = 2 Output: 1-&gt;4-&gt;5-&gt;2-&gt;3-&gt;6 Rotate the sublist 2 3 4 5 towards right 2 times then the modified list are: 1 4 5 2 3 6 Input: list
13 min read
Python | Ways to rotate a list
The rotation of a list has been discussed earlier also, but this particular article focuses on shorthands and various short techniques to achieve this in one-liners or one word. This operation is quite essential in a programmer's life to achieve various tasks. Let's discuss different ways we can rotate a list in Python. Method 1: Rotate a list usin
8 min read
Javascript Program for Rotate Doubly linked list by N nodes
Given a doubly linked list, rotate the linked list counter-clockwise by N nodes. Here N is a given positive integer and is smaller than the count of nodes in linked list. N = 2Rotated List: Examples: Input : a b c d e N = 2 Output : c d e a b Input : a b c d e f g h N = 4 Output : e f g h a b c d Asked in Amazon To rotate the Doubly linked list, we
4 min read
Python3 Program to Rotate the matrix right by K times
Given a matrix of size N*M, and a number K. We have to rotate the matrix K times to the right side. Examples: Input : N = 3, M = 3, K = 2 12 23 34 45 56 67 78 89 91 Output : 23 34 12 56 67 45 89 91 78 Input : N = 2, M = 2, K = 2 1 2 3 4 Output : 1 2 3 4 A simple yet effective approach is to consider each row of the matrix as an array and perform an
2 min read
Rotate matrix by 45 degrees
Given a matrix mat[][] of size N*N, the task is to rotate the matrix by 45 degrees and print the matrix. Examples: Input: N = 6, mat[][] = {{3, 4, 5, 1, 5, 9, 5}, {6, 9, 8, 7, 2, 5, 2}, {1, 5, 9, 7, 5, 3, 2}, {4, 7, 8, 9, 3, 5, 2}, {4, 5, 2, 9, 5, 6, 2}, {4, 5, 7, 2, 9, 8, 3}}Output: 3 6 4 1 9 5 4 5 8 1 4 7 9 7 54 5 8 7 2 9 5 2 9 5 5 7 9 3 3 2 5 5
15+ min read
Rotate-matrix module in Python
The rotate-matrix is an interesting new python module, which allows conversion of a matrix(2-D array) into either clockwise rotation or anti-clockwise rotation. It at present consists of only two methods. You can loop through these methods for 'n' number of rotations. Installation This module doesn't come in-built with python but can be installed u
1 min read
Left rotate digits of node values of all levels of a Binary Tree in increasing order
Given a Binary Tree, the task is to modify the Tree by left rotating every node any number of times such that every level consists of node values in increasing order from left to right. If it is not possible to arrange node values of any level in increasing order, then print "-1". Examples: Input: 341 / \ 241 123 / \ \ 324 235 161Output: 341 / \ 12
14 min read
Rotate all Matrix elements except the diagonal K times by 90 degrees in clockwise direction
Given a square matrix mat[][] of dimension N and an integer K, the task is to rotate the matrix by 90 degrees K times without changing the position of the diagonal elements. Examples: Input: mat[][] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25}}, K = 1Output: 1 16 11 6 5 22 7 12 9 2 23 18 13
10 min read
Practice Tags :
three90RightbarBannerImg