Left Rotation and Right Rotation of a String

29 Jun, 2022
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).
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 : Left Rotation  : "eksforGeeksGe" 
         Right Rotation : "ksGeeksforGee"  


Input : s = "qwertyu" 
        d = 2
Output : Left rotation : "ertyuqw"
         Right rotation : "yuqwert"
Method#1: A Simple Solution is to use a temporary string to do rotations. For left rotation, first, copy last n-d characters, then copy first d characters in order to the temporary string. For right rotation, first, copy last d characters, then copy n-d characters. 
Can we do both rotations in-place and O(n) time? The idea is based on a reversal algorithm for rotation.
// Left rotate string s by d (Assuming d <= n)
leftRotate(s, d)
  reverse(s, 0, d-1); // Reverse substring s[0..d-1]
  reverse(s, d, n-1); // Reverse substring s[d..n-1]
  reverse(s, 0, n-1); // Reverse whole string.  

// Right rotate string s by d (Assuming d <= n)
rightRotate(s, d)

  // We can also call above reverse steps
  // with d = n-d.
  leftRotate(s, n-d)  
Below is the implementation of the above steps : 
C++
Java
Python3
C#
Javascript
// C program for Left Rotation and Right// Rotation of a String#include<bits/stdc++.h>using namespace std; // In-place rotates s towards left by dvoid leftrotate(string &s, int d){    reverse(s.begin(), s.begin()+d);    reverse(s.begin()+d, s.end());    reverse(s.begin(), s.end());} // In-place rotates s towards right by dvoid rightrotate(string &s, int d){   leftrotate(s, s.length()-d);} // Driver codeint main(){    string str1 = "GeeksforGeeks";    leftrotate(str1, 2);    cout << str1 << endl;     string str2 = "GeeksforGeeks";    rightrotate(str2, 2);    cout << str2 << endl;    return 0;}
// Java program for Left Rotation and Right// Rotation of a Stringimport java.util.*;import java.io.*; class GFG{             // function that rotates s towards left by d    static String leftrotate(String str, int d)    {            String ans = str.substring(d) + str.substring(0, d);            return ans;    }     // function that rotates s towards right by d    static String rightrotate(String str, int d)    {            return leftrotate(str, str.length() - d);    }     // Driver code    public static void main(String args[])    {            String str1 = "GeeksforGeeks";            System.out.println(leftrotate(str1, 2));             String str2 = "GeeksforGeeks";            System.out.println(rightrotate(str2, 2));    }} // This code is contributed by rachana soma
# Python3 program for Left# Rotation and Right# Rotation of a String # In-place rotates s towards left by ddef leftrotate(s, d):    tmp = s[d : ] + s[0 : d]    return tmp   # In-place rotates s# towards right by ddef rightrotate(s, d):      return leftrotate(s, len(s) - d) # Driver codeif __name__=="__main__":         str1 = "GeeksforGeeks"    print(leftrotate(str1, 2))      str2 = "GeeksforGeeks"    print(rightrotate(str2, 2)) # This code is contributed by Rutvik_56
// C# program for Left Rotation and Right// Rotation of a Stringusing System;         class GFG{             // function that rotates s towards left by d    static String leftrotate(String str, int d)    {            String ans = str.Substring(d,str.Length-d) + str.Substring(0, d);            return ans;    }     // function that rotates s towards right by d    static String rightrotate(String str, int d)    {            return leftrotate(str, str.Length - d);    }     // Driver code    public static void Main(String []args)    {            String str1 = "GeeksforGeeks";            Console.WriteLine(leftrotate(str1, 2));             String str2 = "GeeksforGeeks";            Console.WriteLine(rightrotate(str2, 2));    }} /* This code is contributed by PrinciRaj1992 */
<script> // JavaScript program for Left Rotation and Right// Rotation of a String // Function that rotates s towards left by dfunction leftrotate(str, d){    var ans = str.substring(d, str.length) +              str.substring(0, d);    return ans;} // Function that rotates s towards right by dfunction rightrotate(str, d){    return leftrotate(str, str.length - d);} // Driver codevar str1 = "GeeksforGeeks";document.write(leftrotate(str1, 2) + "<br>"); var str2 = "GeeksforGeeks";document.write(rightrotate(str2, 2) + "<br>"); // This code is contributed by rdtank </script>
eksforGeeksGe
ksGeeksforGee
               
Time Complexity: O(N), where N is the size of the given string.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Method#2: We can use extended string which is double in size of normal string to rotate string. For left rotation, access the extended string from index n to the index len(string) + n. For right rotation, rotate the string left with size-d places. 
The idea is 
// Left rotate string s by d 
leftRotate(s, n)
  temp = s + s; // extended string 
  l1  = s.length // length of string 
  return temp[n : l1+n] //return rotated string.  

// Right rotate string s by n
rightRotate(s, n)
  // We can also call above reverse steps
  // with x = s.length - n.
  leftRotate(s, x-n)
Below is implementation of above approach
C++
Java
Python3
C#
Javascript
// C++ program for Left Rotation and Right// Rotation of a String#include <bits/stdc++.h>using namespace std; // Rotating the string using extended stringstring leftrotate(string str1, int n){     // creating extended string and index for new rotated    // string    string temp = str1 + str1;    int l1 = str1.size();     string Lfirst = temp.substr(n, l1);     //      now returning  string    return Lfirst;}// Rotating the string using extended stringstring rightrotate(string str1, int n){     return leftrotate(str1, str1.size() - n);} // Driver codeint main(){    string str1 = leftrotate("GeeksforGeeks", 2);    cout << str1 << endl;     string str2 = rightrotate("GeeksforGeeks", 2);    cout << str2 << endl;    return 0;}
// Java program for Left Rotation and Right// Rotation of a Stringimport java.io.*;import java.util.*; class GFG {   // Rotating the string using extended string  static String leftrotate(String str1, int n)  {     // creating extended string and index for new    // rotated string    String temp = str1 + str1;    int l1 = str1.length();     String Lfirst = temp.substring(n, n + l1);     // now returning  string    return Lfirst;  }   // Rotating the string using extended string  static String rightrotate(String str1, int n)  {    return leftrotate(str1, str1.length() - n);  }   // Driver code  public static void main(String args[])  {    String str1 = "GeeksforGeeks";    System.out.println(leftrotate(str1, 2));     String str2 = "GeeksforGeeks";    System.out.println(rightrotate(str2, 2));  }} // This code is contributed by Abhijeet Kumar(abhijeet19403)
# Python3 program for Left# Rotation and Right# Rotation of a String def leftrotate(str1, n):    # extended string    temp = str1 + str1    l = len(str1)    # Return string    return temp[n :l+n]def rightrotate(str1, n):    return leftrotate(str1, len(str1)-n)         return temp[l-n : l1-n  ]# Driver codeif __name__=="__main__":         str1 = "GeeksforGeeks"    print(leftrotate(str1, 2))     str2 = "GeeksforGeeks"    print(rightrotate(str2, 2)) # This code is contributed by sam snehil
// C# program for Left Rotation and Right// Rotation of a Stringusing System; class GFG {     // Rotating the string using extended string    static String leftrotate(String str1, int n)    {         // creating extended string and index for new        // rotated string        String temp = str1 + str1;        int l1 = str1.Length;         String Lfirst = temp.Substring(n, l1);         // now returning  string        return Lfirst;    }     // Rotating the string using extended string    static String rightrotate(String str1, int n)    {        return leftrotate(str1, str1.Length - n);    }     // Driver code    public static void Main(String[] args)    {        String str1 = "GeeksforGeeks";        Console.WriteLine(leftrotate(str1, 2));         String str2 = "GeeksforGeeks";        Console.WriteLine(rightrotate(str2, 2));    }} // This code is contributed by Abhijeet Kumar(abhijeet19403)
// JavaScript program for Left Rotation and Right// Rotation of a String // Function that rotates string towards left by nfunction leftrotate(str1, n){    var temp = str1 + str1;    var l1 = str1.length;         var Lfirst = temp.substr(n,l1); //      now returning  string    return Lfirst;} // Function that rotates string towards right by nfunction rightrotate(str, d){    return leftrotate(str, str.length - d);} // Driver codevar str1 = "GeeksforGeeks";console.log(leftrotate(str1, 2)); var str2 = "GeeksforGeeks";console.log(rightrotate(str2, 2) ); // This code is contributed by sam snehil
eksforGeeksGe
ksGeeksforGee
Time Complexity: O(N), where N is the size of the given string.
Auxiliary Space: O(n), where N is the size of the given string.
This article is contributed by Aart_Rathi and Rishabh Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
rachana soma
princiraj1992
rutvik_56
rdtank
rohitsingh57
tamanna17122007
satyam00so
sachinvinod1904
abhijeet19403
sagartomar9927
rotation
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Different Methods to Reverse a String in C++
Python program to check if a string is palindrome or not
Check for Balanced Brackets in an expression (well-formedness) using Stack
Longest Common Subsequence | DP-4
Length of the longest substring without repeating characters
Top 50 String Coding Problems for Interviews