Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Javascript Program for Left Rotation and Right Rotation of a String

  • Last Updated : 31 Mar, 2022

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"

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 : 

Javascript




<script>
 
// JavaScript program for Left Rotation and Right
// Rotation of a String
 
// Function that rotates s towards left by d
function leftrotate(str, d)
{
    var ans = str.substring(d, str.length) +
              str.substring(0, d);
    return ans;
}
 
// Function that rotates s towards right by d
function rightrotate(str, d)
{
    return leftrotate(str, str.length - d);
}
 
// Driver code
var str1 = "GeeksforGeeks";
document.write(leftrotate(str1, 2) + "<br>");
 
var str2 = "GeeksforGeeks";
document.write(rightrotate(str2, 2) + "<br>");
 
// This code is contributed by rdtank
 
</script>

Output: 

Left rotation:  eksforGeeksGe
Right rotation:  ksGeeksforGee                 

Time Complexity: O(N)

Auxiliary Space: O(1)

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!