Left Rotation and Right Rotation of a String
Last Updated :
19 Oct, 2023
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 : 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++
#include<bits/stdc++.h>
using namespace std;
void leftrotate(string &s, int d)
{
reverse(s.begin(), s.begin()+d);
reverse(s.begin()+d, s.end());
reverse(s.begin(), s.end());
}
void rightrotate(string &s, int d)
{
leftrotate(s, s.length()-d);
}
int main()
{
string str1 = "GeeksforGeeks" ;
leftrotate(str1, 2);
cout << str1 << endl;
string str2 = "GeeksforGeeks" ;
rightrotate(str2, 2);
cout << str2 << endl;
return 0;
}
|
Java
import java.util.*;
import java.io.*;
class GFG
{
static String leftrotate(String str, int d)
{
String ans = str.substring(d) + str.substring( 0 , d);
return ans;
}
static String rightrotate(String str, int d)
{
return leftrotate(str, str.length() - d);
}
public static void main(String args[])
{
String str1 = "GeeksforGeeks" ;
System.out.println(leftrotate(str1, 2 ));
String str2 = "GeeksforGeeks" ;
System.out.println(rightrotate(str2, 2 ));
}
}
|
Python3
def leftrotate(s, d):
tmp = s[d : ] + s[ 0 : d]
return tmp
def rightrotate(s, d):
return leftrotate(s, len (s) - d)
if __name__ = = "__main__" :
str1 = "GeeksforGeeks"
print (leftrotate(str1, 2 ))
str2 = "GeeksforGeeks"
print (rightrotate(str2, 2 ))
|
C#
using System;
class GFG
{
static String leftrotate(String str, int d)
{
String ans = str.Substring(d,str.Length-d) + str.Substring(0, d);
return ans;
}
static String rightrotate(String str, int d)
{
return leftrotate(str, str.Length - d);
}
public static void Main(String []args)
{
String str1 = "GeeksforGeeks" ;
Console.WriteLine(leftrotate(str1, 2));
String str2 = "GeeksforGeeks" ;
Console.WriteLine(rightrotate(str2, 2));
}
}
|
Javascript
<script>
function leftrotate(str, d)
{
var ans = str.substring(d, str.length) +
str.substring(0, d);
return ans;
}
function rightrotate(str, d)
{
return leftrotate(str, str.length - d);
}
var str1 = "GeeksforGeeks" ;
document.write(leftrotate(str1, 2) + "<br>" );
var str2 = "GeeksforGeeks" ;
document.write(rightrotate(str2, 2) + "<br>" );
</script>
|
Output
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++
#include <bits/stdc++.h>
using namespace std;
string leftrotate(string str1, int n)
{
string temp = str1 + str1;
int l1 = str1.size();
string Lfirst = temp.substr(n, l1);
return Lfirst;
}
string rightrotate(string str1, int n)
{
return leftrotate(str1, str1.size() - n);
}
int main()
{
string str1 = leftrotate( "GeeksforGeeks" , 2);
cout << str1 << endl;
string str2 = rightrotate( "GeeksforGeeks" , 2);
cout << str2 << endl;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static String leftrotate(String str1, int n)
{
String temp = str1 + str1;
int l1 = str1.length();
String Lfirst = temp.substring(n, n + l1);
return Lfirst;
}
static String rightrotate(String str1, int n)
{
return leftrotate(str1, str1.length() - n);
}
public static void main(String args[])
{
String str1 = "GeeksforGeeks" ;
System.out.println(leftrotate(str1, 2 ));
String str2 = "GeeksforGeeks" ;
System.out.println(rightrotate(str2, 2 ));
}
}
|
Python3
def leftrotate(str1, n):
temp = str1 + str1
l = len (str1)
return temp[n :l + n]
def rightrotate(str1, n):
return leftrotate(str1, len (str1) - n)
return temp[l - n : l1 - n ]
if __name__ = = "__main__" :
str1 = "GeeksforGeeks"
print (leftrotate(str1, 2 ))
str2 = "GeeksforGeeks"
print (rightrotate(str2, 2 ))
|
C#
using System;
class GFG {
static String leftrotate(String str1, int n)
{
String temp = str1 + str1;
int l1 = str1.Length;
String Lfirst = temp.Substring(n, l1);
return Lfirst;
}
static String rightrotate(String str1, int n)
{
return leftrotate(str1, str1.Length - n);
}
public static void Main(String[] args)
{
String str1 = "GeeksforGeeks" ;
Console.WriteLine(leftrotate(str1, 2));
String str2 = "GeeksforGeeks" ;
Console.WriteLine(rightrotate(str2, 2));
}
}
|
Javascript
function leftrotate(str1, n)
{
var temp = str1 + str1;
var l1 = str1.length;
var Lfirst = temp.substr(n,l1);
return Lfirst;
}
function rightrotate(str, d)
{
return leftrotate(str, str.length - d);
}
var str1 = "GeeksforGeeks" ;
console.log(leftrotate(str1, 2));
var str2 = "GeeksforGeeks" ;
console.log(rightrotate(str2, 2) );
|
Output
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.
Approach#3: Using deque
This approach defines two functions for left and right rotation of a string using the deque data structure from the collections module in Python. The left_rotate_string() function rotates the string s by d positions to the left, while the right_rotate_string() function rotates the string s by d positions to the right. Both functions return the rotated string.
Algorithm
1. Define two functions for left rotation and right rotation.
2. Convert the input string to a deque using the collections module.
3. To perform left rotation, use the rotate() method with a negative rotation point.
4. To perform right rotation, use the rotate() method with a positive rotation point.
5. Convert the deque back to a string using the join() method.
6. Return the rotated string.
C++
#include <bits/stdc++.h>
using namespace std;
string leftRotateString(string s, int d) {
deque< char > charDeque(s.begin(), s.end());
rotate(charDeque.begin(), charDeque.begin() + d, charDeque.end());
return string(charDeque.begin(), charDeque.end());
}
string rightRotateString(string s, int d) {
deque< char > charDeque(s.begin(), s.end());
rotate(charDeque.rbegin(), charDeque.rbegin() + d, charDeque.rend());
return string(charDeque.begin(), charDeque.end());
}
int main() {
string s = "GeeksforGeeks" ;
int d = 2;
cout << "Left Rotation: " << leftRotateString(s, d) << endl;
cout << "Right Rotation: " << rightRotateString(s, d) << endl;
s = "qwertyu" ;
d = 2;
cout << "Left Rotation: " << leftRotateString(s, d) << endl;
cout << "Right Rotation: " << rightRotateString(s, d) << endl;
return 0;
}
|
Java
import java.io.*;
import java.util.ArrayDeque;
import java.util.Deque;
public class GFG {
public static String leftRotateString(String s, int d) {
Deque<Character> charDeque = new ArrayDeque<>();
for ( char c : s.toCharArray()) {
charDeque.addLast(c);
}
for ( int i = 0 ; i < d; i++) {
char firstChar = charDeque.removeFirst();
charDeque.addLast(firstChar);
}
StringBuilder result = new StringBuilder();
for ( char c : charDeque) {
result.append(c);
}
return result.toString();
}
public static String rightRotateString(String s, int d) {
Deque<Character> charDeque = new ArrayDeque<>();
for ( char c : s.toCharArray()) {
charDeque.addLast(c);
}
for ( int i = 0 ; i < d; i++) {
char lastChar = charDeque.removeLast();
charDeque.addFirst(lastChar);
}
StringBuilder result = new StringBuilder();
for ( char c : charDeque) {
result.append(c);
}
return result.toString();
}
public static void main(String[] args) {
String s = "GeeksforGeeks" ;
int d = 2 ;
System.out.println( "Left Rotation: " + leftRotateString(s, d));
System.out.println( "Right Rotation: " + rightRotateString(s, d));
s = "qwertyu" ;
d = 2 ;
System.out.println( "Left Rotation: " + leftRotateString(s, d));
System.out.println( "Right Rotation: " + rightRotateString(s, d));
}
}
|
Python3
from collections import deque
def left_rotate_string(s, d):
char_deque = deque(s)
char_deque.rotate( - d)
return ''.join(char_deque)
def right_rotate_string(s, d):
char_deque = deque(s)
char_deque.rotate(d)
return ''.join(char_deque)
s = "GeeksforGeeks"
d = 2
print ( "Left Rotation:" , left_rotate_string(s, d))
print ( "Right Rotation:" , right_rotate_string(s, d))
s = "qwertyu"
d = 2
print ( "Left Rotation:" , left_rotate_string(s, d))
print ( "Right Rotation:" , right_rotate_string(s, d))
|
C#
using System;
using System.Collections.Generic;
class Program
{
static string LeftRotateString( string s, int d)
{
Queue< char > charQueue = new Queue< char >(s);
for ( int i = 0; i < d; i++)
{
char firstChar = charQueue.Dequeue();
charQueue.Enqueue(firstChar);
}
return new string (charQueue.ToArray());
}
static string RightRotateString( string s, int d)
{
Queue< char > charQueue = new Queue< char >(s);
int rotateCount = s.Length - d;
for ( int i = 0; i < rotateCount; i++)
{
char lastChar = charQueue.Dequeue();
charQueue.Enqueue(lastChar);
}
return new string (charQueue.ToArray());
}
static void Main()
{
string s = "GeeksforGeeks" ;
int d = 2;
Console.WriteLine( "Left Rotation: " + LeftRotateString(s, d));
Console.WriteLine( "Right Rotation: " + RightRotateString(s, d));
s = "qwertyu" ;
d = 2;
Console.WriteLine( "Left Rotation: " + LeftRotateString(s, d));
Console.WriteLine( "Right Rotation: " + RightRotateString(s, d));
}
}
|
Javascript
function left_rotate_string(s, d)
{
let char_deque = [...s];
char_deque = char_deque.slice(d).concat(char_deque.slice(0, d));
return char_deque.join( '' );
}
function right_rotate_string(s, d)
{
let char_deque = [...s];
char_deque = char_deque.slice(-d).concat(char_deque.slice(0, -d));
return char_deque.join( '' );
}
let s = "GeeksforGeeks" ;
let d = 2;
console.log( "Left Rotation:" , left_rotate_string(s, d));
console.log( "Right Rotation:" , right_rotate_string(s, d));
s = "qwertyu" ;
d = 2;
console.log( "Left Rotation:" , left_rotate_string(s, d));
console.log( "Right Rotation:" , right_rotate_string(s, d));
|
Output
Left Rotation: eksforGeeksGe
Right Rotation: ksGeeksforGee
Left Rotation: ertyuqw
Right Rotation: yuqwert
Time complexity: O(n), where n is the length of the input string s. This is because the rotation operation requires visiting every character in the string exactly once.
Auxiliary Space: O(n), where n is the length of the input string s. This is because the deque object created from the string requires O(n) space to store all the characters. The join() function also requires O(n) space to concatenate the characters back into a string.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...