 GeeksforGeeks App
Open App Browser
Continue

# Java Program for Left Rotation and Right Rotation of a String

Given a string of size n, write functions to perform the following operations on a string-

1. Left (Or anticlockwise) rotate the given string by d elements (where d <= n)
2. 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`

Output

```eksforGeeksGe
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`

Output

```eksforGeeksGe
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

1. 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.
2. Create a deque object named “char_deque” of type Character using the ArrayDeque class.
3. Add each character of the string to the deque object using a for-each loop.
4. 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.
5. 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.
6. 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 char_deque``            ``= ``new` `ArrayDeque();``        ``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 char_deque``            ``= ``new` `ArrayDeque();``        ``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`

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)

Please refer complete article on Left Rotation and Right Rotation of a String for more details!

My Personal Notes arrow_drop_up