Input: ‘str’ = ‘ababcdabab’
Output: 'abab'
Explanation:
Here the prefix ‘abab’ is equal to the suffix ‘abab’. The length of the prefix is 4. There's no other prefix that has length > 4 and is also present as a suffix. Hence the answer is 'abab'.
The first line of input contains a string ‘str’ representing the input string.
Return a single integer representing the length of the largest prefix which is also a suffix. If there's no such string return an empty string.
You do not need to print anything. It has already been taken care of. Just implement the given function. '-1' will be printed for returned strings that are empty.
In this approach, we will check all the possible prefixes of the given string. Since we have to find the longest non-overlapping prefix, we will start from the prefix of ‘N/2’ length, where ‘N’ is the length of the string, and then we keep decreasing the prefix, length as long as it doesn’t match with the suffix of the same length.
Algorithm:
In this approach, we will create an ‘lps’ array, ‘lps[i]’, which will store the longest prefix which is also a suffix for the substring ‘str[0: i]’. We create a left and right pointer, where the left pointer points to the ending of the prefix and the right pointer will point to the current position.
If str[right] is equal to str[left] then we set lps[right] as lps[left] + 1, and increase the left pointer.
If they are not equal, then we know the prefix earlier is of length ‘str[left]’ therefore, we will move the left pointer to ‘str[left - 1]’, to check before the start of the current prefix.
Algorithm:
Ninja and Numbers
Longest Palindromic Substring
Cakes
1-3 Palindrome
Search Pattern (KMP - Algorithm)
Search Pattern (KMP - Algorithm)
Search Pattern (KMP - Algorithm)