Given a string str, the task is to find the longest prefix which is also the suffix of the given string. The prefix and suffix should not overlap. If no such prefix exists then print -1.
Input: str = “aabcdaabc”
The string “aabc” is the longest
prefix which is also suffix.
Input: str = “aaaa”
Approach: The idea is to use pre-processing algorithm of KMP search. In this algorithm, we build lps array which stores the following values:
lps[i] = the longest proper prefix of pat[0..i]
which is also a suffix of pat[0..i].
We get the length using the above approach, then print the same number of characters from the front which is our answer.
Below is the implementation of the above approach:
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.
- Find the longest sub-string which is prefix, suffix and also present inside the string | Set 2
- Longest palindromic string formed by concatenation of prefix and suffix of a string
- Find the longest sub-string which is prefix, suffix and also present inside the string
- Longest Palindrome in a String formed by concatenating its prefix and suffix
- Print the longest palindromic prefix of a given string
- String from prefix and suffix of given two strings
- Check if suffix and prefix of a string are palindromes
- Longest string in an array which matches with prefix of the given string
- Longest string which is prefix string of at least two strings
- Longest prefix which is also suffix
- Longest prefix in a string with highest frequency
- Find the longest common prefix between two strings after performing swaps on second string
- Python program to print the substrings that are prefix of the given string
- Minimize length of prefix of string S containing all characters of another string T
- Sub-strings of a string that are prefix of the same string
- Find length of longest subsequence of one string which is substring of another string
- Longest sub string of 0's in a binary string which is repeated K times
- Check if a string is suffix of another
- Print all possible combinations of the string by replacing '$' with any other digit from the string
- Count of distinct substrings of a string using Suffix Array
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.