Check if a string can be obtained by rotating another string d places
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).
Input: str1 = “abcdefg”, str2 = “cdefgab”, d = 2
Rotate str1 2 places to the left.
Input: str1 = “abcdefg”, str2 = “cdfdawb”, d = 6
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:
Time Complexity: O(n)
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.