Multiple left rotations of an array (Efficient - JAVA)

Efficient Approach using JAVA programming language:
The above approaches work well when there is a single rotation required. The approaches also modify the original array. To handle multiple queries of array rotation, we use a temp array of size 2n and quickly handle rotations.
Step 1: Copy the entire array two times in temp[0…2n-1] array.
Step 2: Starting position of array after k rotations in temp[] will be k % n. We do k
Step 3: Print temp[] array from k % n to k % n + n.

  • JAVA

// Java implementation of

// left rotation of an

// array K number of times

import java.io.*;

class GFG

{

// Function to left rotate

// an array k times

static void leftRotate( int arr[],

int n, int k)

{

// Print array after

// k rotations

for ( int i = k; i < k + n; i++)

System.out.print(arr[i % n] + " " );

}

// Driver Code

public static void main (String[] args)

{

int arr[] = { 1 , 3 , 5 , 7 , 9 };

int n = arr.length;

int k = 2 ;

leftRotate(arr, n, k);

System.out.println();

k = 3 ;

leftRotate(arr, n, k);

System.out.println();

k = 4 ;

leftRotate(arr, n, k);

System.out.println();

}

}

Output:

5 7 9 1 3 7 9 1 3 5 9 1 3 5 7