Related Articles

# A Program to check if strings are rotations of each other or not

• Difficulty Level : Easy
• Last Updated : 09 Sep, 2021

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 = str1.str1
2. If str2 is a substring of temp then str1 and str2 are
rotations of each other.

Example:
str1 = "ABACD"
str2 = "CDABA"

temp = str1.str1 = "ABACDABACD"
Since str2 is a substring of temp, str1 and str2 are
rotations of each other.```

## C++

 `// C++ program to check if two given strings``// are rotations of  each other``# include ``using` `namespace` `std;` `/* Function checks if passed strings (str1``   ``and str2) are rotations of each other */``bool` `areRotations(string str1, string str2)``{``   ``/* Check if sizes of two strings are same */``   ``if` `(str1.length() != str2.length())``        ``return` `false``;` `   ``string temp = str1 + str1;``  ``return` `(temp.find(str2) != string::npos);``}` `/* Driver program to test areRotations */``int` `main()``{``   ``string str1 = ``"AACD"``, str2 = ``"ACDA"``;``   ``if` `(areRotations(str1, str2))``     ``printf``(``"Strings are rotations of each other"``);``   ``else``      ``printf``(``"Strings are not rotations of each other"``);``   ``return` `0;``}`

## C

 `// C program to check if two given strings are rotations of``// each other``# include ``# include ``# include ` `/* Function checks if passed strings (str1 and str2)``   ``are rotations of each other */``int` `areRotations(``char` `*str1, ``char` `*str2)``{``  ``int` `size1   = ``strlen``(str1);``  ``int` `size2   = ``strlen``(str2);``  ``char` `*temp;``  ``void` `*ptr;` `  ``/* Check if sizes of two strings are same */``  ``if` `(size1 != size2)``     ``return` `0;` `  ``/* Create a temp string with value str1.str1 */``  ``temp   = (``char` `*)``malloc``(``sizeof``(``char``)*(size1*2 + 1));``  ``temp = ``''``;``  ``strcat``(temp, str1);``  ``strcat``(temp, str1);` `  ``/* Now check if str2 is a substring of temp */``  ``ptr = ``strstr``(temp, str2);` `  ``free``(temp); ``// Free dynamically allocated memory` `  ``/* strstr returns NULL if the second string is NOT a``    ``substring of first string */``  ``if` `(ptr != NULL)``    ``return` `1;``  ``else``    ``return` `0;``}` `/* Driver program to test areRotations */``int` `main()``{``    ``char` `*str1 = ``"AACD"``;``    ``char` `*str2 = ``"ACDA"``;` `    ``if` `(areRotations(str1, str2))``       ``printf``(``"Strings are rotations of each other"``);``    ``else``       ``printf``(``"Strings are not rotations of each other"``);` `    ``getchar``();``    ``return` `0;``}`

## Java

 `// Java program to check if two given strings are rotations of``// each other` `class` `StringRotation``{``    ``/* Function checks if passed strings (str1 and str2)``       ``are rotations of each other */``    ``static` `boolean` `areRotations(String str1, String str2)``    ``{``        ``// There lengths must be same and str2 must be``        ``// a substring of str1 concatenated with str1. ``        ``return` `(str1.length() == str2.length()) &&``               ``((str1 + str1).indexOf(str2) != -``1``);``    ``}``    ` `    ``// Driver method``    ``public` `static` `void` `main (String[] args)``    ``{``        ``String str1 = ``"AACD"``;``        ``String str2 = ``"ACDA"``;` `        ``if` `(areRotations(str1, str2))``            ``System.out.println(``"Strings are rotations of each other"``);``        ``else``            ``System.out.printf(``"Strings are not rotations of each other"``);``    ``}``}``// This code is contributed by  munjal`

## Python

 `# Python program to check if strings are rotations of``# each other or not` `# Function checks if passed strings (str1 and str2)``# are rotations of each other``def` `areRotations(string1, string2):``    ``size1 ``=` `len``(string1)``    ``size2 ``=` `len``(string2)``    ``temp ``=` `''` `    ``# Check if sizes of two strings are same``    ``if` `size1 !``=` `size2:``        ``return` `0` `    ``# Create a temp string with value str1.str1``    ``temp ``=` `string1 ``+` `string1` `    ``# Now check if str2 is a substring of temp``    ``# string.count returns the number of occurrences of``    ``# the second string in temp``    ``if` `(temp.count(string2)> ``0``):``        ``return` `1``    ``else``:``        ``return` `0` `# Driver program to test the above function``string1 ``=` `"AACD"``string2 ``=` `"ACDA"` `if` `areRotations(string1, string2):``    ``print` `"Strings are rotations of each other"``else``:``    ``print` `"Strings are not rotations of each other"` `# This code is contributed by Bhavya Jain`

## C#

 `// C# program to check if two given strings``// are rotations of each other``using` `System;` `class` `GFG {``    ` `    ``/* Function checks if passed strings``    ``(str1 and str2) are rotations of``    ``each other */``    ``static` `bool` `areRotations(String str1,``                                 ``String str2)``    ``{``        ` `        ``// There lengths must be same and``        ``// str2 must be a substring of``        ``// str1 concatenated with str1.``        ``return` `(str1.Length == str2.Length )``             ``&& ((str1 + str1).IndexOf(str2)``                                     ``!= -1);``    ``}``    ` `    ``// Driver method``    ``public` `static` `void` `Main ()``    ``{``        ``String str1 = ``"FGABCDE"``;``        ``String str2 = ``"ABCDEFG"``;` `        ``if` `(areRotations(str1, str2))``            ``Console.Write(``"Strings are"``            ``+ ``" rotation s of each other"``);``        ``else``            ``Console.Write(``"Strings are "``           ``+ ``"not rotations of each other"``);``    ``}``}` `// This code is contributed by nitin mittal.`

## PHP

 ` 0)``{``        ``return` `true;``}``else``{``    ``return` `false;``}``}` `// Driver code``\$str1` `= ``"AACD"``;``\$str2` `= ``"ACDA"``;``if` `(areRotations(``\$str1``, ``\$str2``))``{``    ``echo` `"Strings are rotations "``.``                  ``"of each other"``;``}``else``{``    ``echo` `"Strings are not "` `.``         ``"rotations of each other"` `;``}` `// This code is contributed``// by Shivi_Aggarwal.``?>`
Output
`Strings are rotations of each other`

Method 2(Using STL):

Algorithm :

1. If the size of both the strings is not equal, then it can never be possible.

2. Push the original string into a queue q1.

3. Push the string to be checked inside another queue q2.

4. Keep popping q2‘s and pushing it back into it till the number of such operations are less than the size of the string.

5. If q2 becomes equal to q1 at any point during these operations, it is possible. Else not.

## C++

 `#include ``using` `namespace` `std;``bool` `check_rotation(string s, string goal)``{``    ``if` `(s.size() != goal.size())``        ``;``    ``queue<``char``> q1;``    ``for` `(``int` `i = 0; i < s.size(); i++) {``        ``q1.push(s[i]);``    ``}``    ``queue<``char``> q2;``    ``for` `(``int` `i = 0; i < goal.size(); i++) {``        ``q2.push(goal[i]);``    ``}``    ``int` `k = goal.size();``    ``while` `(k--) {``        ``char` `ch = q2.front();``        ``q2.pop();``        ``q2.push(ch);``        ``if` `(q2 == q1)``            ``return` `true``;``    ``}``    ``return` `false``;``}``int` `main()``{``    ``string s1 = ``"ABCD"``;``    ``string s2 = ``"CDAB"``;``    ``if` `(check_rotation(s1, s2))``        ``cout << s2 << ``" is a rotated form of "` `<< s1``             ``<< endl;``    ``else``        ``cout << s2 << ``" is not a rotated form of "` `<< s1``             ``<< endl;``    ``string s3 = ``"ACBD"``;``    ``if` `(check_rotation(s1, s3))``        ``cout << s3 << ``" is a rotated form of "` `<< s1``             ``<< endl;``    ``else``        ``cout << s3 << ``" is not a rotated form of "` `<< s1``             ``<< endl;``    ``return` `0;``}`
Output
```CDAB is a rotated form of ABCD
ACBD is not a rotated form of ABCD```

Library Functions Used:
strstr:
strstr finds a sub-string within a string.
Prototype: char * strstr(const char *s1, const char *s2);
See http://www.lix.polytechnique.fr/Labo/Leo.Liberti/public/computing/prog/c/C/MAN/strstr.htm for more details
strcat:
strncat concatenate two strings
Prototype: char *strcat(char *dest, const char *src);
See http://www.lix.polytechnique.fr/Labo/Leo.Liberti/public/computing/prog/c/C/MAN/strcat.htm for more details

Time Complexity: Time complexity of this problem depends on the implementation of strstr function.
If the implementation of strstr is done using KMP matcher then complexity of the above program is (-)(n1 + n2) where n1 and n2 are lengths of strings. KMP matcher takes (-)(n) time to find a substring in a string of length n where length of substring is assumed to be smaller than the string.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up