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:
- Using temporary array
- Recursively rotating array one by one
- 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
Python
# 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.
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__
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);
}
}
Python
# 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()
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);
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
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);
}
}
Python
# 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
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();
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:
C++
#include <iostream>
using namespace std;
// Main class
class GFG {
public:
// 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 = 0; i < d; i++)
// Recursively calling
rightRotatebyOne(arr, n);
}
// Method 2
// To rotate array by 1
void rightRotatebyOne(int arr[], int n)
{
int temp = arr[n - 1];
for (int i = n - 1; i > 0; i--)
arr[i] = arr[i - 1];
arr[0] = temp;
}
// Method 3
// To print an array
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
};
// Main driver method
int main()
{
// Creating an object of class inside main()
GFG rotate;
// Custom input elements
int arr[] = { 1, 2, 3, 4, 5 };
int d = 2;
int n = sizeof(arr) / sizeof(arr[0]);
// Calling method 1 and 2
rotate.rightRotate(arr, d, n);
rotate.printArray(arr, n);
return 0;
}
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);
}
}
Python
class RotateArray:
# Method 1
# To right rotate array of size n by d
def right_rotate(self, arr, d, n):
# Iterating till we want
for _ in range(n - d):
# Recursively calling right_rotate_by_one
self.right_rotate_by_one(arr, n)
# Method 2
# To rotate array by 1
def right_rotate_by_one(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 print_array(self, arr):
print(' '.join(map(str, arr)))
# Main driver method
@staticmethod
def main():
# Creating an object of class inside main()
rotate = RotateArray()
# Custom input elements
arr = [1, 2, 3, 4, 5]
# Calling method 1 and 2
rotate.right_rotate(arr, 2, len(arr))
rotate.print_array(arr)
# Call the main method to execute the code
RotateArray.main()
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();
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);
}
}
Python
def right_rotate(arr, d, n):
# To use as left rotation
d = n - d
d = d % n
g_c_d = gcd(d, n)
for i in range(g_c_d):
# 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
def print_array(arr):
# Function to print an array
print(" ".join(map(str, arr)))
def gcd(a, b):
# Function to get gcd of a and b
if b == 0:
return a
else:
return gcd(b, a % b)
def main():
# Main driver code
arr = [1, 2, 3, 4, 5]
# Calling functions
right_rotate(arr, 2, len(arr))
print_array(arr)
# Calling the main function
if __name__ == "__main__":
main()
JavaScript
// Function to right rotate arr[] of size n by d
function rightRotate(arr, d, n) {
// To use as left rotation
d = n - d;
d = d % n;
let i, j, k, temp;
let 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;
}
}
// Function to print an array
function printArray(arr) {
console.log(arr.join(" "));
}
// Function to get gcd of a and b
function gcd(a, b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
// Main driver code
function main() {
// Custom input elements
let arr = [1, 2, 3, 4, 5];
// Calling functions
rightRotate(arr, 2, arr.length);
printArray(arr);
}
// Calling the main function
main();
Time complexity: O(n) , Auxiliary Space: O(1)
Similar Reads
Java Program to Print array after it is right rotated K times
Given an Array of size N and a values K, around which we need to right rotate the array. How to quickly print the right rotated array?Examples :Â Â Input: Array[] = {1, 3, 5, 7, 9}, K = 2. Output: 7 9 1 3 5 Explanation: After 1st rotation - {9, 1, 3, 5, 7} After 2nd rotation - {7, 9, 1, 3, 5} Input:
2 min read
Java 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. Java Code import java.util.Arrays; public class Test { static int arr[] = new int[
1 min read
Java Program to Sort an array in wave form
Given an unsorted array of integers, sort the array into a wave-like array. An array 'arr[0..n-1]' is sorted in wave form if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= ..... Examples: Input: arr[] = {10, 5, 6, 3, 2, 20, 100, 80} Output: arr[] = {10, 5, 6, 2, 20, 3, 100, 80} OR
4 min read
Java Program for Left Rotation and Right Rotation of a String
Given a string of size n, write functions to perform the following operations on a string- Left (Or anticlockwise) rotate the given string by d elements (where d <= n)Right (Or clockwise) rotate the given string by d elements (where d <= n). Examples: Input : s = "GeeksforGeeks" d = 2 Output :
6 min read
Java Program for Reversal algorithm for right rotation of an array
Given an array, right rotate it by k elements. After K=3 rotation Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} k = 3 Output: 8 9 10 1 2 3 4 5 6 7 Input: arr[] = {121, 232, 33, 43 ,5} k = 2 Output: 43 5 121 232 33 Note : In the below solution, k is assumed to be smaller than or equal to n
2 min read
Find Mth element after K Right Rotations of an Array
Given non-negative integers K, M, and an array arr[ ] consisting of N elements, the task is to find the Mth element of the array after K right rotations. Examples: Input: arr[] = {3, 4, 5, 23}, K = 2, M = 1 Output: 5 Explanation: The array after first right rotation a1[ ] = {23, 3, 4, 5} The array a
11 min read
Java Program to Find the Mth element of the Array after K left rotations
Given non-negative integers K, M, and an array arr[] with N elements find the Mth element of the array after K left rotations. Examples: Input: arr[] = {3, 4, 5, 23}, K = 2, M = 1Output: 5Explanation:Â The array after first left rotation a1[ ] = {4, 5, 23, 3}The array after second left rotation a2[ ]
3 min read
Java Program to Sort 2D Array Across Left Diagonal
The Vector class implements a growable array of objects. Vectors basically fall in legacy classes but now it is fully compatible with collections. It is found in java.util package and implements the List interface, so we can use all the methods of List interface here. This program is used to Sort th
3 min read
Java Program to Print matrix in antispiral form
Given a 2D array, the task is to print matrix in anti spiral form:Examples: Output: 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 Input : arr[][4] = {1, 2, 3, 4 5, 6, 7, 8 9, 10, 11, 12 13, 14, 15, 16}; Output : 10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1 Input :arr[][6] = {1, 2, 3, 4, 5, 6 7, 8, 9, 10, 11, 12
3 min read
Java Program to Print all possible rotations of a given Array
Given an integer array arr[] of size N, the task is to print all possible rotations of the array.Examples: Input: arr[] = {1, 2, 3, 4} Output: {1, 2, 3, 4}, {4, 1, 2, 3}, {3, 4, 1, 2}, {2, 3, 4, 1} Explanation: Initial arr[] = {1, 2, 3, 4} After first rotation arr[] = {4, 1, 2, 3} After second rotat
3 min read