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
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.
- Longest Common Prefix using Trie
- Longest Common Prefix Matching | Set-6
- Longest Common Prefix using Sorting
- Longest Common Prefix using Binary Search
- Longest Common Prefix using Linked List
- Longest Common Prefix using Divide and Conquer Algorithm
- Longest Common Prefix using Character by Character Matching
- Longest Common Prefix using Word by Word Matching
- Find the longest sub-string which is prefix, suffix and also present inside the string | Set 2
- Find the longest sub-string which is prefix, suffix and also present inside the string
- Longest prefix which is also suffix
- Longest prefix in a string with highest frequency
- Length of longest balanced parentheses prefix
- Print the longest palindromic prefix of a given string
- Longest Palindrome in a String formed by concatenating its prefix and suffix
- Longest Increasing Subsequence using Longest Common Subsequence Algorithm
- Longest Common Substring | DP-29
- Longest Common Subsequence | DP-4
- Print the longest common substring
- LCS (Longest Common Subsequence) of three strings
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.