Check if a string can be obtained by rotating another string 2 places

08 Jul, 2022
Given two strings, the task is to find if a string can be obtained by rotating another string two places. 
Examples: 
Input: string1 = “amazon”, string2 = “azonam” Output: Yes // rotated anti-clockwiseInput: string1 = “amazon”, string2 = “onamaz” Output: Yes // rotated clockwise
Asked in: Amazon Interview
Clockwise rotated Anti-clockwise rotated
Clockwise rotated 
Anti-clockwise rotated
If clockwise rotated that means elements are shifted in right. So, check if a substring[2.... len-1] of string2 when concatenated with substring[0,1] of string2 is equal to string1. Then, return true.
Else, check if it is rotated anti-clockwise that means elements are shifted to left.  So, check if concatenation of substring[len-2, len-1] with substring[0....len-3] makes it equals to string1. Then return true.
Else, return false.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program to check if a string is two time// rotation of another string.#include<bits/stdc++.h>using namespace std; // Function to check if string2 is obtained by// string 1bool isRotated(string str1, string str2){    if (str1.length() != str2.length())        return false;    if(str1.length()<2){      return str1.compare(str2) == 0;    }    string clock_rot = "";    string anticlock_rot = "";    int len = str2.length();     // Initialize string as anti-clockwise rotation    anticlock_rot = anticlock_rot +                    str2.substr(len-2, 2) +                    str2.substr(0, len-2) ;     // Initialize string as clock wise rotation    clock_rot = clock_rot +                str2.substr(2) +                str2.substr(0, 2) ;     // check if any of them is equal to string1    return (str1.compare(clock_rot) == 0 ||            str1.compare(anticlock_rot) == 0);} // Driver codeint main(){    string str1 = "geeks";    string str2 = "eksge";     isRotated(str1, str2) ? cout << "Yes"                          : cout << "No";    return 0;}
// Java program to check if a string is two time// rotation of another string. class Test{    // Method to check if string2 is obtained by    // string 1    static boolean isRotated(String str1, String str2)    {        if (str1.length() != str2.length())            return false;        if(str1.length() < 2)        {            return str1.equals(str2);        }              String clock_rot = "";        String anticlock_rot = "";        int len = str2.length();              // Initialize string as anti-clockwise rotation        anticlock_rot = anticlock_rot +                        str2.substring(len-2, len) +                        str2.substring(0, len-2) ;              // Initialize string as clock wise rotation        clock_rot = clock_rot +                    str2.substring(2) +                    str2.substring(0, 2) ;              // check if any of them is equal to string1        return (str1.equals(clock_rot) ||                str1.equals(anticlock_rot));    }         // Driver method    public static void main(String[] args)    {        String str1 = "geeks";        String str2 = "eksge";              System.out.println(isRotated(str1, str2) ?  "Yes"                              : "No");    }}
# Python 3 program to check if a string# is two time rotation of another string. # Function to check if string2 is# obtained by string 1def isRotated(str1, str2):     if (len(str1) != len(str2)):        return False         if(len(str1) < 2):        return str1 == str2    clock_rot = ""    anticlock_rot = ""    l = len(str2)     # Initialize string as anti-clockwise rotation    anticlock_rot = (anticlock_rot + str2[l - 2:] +                                     str2[0: l - 2])         # Initialize string as clock wise rotation    clock_rot = clock_rot + str2[2:] + str2[0:2]     # check if any of them is equal to string1    return (str1 == clock_rot or            str1 == anticlock_rot) # Driver codeif __name__ == "__main__":         str1 = "geeks"    str2 = "eksge"if isRotated(str1, str2):    print("Yes") else:    print("No") # This code is contributed by ita_c
using System; // C# program to check if a string is two time// rotation of another string. public class Test {    // Method to check if string2 is obtained by    // string 1    public static bool isRotated(string str1, string str2)    {        if (str1.Length != str2.Length) {            return false;        }         if (str1.Length < 2) {            return str1.Equals(str2);        }         string clock_rot = "";        string anticlock_rot = "";        int len = str2.Length;         // Initialize string as anti-clockwise rotation        anticlock_rot            = anticlock_rot              + str2.Substring(len - 2, len - (len - 2))              + str2.Substring(0, len - 2);         // Initialize string as clock wise rotation        clock_rot = clock_rot + str2.Substring(2)                    + str2.Substring(0, 2);         // check if any of them is equal to string1        return (str1.Equals(clock_rot)                || str1.Equals(anticlock_rot));    }     // Driver code    public static void Main(string[] args)    {        string str1 = "geeks";        string str2 = "eksge";         Console.WriteLine(isRotated(str1, str2) ? "Yes"                                                : "No");    }} // This code is contributed by Shrikant13
<script> // Javascript program to check if a// string is two time rotation of// another string.     // Method to check if string2 is// obtained by string 1function isRotated(str1, str2){    if (str1.length != str2.length)        return false;             if (str1.length < 2)    {        return str1.localeCompare(str2);    }       let clock_rot = "";    let anticlock_rot = "";    let len = str2.length;       // Initialize string as anti-clockwise rotation    anticlock_rot = anticlock_rot +                    str2.substring(len - 2, len + 1) +                    str2.substring(0, len - 1) ;       // Initialize string as clock wise rotation    clock_rot = clock_rot +                str2.substring(2, str2.length - 2 + 1) +                str2.substring(0, 2 + 1);       // Check if any of them is equal to string1    return (str1.localeCompare(clock_rot) ||            str1.localeCompare(anticlock_rot));} // Driver codelet str1 = "geeks";let str2 = "eksge"; document.write(isRotated(str1, str2) ?                "Yes" : "No"); // This code is contributed by rag2127 </script>
Yes
Time Complexity : O(n) Auxiliary Space: O(n)
Exercise : Check if string2 is obtained by rotating string1 by k places
Method 2 – Without using any extra space: 
We could check directly if the string is rotated or not by comparing the two strings. 
Steps –
Check if the string is rotated in clockwise manner.Check if the string is rotated in anticlockwise manner. Return true if any one of the above is true
Check if the string is rotated in clockwise manner.
Check if the string is rotated in anticlockwise manner. 
Return true if any one of the above is true
We compare for clockwise and anticlockwise by using for loops and the modulo operator-
Note that – 
For clockwise – str1[i] == str2[(i + 2) % n]
For anticlockwise – str1[(i + 2) % n] == str2[i]
Here n is length of string 
Check using the above two conditions and the problem will be solved!
See the code for better understanding.
C++
// C++ code to find if string is rotated by 2 positions #include <iostream>using namespace std; bool isRotated(string str1, string str2){    // Your code here    // clockwise direction check    int n = str1.length();    bool clockwise = true, anticlockwise = true;    for (int i = 0; i < n; i++)    {        if (str1[i] != str2[(i + 2) % n])        {            clockwise = false; // not rotated clockwise            break;        }    }     for (int i = 0; i < n; i++)    {        if (str1[(i + 2) % n] != str2[i])        {            anticlockwise = false; // not rotated anticlockwise            break;        }    }     return clockwise or anticlockwise; // if any of both is true, return true}int main(){    string str1 = "geeks";    string str2 = "eksge";     isRotated(str1, str2) ? cout << "Yes"                          : cout << "No";    return 0;} //code contributed by Anshit Bansal
Yes
Time Complexity – O(n)Space Complexity – O(1)
This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 
shrikanth13
ukasp
piyush_1301
rajatmiglani1
rag2127
hasani
anshitbansal
hardikkoriintern
Accolite
Amazon
rotation
Strings
Accolite
Amazon
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Data Structure: Types, Classifications and Applications
Top 50 String Coding Problems for Interviews
Length of the longest substring without repeating characters
Convert string to char array in C++
Reverse words in a given string
Check whether two strings are anagram of each other
Print all the duplicates in the input string
Reverse string in Python (6 different ways)
Remove duplicates from a given string
Array of Strings in C++ - 5 Different Ways to Create