Right rotation of string in python

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Given a string of size n, write functions to perform following operations on 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: We have existing solution for this problem please refer Left Rotation and Right Rotation of a String link. We will solve this problem quickly in python using String Slicing. Approach is very simple,

    1. Separate string in two parts first & second, for Left rotation Lfirst = str[0 : d] and Lsecond = str[d :]. For Right rotation Rfirst = str[0 : len(str)-d] and Rsecond = str[len(str)-d : ].
    2. Now concatenate these two parts second + first accordingly.

    Implementation:

    Python3

    def rotate(input,d):

        Lfirst = input[0 : d]

        Lsecond = input[d :]

        Rfirst = input[0 : len(input)-d]

        Rsecond = input[len(input)-d : ]

        print ("Left Rotation : ", (Lsecond + Lfirst) )

        print ("Right Rotation : ", (Rsecond + Rfirst))

    if __name__ == "__main__":

        input = 'GeeksforGeeks'

        d=2

        rotate(input,d)

    Output:

    Left Rotation  : eksforGeeksGe 
    Right Rotation : ksGeeksforGee

    Method 2: We use extended string to rotate the string. We will solve this problem quickly in python by slicing extended string. Approach is very simple,

    Use extended string Extend_str, for Left rotation Lfirst = Extended_str[n : l1+n] . For Right rotation Rfirst = str[l1-n : l2-n].
    Now print this string. 

    Implementation:

    Python3

    def rotate(str1,n):

        temp = str1 + str1

        l1 = len(str1)

        l2 = len(temp)

        Lfirst = temp[n  : l1+n]

        Lfirst = temp[l1-n : l2-n]

        print ("Left Rotation : ", Lfirst)

        print ("Right Rotation : ", Lfirst )

    if __name__ == "__main__":

        input = 'GeeksforGeeks'

        d=2

        rotate(input,d)

    Output

    Left Rotation :  ksGeeksforGee
    Right Rotation :  ksGeeksforGee


    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)

    1. 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++

    #include

    using namespace std;

    void leftrotate(string &s, int d)

    {

        reverse(s.begin(), s.begin()+d);

        reverse(s.begin()+d, s.end());

        reverse(s.begin(), s.end());

    }

    void rightrotate(string &s, int d)

    {

       leftrotate(s, s.length()-d);

    }

    int main()

    {

        string str1 = "GeeksforGeeks";

        leftrotate(str1, 2);

        cout << str1 << endl;

        string str2 = "GeeksforGeeks";

        rightrotate(str2, 2);

        cout << str2 << endl;

        return 0;

    }

    Java

    import java.util.*;

    import java.io.*;

    class GFG

    {

        static String leftrotate(String str, int d)

        {

                String ans = str.substring(d) + str.substring(0, d);

                return ans;

        }

        static String rightrotate(String str, int d)

        {

                return leftrotate(str, str.length() - d);

        }

        public static void main(String args[])

        {

                String str1 = "GeeksforGeeks";

                System.out.println(leftrotate(str1, 2));

                String str2 = "GeeksforGeeks";

                System.out.println(rightrotate(str2, 2));

        }

    }

    Python3

    def leftrotate(s, d):

        tmp = s[d : ] + s[0 : d]

        return tmp

    def rightrotate(s, d):

       return leftrotate(s, len(s) - d)

    if __name__=="__main__":

        str1 = "GeeksforGeeks"

        print(leftrotate(str1, 2))

        str2 = "GeeksforGeeks"

        print(rightrotate(str2, 2))

    C#

    using System;

    class GFG

    {

        static String leftrotate(String str, int d)

        {

                String ans = str.Substring(d,str.Length-d) + str.Substring(0, d);

                return ans;

        }

        static String rightrotate(String str, int d)

        {

                return leftrotate(str, str.Length - d);

        }

        public static void Main(String []args)

        {

                String str1 = "GeeksforGeeks";

                Console.WriteLine(leftrotate(str1, 2));

                String str2 = "GeeksforGeeks";

                Console.WriteLine(rightrotate(str2, 2));

        }

    }

    Javascript

    Output

    eksforGeeksGe
    ksGeeksforGee

    Time Complexity: O(N), where N is the size of the given string.
    Auxiliary Space: O(1), no extra space is required, so it is a constant.

    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. 

    The idea 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++

    #include

    using namespace std;

    string leftrotate(string str1, int n)

    {

        string temp = str1 + str1;

        int l1 = str1.size();

        string Lfirst = temp.substr(n, l1);

        return Lfirst;

    }

    string rightrotate(string str1, int n)

    {

        return leftrotate(str1, str1.size() - n);

    }

    int main()

    {

        string str1 = leftrotate("GeeksforGeeks", 2);

        cout << str1 << endl;

        string str2 = rightrotate("GeeksforGeeks", 2);

        cout << str2 << endl;

        return 0;

    }

    Java

    import java.io.*;

    import java.util.*;

    class GFG {

      static String leftrotate(String str1, int n)

      {

        String temp = str1 + str1;

        int l1 = str1.length();

        String Lfirst = temp.substring(n, n + l1);

        return Lfirst;

      }

      static String rightrotate(String str1, int n)

      {

        return leftrotate(str1, str1.length() - n);

      }

      public static void main(String args[])

      {

        String str1 = "GeeksforGeeks";

        System.out.println(leftrotate(str1, 2));

        String str2 = "GeeksforGeeks";

        System.out.println(rightrotate(str2, 2));

      }

    }

    Python3

    def leftrotate(str1, n):

        temp = str1 + str1

        l = len(str1)

        return temp[n :l+n]

    def rightrotate(str1, n):

        return leftrotate(str1, len(str1)-n)

        return temp[l-n : l1-n  ]

    if __name__=="__main__":

        str1 = "GeeksforGeeks"

        print(leftrotate(str1, 2))

        str2 = "GeeksforGeeks"

        print(rightrotate(str2, 2))

    C#

    using System;

    class GFG {

        static String leftrotate(String str1, int n)

        {

            String temp = str1 + str1;

            int l1 = str1.Length;

            String Lfirst = temp.Substring(n, l1);

            return Lfirst;

        }

        static String rightrotate(String str1, int n)

        {

            return leftrotate(str1, str1.Length - n);

        }

        public static void Main(String[] args)

        {

            String str1 = "GeeksforGeeks";

            Console.WriteLine(leftrotate(str1, 2));

            String str2 = "GeeksforGeeks";

            Console.WriteLine(rightrotate(str2, 2));

        }

    }

    Javascript

    function leftrotate(str1, n)

    {

        var temp = str1 + str1;

        var l1 = str1.length;

        var Lfirst = temp.substr(n,l1);

        return Lfirst;

    }

    function rightrotate(str, d)

    {

        return leftrotate(str, str.length - d);

    }

    var str1 = "GeeksforGeeks";

    console.log(leftrotate(str1, 2));

    var str2 = "GeeksforGeeks";

    console.log(rightrotate(str2, 2) );

    Output

    eksforGeeksGe
    ksGeeksforGee

    Time Complexity: O(N), where N is the size of the given string.
    Auxiliary Space: O(n), where N is the size of the given string.

    This article is contributed by Aart_Rathi and Rishabh Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks. 


    How do you rotate a string to the right in Python?

    Step 1: Enter string. Step 2: Separate string in two parts first & second, for Left rotation Lfirst = str[0 : d] and Lsecond = str[d :]. For Right rotation Rfirst = str[0 : len(str)-d] and Rsecond = str[len(str)-d : ]. Step 3: Now concatenate these two parts second + first accordingly.

    What is rotation of a string?

    A String is said to be a rotation of another String, if it has the same length, contains the same characters, and they were rotated around one of the characters. For example, String"bcda" is a rotation of "abcd" but "bdca" is not a rotation of String "abcd".

    Is there a rotate command in Python?

    rotate is undoable, NOT queryable, and NOT editable. The rotate command is used to change the rotation of geometric objects. The rotation values are specified as Euler angles (rx, ry, rz). ... .

    How do you rotate an array of elements in the right in Python?

    STEP 3: The array can be right rotated by shifting its elements to a position next to them which can be accomplished by looping through the array in reverse order (loop will start from the length of the array -1 to 0) and perform the operation arr[j] = arr[j-1].