Given an arrayarr[] of size N, the task is to rotate the array by d position to the left.
Examples:
Input: arr[] = {1, 2, 3, 4, 5, 6, 7}, d = 2 Output: 3, 4, 5, 6, 7, 1, 2 Explanation: If the array is rotated by 1 position to the left, it becomes {2, 3, 4, 5, 6, 7, 1}. When it is rotated further by 1 position, it becomes: {3, 4, 5, 6, 7, 1, 2}
Approach: We have already discussed several methods in this post. The ways discussed there are:
Using another temporary array.
Rotating one by one.
Using a juggling algorithm.
Another Approach (The Reversal Algorithm): Here we will be discussing another method which uses the concept of reversing a part of array. The intuition behind the idea is mentioned below:
Intuition:
If we observe closely, we can see that a group of array elements is changing its position. For example see the following array: arr[] = {1, 2, 3, 4, 5, 6, 7} and d = 2. The rotated array is {3, 4, 5, 6, 7, 1, 2}
The group having the first two elements is moving to the end of the array. This is like reversing the array.
But the issue is that if we only reverse the array, it becomes {7, 6, 5, 4, 3, 2, 1}.
After rotation the elements in the chunks having the first 5 elements {7, 6, 5, 4, 3} and the last 2 elements {2, 1} should be in the actual order as of the initial array [i.e., {3, 4, 5, 6, 7} and {1, 2}]but here it gets reversed.
So if those blocks are reversed again we get the desired rotated array.
So the sequence of operations is:
Reverse the whole array
Then reverse the last 'd' elements and
Then reverse the first (N-d) elements.
As we are performing reverse operations it is also similar to the following sequence:
Reverse the first 'd' elements
Reverse last (N-d) elements
Reverse the whole array.
Algorithm: The algorithm can be described with the help of the below pseudocode:
Pseudocode:
Algorithm reverse(arr, start, end): mid = (start + end)/2 loop from i = start to mid: swap (arr[i], arr[end-(mid-i+1)])
Follow the illustration below to for better understanding of the algorithm and intuition:
For example take the array arr[] = {1, 2, 3, 4, 5, 6, 7} and d = 2.
Array
The rotated array will look like:
Rotated Array
1st Step: Consider the array as a combination of two blocks. One containing the first two elements and the other containing the remaining elements as shown above.
Considered 2 blocks
2nd Step: Now reverse the first d elements. It becomes as shown in the image
Reverse the first K elements
3rd Step: Now reverse the last (N-d) elements. It become as it is shown in the below image:
Reverse the last (N-K) elements
4th Step: Now the array is the exact reversed form of how it should be if left shifted d times. So reverse the whole array and you will get the required rotated array.
The total array is reversed
See that the array is now the same as the rotated array.
Below is the implementation of the above approach:
C++
#include<algorithm> // for reverse function#include<iostream> // for input/output operations#include<vector> // for vector containerusingnamespacestd;// Function to rotate an array by k elements to the rightvoidrotateArray(vector<int>&arr,intk){// Find the size of the arrayintn=arr.size();// Mod k with the size of the array// To handle the case where k is greater than the size of the arrayk%=n;// Reverse the entire arrayreverse(arr.begin(),arr.end());// Reverse the first k elementsreverse(arr.begin(),arr.begin()+k);// Reverse the remaining n-k elementsreverse(arr.begin()+k,arr.end());}intmain(){// Initialize the arrayvector<int>arr={1,2,3,4,5};// Number of elements to rotate to the rightintk=2;// Call the rotateArray function to rotate the arrayrotateArray(arr,k);// Print the rotated arrayfor(inti:arr){cout<<i<<" ";}// Return 0 to indicate successful termination of the programreturn0;}
C++
// C++ program for reversal algorithm// of array rotation#include<bits/stdc++.h>usingnamespacestd;// Function to reverse arr[] // from index start to endvoidreverseArray(intarr[],intstart,intend){while(start<end){inttemp=arr[start];arr[start]=arr[end];arr[end]=temp;start++;end--;}}// Function to left rotate arr[] of size n by dvoidleftRotate(intarr[],intd,intn){if(d==0)return;// In case the rotating factor is// greater than array lengthd=d%n;reverseArray(arr,0,d-1);reverseArray(arr,d,n-1);reverseArray(arr,0,n-1);}// Function to print an arrayvoidprintArray(intarr[],intsize){for(inti=0;i<size;i++)cout<<arr[i]<<" ";}// Driver codeintmain(){intarr[]={1,2,3,4,5,6,7};intN=sizeof(arr)/sizeof(arr[0]);intd=2;// Function callleftRotate(arr,d,N);printArray(arr,N);return0;}
C
// C/C++ program for reversal algorithm of array rotation#include<stdio.h>/*Utility function to print an array */voidprintArray(intarr[],intsize);/* Utility function to reverse arr[] from start to end */voidreverseArray(intarr[],intstart,intend);/* Function to left rotate arr[] of size n by d */voidleftRotate(intarr[],intd,intn){if(d==0)return;// in case the rotating factor is// greater than array lengthd=d%n;reverseArray(arr,0,d-1);reverseArray(arr,d,n-1);reverseArray(arr,0,n-1);}/*UTILITY FUNCTIONS*//* function to print an array */voidprintArray(intarr[],intsize){inti;for(i=0;i<size;i++)printf("%d ",arr[i]);}/*Function to reverse arr[] from index start to end*/voidreverseArray(intarr[],intstart,intend){inttemp;while(start<end){temp=arr[start];arr[start]=arr[end];arr[end]=temp;start++;end--;}}/* Driver program to test above functions */intmain(){intarr[]={1,2,3,4,5,6,7};intn=sizeof(arr)/sizeof(arr[0]);intd=2;leftRotate(arr,d,n);printArray(arr,n);return0;}
Java
// Java program for reversal algorithm of array rotationimportjava.io.*;classLeftRotate{/* Function to left rotate arr[] of size n by d */staticvoidleftRotate(intarr[],intd){if(d==0)return;intn=arr.length;// in case the rotating factor is// greater than array lengthd=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*/staticvoidreverseArray(intarr[],intstart,intend){inttemp;while(start<end){temp=arr[start];arr[start]=arr[end];arr[end]=temp;start++;end--;}}/*UTILITY FUNCTIONS*//* function to print an array */staticvoidprintArray(intarr[]){for(inti=0;i<arr.length;i++)System.out.print(arr[i]+" ");}/* Driver program to test above functions */publicstaticvoidmain(String[]args){intarr[]={1,2,3,4,5,6,7};intn=arr.length;intd=2;leftRotate(arr,d);// Rotate array by dprintArray(arr);}}/*This code is contributed by Devesh Agrawal*/
Python3
# Python program for reversal algorithm of array rotation# Function to reverse arr[] from index start to enddefreverseArray(arr,start,end):while(start<end):temp=arr[start]arr[start]=arr[end]arr[end]=tempstart+=1end=end-1# Function to left rotate arr[] of size n by ddefleftRotate(arr,d):ifd==0:returnn=len(arr)# in case the rotating factor is# greater than array lengthd=d%nreverseArray(arr,0,d-1)reverseArray(arr,d,n-1)reverseArray(arr,0,n-1)# Function to print an arraydefprintArray(arr):foriinrange(0,len(arr)):print(arr[i],end=' ')# Driver function to test above functionsarr=[1,2,3,4,5,6,7]n=len(arr)d=2leftRotate(arr,d)# Rotate array by 2printArray(arr)# This code is contributed by Devesh Agrawal
C#
// C# program for reversal algorithm// of array rotationusingSystem;classGFG{/* Function to left rotate arr[] of size n by d */staticvoidleftRotate(int[]arr,intd){if(d==0)return;intn=arr.Length;// in case the rotating factor is// greater than array lengthd=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*/staticvoidreverseArray(int[]arr,intstart,intend){inttemp;while(start<end){temp=arr[start];arr[start]=arr[end];arr[end]=temp;start++;end--;}}/*UTILITY FUNCTIONS*//* function to print an array */staticvoidprintArray(int[]arr){for(inti=0;i<arr.Length;i++)Console.Write(arr[i]+" ");}// Driver codepublicstaticvoidMain(){int[]arr={1,2,3,4,5,6,7};intn=arr.Length;intd=2;leftRotate(arr,d);// Rotate array by 2printArray(arr);}}// This code is contributed by Sam007
PHP
<?php// PHP program for reversal // algorithm of array rotation/* Function to left rotate arr of size n by d */functionleftRotate(&$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 reverse $arr from index start to end*/functionreverseArray(&$arr,$start,$end){while($start<$end){$temp=$arr[$start];$arr[$start]=$arr[$end];$arr[$end]=$temp;$start++;$end--;}}// Function to // print an array functionprintArray($arr,$size){for($i=0;$i<$size;$i++)print$arr[$i]." ";}// Driver code$arr=array(1,2,3,4,5,6,7);$n=sizeof($arr);$d=2;// Function callingleftRotate($arr,$d,$n);printArray($arr,$n);// This code is contributed// by ChitraNayal?>
JavaScript
<script>// JavaScript program for reversal algorithm// of array rotation/*Function to reverse arr[] from index start to end*/functionreverseArray(arr,start,end){while(start<end){vartemp=arr[start];arr[start]=arr[end];arr[end]=temp;start++;end--;}}/* Function to left rotate arr[] of size n by d */functionleftRotate(arr,d,n){if(d==0)return;// in case the rotating factor is// greater than array lengthd=d%n;reverseArray(arr,0,d-1);reverseArray(arr,d,n-1);reverseArray(arr,0,n-1);}// Function to print an arrayfunctionprintArray(arr,size){for(vari=0;i<size;i++)document.write(arr[i]+" ");}/* Driver program to test above functions */vararr=[1,2,3,4,5,6,7];varn=arr.length;vard=2;// Function callingleftRotate(arr,d,n);printArray(arr,n);// This code is contributed by rdtank.</script>
#include<algorithm> // for reverse function#include<iostream> // for input/output operations#include<vector> // for vector containerusingnamespacestd;// Function to rotate an array by k elements to the rightvoidrotateArray(vector<int>&arr,intk){// Find the size of the arrayintn=arr.size();// Mod k with the size of the array// To handle the case where k is greater than the size of the arrayk%=n;// Reverse the entire arrayreverse(arr.begin(),arr.end());// Reverse the first k elementsreverse(arr.begin(),arr.begin()+k);// Reverse the remaining n-k elementsreverse(arr.begin()+k,arr.end());}intmain(){// Initialize the arrayvector<int>arr={1,2,3,4,5};// Number of elements to rotate to the rightintk=2;// Call the rotateArray function to rotate the arrayrotateArray(arr,k);// Print the rotated arrayfor(inti:arr){cout<<i<<" ";}// Return 0 to indicate successful termination of the programreturn0;}
Java
importjava.util.ArrayList;importjava.util.Collections;publicclassMain{publicstaticvoidmain(String[]args){// Initialize the arrayArrayList<Integer>arr=newArrayList<>();arr.add(1);arr.add(2);arr.add(3);arr.add(4);arr.add(5);// Number of elements to rotate to the rightintk=2;// Call the rotateArray function to rotate the arrayrotateArray(arr,k);// Print the rotated arrayfor(inti:arr){System.out.print(i+" ");}}// Function to rotate an array by k elements to the// rightpublicstaticvoidrotateArray(ArrayList<Integer>arr,intk){// Find the size of the arrayintn=arr.size();// Mod k with the size of the array// To handle the case where k is greater than the// size of the arrayk%=n;// Reverse the entire arrayCollections.reverse(arr);// Reverse the first k elementsfor(inti=0;i<k/2;i++){inttemp=arr.get(i);arr.set(i,arr.get(k-i-1));arr.set(k-i-1,temp);}// Reverse the remaining n-k elementsfor(inti=k;i<(n+k)/2;i++){inttemp=arr.get(i);arr.set(i,arr.get(n+k-i-1));arr.set(n+k-i-1,temp);}}}
Python3
# Function to rotate an array by k elements to the rightdefrotateArray(arr,k):# Find the size of the arrayn=len(arr);# Mod k with the size of the array# To handle the case where k is greater than the size of the arrayk%=n;# Reverse the entire arrayarr[0:n]=arr[0:n][::-1]# Reverse the first k elementsarr[0:k]=arr[0:k][::-1]# Reverse the remaining n-k elementsarr[k:n]=arr[k:n][::-1]# Initialize the arrayarr=[1,2,3,4,5];# Number of elements to rotate to the rightk=2;# Call the rotateArray function to rotate the arrayrotateArray(arr,k);# Print the rotated arrayforiinrange(0,len(arr)):print(arr[i],end=" ");
JavaScript
// Define the function to rotate an arrayfunctionrotateArray(arr,k){// Find the length of the arrayconstn=arr.length;// Mod k with the length of the array// To handle the case where k is greater than the// length of the arrayk%=n;// Reverse the entire arrayarr.reverse();// Reverse the first k elementsfor(leti=0;i<k/2;i++){consttemp=arr[i];arr[i]=arr[k-i-1];arr[k-i-1]=temp;}// Reverse the remaining n-k elementsfor(leti=k;i<(n+k)/2;i++){consttemp=arr[i];arr[i]=arr[n+k-i-1];arr[n+k-i-1]=temp;}}// Initialize the arrayconstarr=[1,2,3,4,5];// Number of elements to rotate to the rightconstk=2;// Call the rotateArray function to rotate the arrayrotateArray(arr,k);// Print the rotated arrayconsole.log(arr.join(' '));
C#
usingSystem;usingSystem.Linq;namespaceArrayRotation{classProgram{staticvoidMain(string[]args){// Initialize the arrayint[]arr={1,2,3,4,5};// Number of elements to rotate to the rightintk=2;// Call the RotateArray function to rotate the arrayRotateArray(refarr,k);// Print the rotated arrayConsole.WriteLine(string.Join(" ",arr));// Wait for the user to end the programConsole.ReadKey();}// Function to rotate an array by k elements to the// rightstaticvoidRotateArray(refint[]arr,intk){// Find the size of the arrayintn=arr.Length;// Mod k with the size of the array// To handle the case where k is greater than the// size of the arrayk%=n;// Reverse the first n-k elementsArray.Reverse(arr,0,n-k);// Reverse the remaining k elementsArray.Reverse(arr,n-k,k);// Reverse the entire arrayArray.Reverse(arr);}}}
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.