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
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
C++ Programming Language
C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read