Given a string str. The task is to find the longest sub-string which is a prefix, a suffix and a sub-string of the given string, str. If no such string exists then print -1.
Input: str = “fixprefixsuffix”
“fix” is a prefix, suffix and present inside in the string too.
Input: str = “aaaa”
“aa” is a prefix, suffix and present inside the string.
Approach: Let us calculate the longest prefix suffix for all prefixes of string. longest prefix suffix lps[i] is maximal length of prefix that also is suffix of substring [0…i]. More about longest prefix suffix you can see in a description of kmp algorithm.
The first of possible answers is a prefix of length lps[n-1]. If lps[n-1] = 0, there is no solution. For checking the first possible answer you should iterate over lps[i]. If at least one of them equal to lps[n-1] (but not n-1th, of course) – you found the answer. The second possible answer is a prefix of length lps[lps[n-1]-1]. If lps[lps[n-1]-1] = 0, you also have no solution. Otherwise, you can be sure that the answer already found. This substring is a prefix and a suffix of our string. Also, it is a suffix of a prefix with length lps[n-1] that places inside of all string. This solution works in O(n).
Below is the implementation of the above approach:
- Print the longest prefix of the given string which is also the suffix of the same string
- Longest prefix which is also suffix
- Suffix Tree Application 6 - Longest Palindromic Substring
- Find length of longest subsequence of one string which is substring of another string
- Find the longest substring with k unique characters in a given string
- String from prefix and suffix of given two strings
- Check if suffix and prefix of a string are palindromes
- Python | Check if a Substring is Present in a Given String
- Find index i such that prefix of S1 and suffix of S2 till i form a palindrome when concatenated
- Longest string in an array which matches with prefix of the given string
- Number of Positions to partition the string such that atleast m characters with same frequency are present in each substring
- Find if a given string can be represented from a substring by iterating the substring “n” times
- Longest substring of only 4's from the first N characters of the infinite string
- Longest substring of 0s in a string formed by k concatenations
- Find minimum shift for longest common prefix
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.