Check if a given string can be derived from another string by circularly rotating it. The rotation can be in a clockwise or anti-clockwise rotation.

For example,

Input:
 
X = ABCD
Y = DABC
 
Output: Yes
 
Y can be derived from X by right-rotating it by 1 unit

Practice this problem

For two given strings X and Y, a simple solution would be to check if the string Y is a substring of the string XX or not. If yes, they can be derived from each other. For example, consider string X = ABCD and Y = DABC.

XX = ABCD + ABCD = ABCDABCD

The string Y is clearly a substring of the string ABCDABCD.

The implementation can be seen here. This solution seems efficient, but uses O(n) extra space.

How to do this using O(1) space?

The idea is to in-place rotate the string X and check if it becomes equal to the string Y or not. We have to consider every possible rotation of a string X (i.e., rotation by 1 unit, 2 unit… till n-1 unit, where n is the length of the string X). Note that clockwise or anti-clockwise rotation doesn’t matter.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

Given strings can be derived from each other

Java


Download  Run Code

Output:

Given strings can be derived from each other

Python


Download  Run Code

Output:

Given strings can be derived from each other

The time complexity of the above solution is O(n2), where n is the length of the input strings, and doesn’t require any extra space.