You are given two string str1 and str2 of same length. In a single shift you can rotate one string (str2) by 1 element such that its 1st element becomes the last and second one becomes the first like “abcd” will change to “bcda” after one shift operation. You have to find the minimum shift operation required to get common prefix of maximum length from str1 and str2.
Input : str1 = "geeks", str2 = "dgeek" Output : Shift = 1, Prefix = geek Input : str1 = "practicegeeks", str2 = "coderpractice" Output : Shift = 5 Prefix = practice
Naive Approach : Shift second string one by one and keep track the length of longest prefix for each shift, there are total of n shifts and for each shift finding the length of common prefix will take O(n) time. Hence, overall time complexity for this approach is O(n^2).
Better Approach : If we will add second string at the end of itself that is str2 = str2 + str2 then there is no need of finding prefix for each shift separately. Now, after adding str2 to itself we have to only find the longest prefix of str1 present in str2 and the starting position of that prefix in str2 will give us the actual number of shift required. For finding longest prefix we can use KMP pattern search algorithm.
So, in this way our time-complexity will reduces to O(n) only.
Shift = 8 Prefix = geeksforgeeks
This article is attributed to GeeksforGeeks.org