Given a string of size n, write functions to perform following operations on 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).
Input : s = "GeeksforGeeks" d = 2 Output : Left Rotation : "eksforGeeksGe" Right Rotation : "ksGeeksforGee" Input : s = "qwertyu" d = 2 Output : Left rotation : "ertyuqw" Right rotation : "yuqwert"
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 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 above steps :
Left rotation: eksforGeeksGe Right rotation: ksGeeksforGee
This article is contributed by Rishabh Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Left rotation of an array using vectors in C++
- Print left rotation of array in O(n) time and O(1) space
- Check if a given string is a rotation of a palindrome
- Lexicographically minimum string rotation | Set 1
- Queries for rotation and Kth character of the given string in constant time
- Program for array rotation
- Circular rotation of an array using deque in C++
- Clockwise rotation of Linked List
- Reversal algorithm for array rotation
- Reversal algorithm for right rotation of an array
- Maximize count of corresponding same elements in given Arrays by Rotation
- Block swap algorithm for array rotation
- Find a rotation with maximum hamming distance
- C Program for Reversal algorithm for array rotation
- Find the Rotation Count in Rotated Sorted array
- Java Program for Reversal algorithm for array rotation
- Minimum length of substring whose rotation generates a palindromic substring
- Check if left and right shift of any string results into given string
- Check if string is right to left diagonal or not
- Maximize count of 0s in left and 1s in right substring by splitting given Binary string