C++ Program for Left Rotation and Right Rotation of a String
Last Updated :
07 May, 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++
// 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 d
void 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 d
void rightrotate(string &s, int d)
{
leftrotate(s, s.length()-d);
}
// Driver code
int main()
{
string str1 = "GeeksforGeeks";
leftrotate(str1, 2);
cout << str1 << endl;
string str2 = "GeeksforGeeks";
rightrotate(str2, 2);
cout << str2 << endl;
return 0;
}
Output:
Left rotation: eksforGeeksGe
Right rotation: ksGeeksforGee
Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time
Auxiliary Space: O(1), as we are not using any extra space.
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.
Approach:
The approach 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++
// C++ program for Left Rotation and Right
// Rotation of a String
#include <bits/stdc++.h>
using namespace std;
// Rotating the string using extended string
string 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 string
string rightrotate(string str1, int n)
{
return leftrotate(str1, str1.size() - n);
}
// Driver code
int main()
{
string str1 = leftrotate("GeeksforGeeks", 2);
cout << str1 << endl;
string str2 = rightrotate("GeeksforGeeks", 2);
cout << str2 << endl;
return 0;
}
// This code is contributed by Susobhan Akhuli
OutputeksforGeeksGe
ksGeeksforGee
Time Complexity: O(N), where N is the size of the given string.
Auxiliary Space: O(N)
Method 3:
This approach defines two functions for left and right rotation of a string using the rotate() function provided by the STL (Standard Template Library) in C++. 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.
Approach:
The approach is
- Define two functions: left_rotate_string() and right_rotate_string().
- In left_rotate_string(), perform a left rotation on the string s by d elements using the rotate() function.
- In right_rotate_string(), perform a right rotation on the string s by d elements using the rotate() function.
- Return the rotated string.
Below is the implementation of the above approach:
C++
// CPP program for Left Rotation and Right
// Rotation of a String
#include <algorithm>
#include <iostream>
using namespace std;
// Define the left_rotate_string function
string left_rotate_string(string s, int d)
{
// Perform a left rotation on the string by d elements
rotate(s.begin(), s.begin() + d, s.end());
return s;
}
// Define the right_rotate_string function
string right_rotate_string(string s, int d)
{
// Perform a right rotation on the string by d elements
rotate(s.rbegin(), s.rbegin() + d, s.rend());
return s;
}
int main()
{
string s = "GeeksforGeeks";
int d = 2;
cout << "Left Rotation: " << left_rotate_string(s, d)
<< endl;
cout << "Right Rotation: " << right_rotate_string(s, d)
<< endl;
s = "qwertyu";
d = 2;
cout << "Left Rotation: " << left_rotate_string(s, d)
<< endl;
cout << "Right Rotation: " << right_rotate_string(s, d)
<< endl;
return 0;
}
// This code is contributed by Susobhan Akhuli
OutputLeft 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)
Please refer complete article on Left Rotation and Right Rotation of a String for more details!
Similar Reads
C++ Program for Longest subsequence of a number having same left and right rotation
Given a numeric string S, the task is to find the maximum length of a subsequence having its left rotation equal to its right rotation. Examples: Input: S = "100210601" Output: 4 Explanation: The subsequence "0000" satisfies the necessary condition. The subsequence "1010" generates the string "0101"
4 min read
C++ Program for Minimum rotations required to get the same string
Given a string, we need to find the minimum number of rotations required to get the same string. Examples: Input : s = "geeks" Output : 5 Input : s = "aaaa" Output : 1 The idea is based on below post.A Program to check if strings are rotations of each other or not Step 1: Initialize result = 0 (Here
2 min read
C++ 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
C++ Program to Minimize characters to be changed to make the left and right rotation of a string same
Given a string S of lowercase English alphabets, the task is to find the minimum number of characters to be changed such that the left and right rotation of the string are the same. Examples: Input: S = âabcdâOutput: 2Explanation:String after the left shift: âbcdaâString after the right shift: âdabc
3 min read
C++ Program to check if strings are rotations of each other or not
Given a string s1 and a string s2, write a snippet to say whether s2 is a rotation of s1? (eg given s1 = ABCD and s2 = CDAB, return true, given s1 = ABCD, and s2 = ACBD , return false) Algorithm: areRotations(str1, str2) 1. Create a temp string and store concatenation of str1 to str1 in temp. temp =
2 min read
C++ Program to Check if strings are rotations of each other or not | Set 2
Given two strings s1 and s2, check whether s2 is a rotation of s1. Examples: Input : ABACD, CDABA Output : True Input : GEEKS, EKSGE Output : True We have discussed an approach in earlier post which handles substring match as a pattern. In this post, we will be going to use KMP algorithm's lps (lon
2 min read
C++ 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
C++ 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
C++ Program to Find Lexicographically minimum string rotation | Set 1
Write code to find lexicographic minimum in a circular array, e.g. for the array BCABDADAB, the lexicographic minimum is ABBCABDAD.Source: Google Written TestMore Examples:Â Input: GEEKSQUIZ Output: EEKSQUIZG Input: GFG Output: FGG Input: GEEKSFORGEEKS Output: EEKSFORGEEKSG Following is a simple sol
2 min read
C++ Program for Queries for rotation and Kth character of the given string in constant time
Given a string str, the task is to perform the following type of queries on the given string: (1, K): Left rotate the string by K characters.(2, K): Print the Kth character of the string. Examples: Input: str = "abcdefgh", q[][] = {{1, 2}, {2, 2}, {1, 4}, {2, 7}} Output: d e Query 1: str = "cdefghab
3 min read