Java 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 :
Java
// Java program for Left Rotation and Right
// Rotation of a String
import 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
OutputeksforGeeksGe
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:
Java
// Java program for Left Rotation and Right
// Rotation of a String
import 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 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 deque. 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:
The algorithm is
- Define two functions for left rotation and right rotation which accept two arguments as input, a string "s" and an integer "d" which indicates the number of characters to be rotated.
- Create a deque object named "char_deque" of type Character using the ArrayDeque class.
- Add each character of the string to the deque object using a for-each loop.
- Perform a left rotation on the deque object by using a for loop to iterate through the deque "d" number of times. Within the for loop, remove the first element of the deque using "removeFirst()" method and add it to the end of the deque using "addLast()" method.
- Perform a right rotation on the deque object by using a for loop to iterate through the deque "d" number of times. Within the for loop, remove the last element of the deque using "removeLast()" method and add it to the beginning of the deque using "addFirst()" method.
- Convert the deque object back to a string using StringBuilder class and return it as a result of the function.
Below is implementation of above approach:
Java
// Java program for Left Rotation and Right
// Rotation of a String
import java.util.*;
public class GFG {
// Define the left_rotate_string function in Java
static String left_rotate_string(String s, int d)
{
// Create a deque object and add each character of
// the string to it
Deque<Character> char_deque
= new ArrayDeque<Character>();
for (char c : s.toCharArray()) {
char_deque.add(c);
}
// Perform a left rotation on the deque object by
// rotating it by -d elements
for (int i = 0; i < d; i++) {
char_deque.addLast(char_deque.removeFirst());
}
// Convert the deque object back to a string and
// return it
StringBuilder sb = new StringBuilder();
for (char c : char_deque) {
sb.append(c);
}
return sb.toString();
}
// Define the right_rotate_string function in Java
static String right_rotate_string(String s, int d)
{
// Create a deque object and add each character of
// the string to it
Deque<Character> char_deque
= new ArrayDeque<Character>();
for (char c : s.toCharArray()) {
char_deque.add(c);
}
// Perform a right rotation on the deque object by
// rotating it by d elements
for (int i = 0; i < d; i++) {
char_deque.addFirst(char_deque.removeLast());
}
// Convert the deque object back to a string and
// return it
StringBuilder sb = new StringBuilder();
for (char c : char_deque) {
sb.append(c);
}
return sb.toString();
}
public static void main(String[] args)
{
String s = "GeeksforGeeks";
int d = 2;
System.out.println("Left Rotation: "
+ left_rotate_string(s, d));
System.out.println("Right Rotation: "
+ right_rotate_string(s, d));
s = "qwertyu";
d = 2;
System.out.println("Left Rotation: "
+ left_rotate_string(s, d));
System.out.println("Right Rotation: "
+ right_rotate_string(s, d));
}
}
// 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
Java 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
Java 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
Java Program For Printing 180 Degree Rotation of Simple Half Left Pyramid
We can utilize 'for' and 'while' loops to print a 180-degree rotation of a simple half-left pyramid in Java as follows: Example of 180-degree Rotation of Simple Half-Left PyramidRows = 5Output : * * * * * * * * * * * * * * * Methods For Printing 180-Degree Rotation of Simple Half-Left PyramidThere a
3 min read
Java Program for Rotate the matrix right by K times
Given a matrix of size N*M, and a number K. We have to rotate the matrix K times to the right side. Examples: Input : N = 3, M = 3, K = 2 12 23 34 45 56 67 78 89 91 Output : 23 34 12 56 67 45 89 91 78 Input : N = 2, M = 2, K = 2 1 2 3 4 Output : 1 2 3 4 A simple yet effective approach is to consider
2 min read
Java Program to Generate all rotations of a number
Given an integer n, the task is to generate all the left shift numbers possible. A left shift number is a number that is generated when all the digits of the number are shifted one position to the left and the digit at the first position is shifted to the last.Examples: Input: n = 123 Output: 231 31
2 min read
How to Left or Right rotate an Array in Java?
Given an array arr[] of size N and D index, the task is to rotate the array by the D index. We have two flexibilities either to rotate them leftwards or rightwards via different ways which we are going to explore by implementing every way of rotating in both of the rotations. Ways: Using temporary a
15+ min read
Java Program to Count of rotations required to generate a sorted array
Given an array arr[], the task is to find the number of rotations required to convert the given array to sorted form.Examples: Input: arr[] = {4, 5, 1, 2, 3}Â Output: 2Â Explanation:Â Sorted array {1, 2, 3, 4, 5} after 2 anti-clockwise rotations. Input: arr[] = {2, 1, 2, 2, 2}Â Output: 1Â Explanation:Â So
4 min read
Java 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
Java Program to Left Rotate the Elements of an Array
In Java, left rotation of an array involves shifting its elements to the left by a given number of positions, with the first elements moving around to the end. There are different ways to left rotate the elements of an array in Java.Example: We can use a temporary array to rotate the array left by "
5 min read
Java 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