Quickly find multiple left rotations of an array | Set 1
Last Updated :
19 Sep, 2023
Given an array of size n and multiple values around which we need to left rotate the array. How to quickly find multiple left rotations?
Examples:
Input: arr[] = {1, 3, 5, 7, 9}
k1 = 1
k2 = 3
k3 = 4
k4 = 6
Output: 3 5 7 9 1
7 9 1 3 5
9 1 3 5 7
3 5 7 9 1
Input: arr[] = {1, 3, 5, 7, 9}
k1 = 14
Output: 9 1 3 5 7
Simple Approach: We have already discussed different approaches given in the below posts.
- Left Rotation of array (Simple and Juggling Algorithms).
- Block swap algorithm for array rotation
- Reversal algorithm for array rotation
The best of the above approaches take O(n) time and O(1) extra space.
Simple Approach: We are using the reverse algorithm but this time for multiple k values - you can click on the above link to understand this approach.
Implementation:
C++
// C++ program for the above approach
#include <iostream>
using namespace std;
int* rotateArray(int A[], int start, int end)
{
while (start < end) {
int temp = A[start];
A[start] = A[end];
A[end] = temp;
start++;
end--;
}
return A;
}
void leftRotate(int A[], int a, int k)
{
// if the value of k ever exceeds the length of the
// array
int c = k % a;
// initializing array D so that we always
// have a clone of the original array to rotate
int D[a];
for (int i = 0; i < a; i++)
D[i] = A[i];
rotateArray(D, 0, c - 1);
rotateArray(D, c, a - 1);
rotateArray(D, 0, a - 1);
// printing the rotated array
for (int i = 0; i < a; i++)
cout << D[i] << " ";
cout << "\n";
}
int main()
{
int A[] = { 1, 3, 5, 7, 9 };
int n = sizeof(A) / sizeof(A[0]);
int k = 2;
leftRotate(A, n, k);
k = 3;
leftRotate(A, n, k);
k = 4;
leftRotate(A, n, k);
return 0;
}
// this code is contributed by aditya942003patil
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.Arrays;
class GFG {
public static void leftRotate(int[] A, int a, int k)
{
// if the value of k ever exceeds the length of the
// array
int c = k % a;
// initializing array D so that we always
// have a clone of the original array to rotate
int[] D = A.clone();
rotateArray(D, 0, c - 1);
rotateArray(D, c, a - 1);
rotateArray(D, 0, a - 1);
// printing the rotated array
System.out.print(Arrays.toString(D));
System.out.println();
}
// Function to rotate the array from start index to end
// index
public static int[] rotateArray(int[] A, int start,
int end)
{
while (start < end) {
int temp = A[start];
A[start] = A[end];
A[end] = temp;
start++;
end--;
}
return A;
}
// Driver Code
public static void main(String[] args)
{
int A[] = { 1, 3, 5, 7, 9 };
int n = A.length;
int k = 2;
leftRotate(A, n, k);
k = 3;
leftRotate(A, n, k);
k = 4;
leftRotate(A, n, k);
}
}
Python3
# Python3 implementation of left rotation
# of an array K number of times
# Fills temp with two copies of arr
def rotateArray(A, start, end):
while start < end:
temp = A[start]
A[start] = A[end]
A[end] = temp
start += 1
end -= 1
return A
# Function to left rotate an array k times
def leftRotate(arr, a, k):
# if the value of k ever exceeds the length of the array
c = k % a
# initializing array D so that we always
# have a clone of the original array to rotate
D = arr.copy()
rotateArray(D, 0, c - 1)
rotateArray(D, c, a - 1)
rotateArray(D, 0, a - 1)
# printing the rotated array
print(D)
# Driver program
arr = [1, 3, 5, 7, 9]
n = len(arr)
k = 2
leftRotate(arr, n, k)
k = 3
leftRotate(arr, n, k)
k = 4
leftRotate(arr, n, k)
# This code is contributed by aditya942003patil
C#
// C# program for the above approach
using System;
public class GFG {
public static void leftRotate(int[] A, int a, int k)
{
// if the value of k ever exceeds the length of the
// array
int c = k % a;
// initializing array D so that we always
// have a clone of the original array to rotate
int[] D = A.Clone() as int[];
rotateArray(D, 0, c - 1);
rotateArray(D, c, a - 1);
rotateArray(D, 0, a - 1);
// printing the rotates array
Console.Write("[");
for (int i = 0; i < D.Length - 1; i++) {
Console.Write(D[i] + " ");
}
Console.WriteLine(D[D.Length - 1] + "]");
}
// Function to rotate the array from start index to end
// index
public static int[] rotateArray(int[] A, int start,
int end)
{
while (start < end) {
int temp = A[start];
A[start] = A[end];
A[end] = temp;
start++;
end--;
}
return A;
}
static public void Main()
{
// Code
int[] A = { 1, 3, 5, 7, 9 };
int n = A.Length;
int k = 2;
leftRotate(A, n, k);
k = 3;
leftRotate(A, n, k);
k = 4;
leftRotate(A, n, k);
}
}
// This code is contributed by lokeshmvs21.
JavaScript
class GFG
{
static leftRotate(A, a, k)
{
// if the value of k ever exceeds the length of the array
var c = k % a;
// initializing array D so that we always
// have a clone of the original array to rotate
var D = [...A];
GFG.rotateArray(D, 0, c - 1);
GFG.rotateArray(D, c, a - 1);
GFG.rotateArray(D, 0, a - 1);
// printing the rotated array
console.log(D);
console.log();
}
// Function to rotate the array from start index to end index
static rotateArray(A, start, end)
{
while (start < end)
{
var temp = A[start];
A[start] = A[end];
A[end] = temp;
start++;
end--;
}
return A;
}
// Driver Code
static main(args)
{
var A = [1, 3, 5, 7, 9];
var n = A.length;
var k = 2;
GFG.leftRotate(A, n, k);
k = 3;
GFG.leftRotate(A, n, k);
k = 4;
GFG.leftRotate(A, n, k);
}
}
GFG.main([]);
Output5 7 9 1 3
7 9 1 3 5
9 1 3 5 7
Time Complexity: O(n)
Auxiliary Space: O(n)
Efficient Approach:
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 the temp[0..2n-1] array.
- Step 2: Starting position of the 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.
Implementation:
C++
// CPP implementation of left rotation of
// an array K number of times
#include <bits/stdc++.h>
using namespace std;
// Fills temp[] with two copies of arr[]
void preprocess(int arr[], int n, int temp[])
{
// Store arr[] elements at i and i + n
for (int i = 0; i < n; i++)
temp[i] = temp[i + n] = arr[i];
}
// Function to left rotate an array k times
void leftRotate(int arr[], int n, int k, int temp[])
{
// Starting position of array after k
// rotations in temp[] will be k % n
int start = k % n;
// Print array after k rotations
for (int i = start; i < start + n; i++)
cout << temp[i] << " ";
cout << endl;
}
// Driver program
int main()
{
int arr[] = { 1, 3, 5, 7, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
int temp[2 * n];
preprocess(arr, n, temp);
int k = 2;
leftRotate(arr, n, k, temp);
k = 3;
leftRotate(arr, n, k, temp);
k = 4;
leftRotate(arr, n, k, temp);
return 0;
}
Java
// Java implementation of left rotation of
// an array K number of times
class LeftRotate {
// Fills temp[] with two copies of arr[]
static void preprocess(int arr[], int n, int temp[])
{
// Store arr[] elements at i and i + n
for (int i = 0; i < n; i++)
temp[i] = temp[i + n] = arr[i];
}
// Function to left rotate an array k time
static void leftRotate(int arr[], int n, int k,
int temp[])
{
// Starting position of array after k
// rotations in temp[] will be k % n
int start = k % n;
// Print array after k rotations
for (int i = start; i < start + n; i++)
System.out.print(temp[i] + " ");
System.out.print("\n");
}
// Driver program
public static void main(String[] args)
{
int arr[] = { 1, 3, 5, 7, 9 };
int n = arr.length;
int temp[] = new int[2 * n];
preprocess(arr, n, temp);
int k = 2;
leftRotate(arr, n, k, temp);
k = 3;
leftRotate(arr, n, k, temp);
k = 4;
leftRotate(arr, n, k, temp);
}
}
/*This code is contributed by Prakriti Gupta*/
Python3
# Python3 implementation of left rotation
# of an array K number of times
# Fills temp with two copies of arr
def preprocess(arr, n):
temp = [None] * (2 * n)
# Store arr elements at i and i + n
for i in range(n):
temp[i] = temp[i + n] = arr[i]
return temp
# Function to left rotate an array k times
def leftRotate(arr, n, k, temp):
# Starting position of array after k
# rotations in temp will be k % n
start = k % n
# Print array after k rotations
for i in range(start, start + n):
print(temp[i], end=" ")
print("")
# Driver program
arr = [1, 3, 5, 7, 9]
n = len(arr)
temp = preprocess(arr, n)
k = 2
leftRotate(arr, n, k, temp)
k = 3
leftRotate(arr, n, k, temp)
k = 4
leftRotate(arr, n, k, temp)
# This code is contributed by Sanghamitra Mishra
C#
// C# implementation of left rotation of
// an array K number of times
using System;
class LeftRotate {
// Fills temp[] with two copies of arr[]
static void preprocess(int[] arr, int n, int[] temp)
{
// Store arr[] elements at i and i + n
for (int i = 0; i < n; i++)
temp[i] = temp[i + n] = arr[i];
}
// Function to left rotate an array k time
static void leftRotate(int[] arr, int n, int k,
int[] temp)
{
// Starting position of array after k
// rotations in temp[] will be k % n
int start = k % n;
// Print array after k rotations
for (int i = start; i < start + n; i++)
Console.Write(temp[i] + " ");
Console.WriteLine();
}
// Driver program
public static void Main()
{
int[] arr = { 1, 3, 5, 7, 9 };
int n = arr.Length;
int[] temp = new int[2 * n];
preprocess(arr, n, temp);
int k = 2;
leftRotate(arr, n, k, temp);
k = 3;
leftRotate(arr, n, k, temp);
k = 4;
leftRotate(arr, n, k, temp);
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP implementation of
// left rotation of an
// array K number of times
// Fills $temp with
// two copies of $arr
function preprocess(&$arr, $n,
&$temp)
{
// Store $arr elements
// at i and i + n
for ($i = 0; $i < $n; $i++)
$temp[$i] = $temp[$i + $n] = $arr[$i];
}
// Function to left rotate
// an array k times
function leftRotate(&$arr, $n,
$k, &$temp)
{
// Starting position of
// array after k rotations
// in temp[] will be k % n
$start = $k % $n;
// Print array after
// k rotations
for ($i = $start;
$i < $start + $n; $i++)
echo $temp[$i] . " ";
echo "\n";
}
// Driver Code
$arr = array(1, 3, 5, 7, 9);
$n = sizeof($arr);
$temp[2 * $n] = array();
preprocess($arr, $n, $temp);
$k = 2;
leftRotate($arr, $n, $k, $temp);
$k = 3;
leftRotate($arr, $n, $k, $temp);
$k = 4;
leftRotate($arr, $n, $k, $temp);
// This code is contributed
// by ChitraNayal
?>
JavaScript
<script>
// Javascript implementation of left rotation of
// an array K number of times
// Fills temp with two copies of arr
function preprocess(arr , n , temp) {
// Store arr elements at i and i + n
for (i = 0; i < n; i++)
temp[i] = temp[i + n] = arr[i];
}
// Function to left rotate an array k time
function leftRotate(arr , n , k , temp) {
// Starting position of array after k
// rotations in temp will be k % n
var start = k % n;
// Print array after k rotations
for (i = start; i < start + n; i++)
document.write(temp[i] + " ");
document.write("<br/>");
}
// Driver program
var arr = [ 1, 3, 5, 7, 9 ];
var n = arr.length;
var temp = Array(2 * n).fill(0);
preprocess(arr, n, temp);
var k = 2;
leftRotate(arr, n, k, temp);
k = 3;
leftRotate(arr, n, k, temp);
k = 4;
leftRotate(arr, n, k, temp);
// This code contributed by gauravrajput1
</script>
Output5 7 9 1 3
7 9 1 3 5
9 1 3 5 7
Time Complexity: O(n)
Note that the task to find starting address of rotation takes O(1) time. It is printing the elements that take O(n) time.
Auxiliary Space: O(n)
Space-optimized Approach: The above method takes extra space. Below given is a space-optimized solution. Thanks to frenzy77 for suggesting this approach.
Implementation:
C++
// CPP implementation of left rotation of
// an array K number of times
#include <bits/stdc++.h>
using namespace std;
// Function to left rotate an array k times
void leftRotate(int arr[], int n, int k)
{
// Print array after k rotations
for (int i = k; i < k + n; i++)
cout << arr[i % n] << " ";
}
// Driver program
int main()
{
int arr[] = { 1, 3, 5, 7, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 2;
leftRotate(arr, n, k);
cout << endl;
k = 3;
leftRotate(arr, n, k);
cout << endl;
k = 4;
leftRotate(arr, n, k);
cout << endl;
return 0;
}
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();
}
}
// This code is contributed by ajit
Python 3
# Python3 implementation of
# left rotation of an array
# K number of times
# Function to left rotate
# an array k times
def leftRotate(arr, n, k):
# Print array
# after k rotations
for i in range(k, k + n):
print(str(arr[i % n]),
end=" ")
# Driver Code
arr = [1, 3, 5, 7, 9]
n = len(arr)
k = 2
leftRotate(arr, n, k)
print()
k = 3
leftRotate(arr, n, k)
print()
k = 4
leftRotate(arr, n, k)
print()
# This code is contributed
# by ChitraNayal
C#
// C# implementation of
// left rotation of an
// array K number of times
using System;
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++)
Console.Write(arr[i % n] + " ");
}
// Driver Code
static public void Main()
{
int[] arr = { 1, 3, 5, 7, 9 };
int n = arr.Length;
int k = 2;
leftRotate(arr, n, k);
Console.WriteLine();
k = 3;
leftRotate(arr, n, k);
Console.WriteLine();
k = 4;
leftRotate(arr, n, k);
Console.WriteLine();
}
}
// This code is contributed
// by akt_mit
PHP
<?php
// PHP implementation of left rotation of
// an array K number of times
// Function to left rotate an array k times
function leftRotate($arr, $n, $k)
{
// Print array after k rotations
for ($i = $k; $i < $k + $n; $i++)
echo $arr[$i % $n] ," ";
}
// Driver program
$arr = array (1, 3, 5, 7, 9);
$n = sizeof($arr);
$k = 2;
leftRotate($arr, $n, $k);
echo "\n";
$k = 3;
leftRotate($arr, $n, $k);
echo "\n";
$k = 4;
leftRotate($arr, $n, $k);
echo "\n";
// This code is contributed by aj_36
?>
JavaScript
<script>
// JavaScript implementation of
// left rotation of an
// array K number of times
// Function to left rotate
// an array k times
function leftRotate(arr, n, k)
{
// Print array after
// k rotations
for (let i = k; i < k + n; i++)
document.write(arr[i % n] + " ");
}
// Driver Code
let arr = [1, 3, 5, 7, 9];
n = arr.length;
k = 2;
leftRotate(arr, n, k);
document.write("<br>");
k = 3;
leftRotate(arr, n, k);
document.write("<br>");
k = 4;
leftRotate(arr, n, k);
document.write("<br>");
</script>
Output5 7 9 1 3
7 9 1 3 5
9 1 3 5 7
Time Complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
Print left rotation of array in O(n) time and O(1) space Given an array of size n and multiple values around which we need to left rotate the array. How to quickly print multiple left rotations?Examples : Input : arr[] = {1, 3, 5, 7, 9}k1 = 1k2 = 3k3 = 4k4 = 6Output : 3 5 7 9 17 9 1 3 59 1 3 5 73 5 7 9 1Input : arr[] = {1, 3, 5, 7, 9}k1 = 14 Output : 9 1
15+ min read
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[ ]
5 min read
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
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
8 min read
Javascript Program to 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
8 min read
Javascript 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[ ]
2 min read
Range sum queries for anticlockwise rotations of Array by K indices Given an array arr consisting of N elements and Q queries of the following two types: 1 K: For this type of query, the array needs to be rotated by K indices anticlockwise from its current state.2 L R: For this query, the sum of the array elements present in the indices [L, R] needs to be calculated
10 min read
Queries on Left and Right Circular shift on array Given an array arr[] of N integers. There are three types of commands: 1 x: Right Circular Shift the array x times. If an array is a[0], a[1], ...., a[n - 1], then after one right circular shift the array will become a[n - 1], a[0], a[1], ...., a[n - 2].2 y: Left Circular Shift the array y times. If
11 min read
Rotate a 2D Array or Matrix - Complete Tutorial Rotate a Matrix Clockwise by 1Input 1 2 34 5 6 7 8 9Output: 4 1 27 5 3 8 9 6If we take a closer look at this problem, it is mainly a variation of spiral traversal. We traverse the matrix in spiral form and keep moving previous item to current in a circular manner. Please refer Rotate a Matrix Clockw
5 min read
Minimize number of rotations on array A such that it becomes equal to B Given arrays, A[] and array B[] of size N, the task is to minimize the number of rotations (left or right) on A such that it becomes equal to B. Note: It is always possible to change A to B. Examples: Input: A[] = {1, 2, 3, 4, 5}, B[] = {4, 5, 1, 2, 3} Output: 2Explanation: A[] can be changed to B[]
10 min read