Problem Description
A string is called a happy prefix if it is a non-empty prefix which is also a suffix (excluding itself). Given a string s
, return the longest happy prefix of s
. Return an empty string ""
if no such prefix exists.
Key Insights
- A happy prefix must be a non-empty substring that can be found at both the start and end of the string.
- The longest happy prefix can be found by examining the overlaps between the prefix and suffix of the string.
- Efficient algorithms such as KMP (Knuth-Morris-Pratt) can be utilized to find the longest prefix which is also a suffix.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(n)
Solution
To solve the problem of finding the longest happy prefix, we can employ the KMP algorithm's preprocessing step. The algorithm builds a longest prefix-suffix (LPS) array that helps in identifying the longest prefix that is also a suffix efficiently.
- Create an array
lps
wherelps[i]
represents the length of the longest proper prefix which is also a suffix for the substrings[0..i]
. - Iterate through the string to fill the
lps
array. - The value
lps[n-1]
(where n is the length of the string) gives us the length of the longest happy prefix. - Return the substring of
s
from the start with length equal tolps[n-1]
.