You are given a string ‘str’.
Find the longest prefix in the string which is also a suffix of the string, excluding the string itself.
If there's no such string return an empty string "".
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.
aaaaabaa
"aa"
aa
For this test case, ‘str’ = ‘aaaaabaa’. Here the prefix ‘aa’ is equal to the suffix ‘aa’. The length of the prefix is 2. There's no other prefix with length > 2 which is also present as a suffix. Hence the answer is 'aa'.
aab
""
-1
Try to do this in O(n), where 'n' is the length of string 'str'.
1 <= |str| <= 10^6
All the characters of ‘str’ are lower case English alphabets.
Time Limit: 1 sec
Try by checking all the possible prefixes.
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:
O(N^2), Where N is the length of the string.
We iterate over all the prefixes and suffixes which will cost O(N/2) time, to compare each prefix to suffix will cost O(N) time. Hence the final time complexity is O(N^2)
O(N), Where N is the length of the string.
We are storing the prefix and suffix for each iteration of the loop which will take O(N) space. Hence the final space complexity is O(N).