![]() |
VOOZH | about |
Given two strings str1 and str2 and an integer d, the task is to check whether str2 can be obtained by rotating str1 by d places (either to the left or to the right).
Examples:
Input: str1 = "abcdefg", str2 = "cdefgab", d = 2
Output: Yes
Rotate str1 2 places to the left.Input: str1 = "abcdefg", str2 = "cdfdawb", d = 6
Output: No
Approach: An approach to solve the same problem has been discussed here. In this article, reversal algorithm is used to rotate the string to the left and to the right in O(n). If any one of the rotations of str1 is equal to str2 then print Yes else print No.
Below is the implementation of the above approach:
Yes
Time Complexity: O(n)
Approach: In this approach we use temp string which is long string with multiplicity of str1 by 2. If we want to rotate the string by d place then we slice the string from n places starting from d. Similarly we rotate in right, For right rotation we use d with value (length of str1) - d. If any one of the rotations of str1 is equal to str2 then print Yes else print No.
Below is the implementation of the above approach:
Output:
Yes
Time Complexity: O(n), where n is the size of the given string.
Please refer complete article on Check if a string can be obtained by rotating another string d places for more details!