


Consider the two strings 'P' = "abfyg" and 'Q' = "gabfy"
If we cyclically rotate String 'P' to the right once. The resulting string P becomes "gabfy" which is equal to String 'Q'.
Therefore it is possible to convert String 'P' to String 'Q'.
The first line contains the String 'P'.
The second line contains the String 'Q'.
The only line contains 1 if String 'P' can be converted to String 'Q' by cyclically rotating it to the right any number of times, otherwise 0.
You do not need to print anything, it has already been taken care of. Just implement the given function.
The idea is to generate all the possible rotations of String P and compare each of them with String Q. To generate the next cyclic rotation of a string P from the current rotation we can move the last character of it to the first position while keeping the other characters unchanged.
This approach uses linear extra space but there is a way by which we can optimize the above method by which it will take constant extra space.
Let's take the String A = "abcd" having length N = 4.
Consider the above example, from which we can observe that the Jth character of the string which is formed by cyclically rotating String A I times is the (I+J)%(N)th character of the original string A having length 'N'.
Using this observation we can generate all the rotations without actually having to generate them thereby using constant extra spaces.
From the above example we can also conclude that for a string of length ‘N’ there are only N possible rotations as when the Nth rotation is performed the resulting string becomes equal to the original string and hence no more new rotations can be generated.
The idea is to concatenate String P with itself and find out whether String Q is present in the resulting string as a substring. Let res be the string which is formed by the concatenation of String P with itself. This approach works because all the N possible rotations of String P exist in the string res as a substring.
For example consider String A = "pqrr" having length N = 4.
The four possible rotations for the above string are "pqrr", "rpqr", "rrpq", "qrrp".
The string res which is formed by concatenating the string A with itself is "pqrrpqrr".
We can see that all the rotations of String A are a substring of string res.
To find whether the String Q is present in the string res as a substring we can use string matching algorithms like Knuth-Morris-Pratt algorithm, Boyer-Moore algorithm, Rabin-Karp algorithm.
In our implementation we will be using Knuth-Morris-Pratt algorithm.