Problem Description
Given a string s, find the longest "happy prefix". A happy prefix is defined as a non-empty prefix which is also a suffix of s, excluding the string itself. If no such prefix exists, return an empty string.
Key Insights
- The problem can be solved efficiently by leveraging techniques used in string matching algorithms.
- A key method is to compute the prefix function (also known as pi array) from the KMP (Knuth-Morris-Pratt) algorithm.
- The value at the last index of the pi array corresponds to the length of the longest prefix that is also a suffix (excluding the whole string).
- An alternative approach is to use a rolling hash technique, but the KMP prefix function is more straightforward and has a linear time complexity.
Space and Time Complexity
Time Complexity: O(n), where n is the length of s
Space Complexity: O(n), for storing the prefix function
Solution
We use the KMP prefix function to solve this problem:
- Initialize an array pi of size n (length of s) with zeros.
- Iterate through the string from the second character, and update the pi array which keeps track of the longest proper prefix which is also a suffix for each substring ending at that index.
- The value at pi[n-1] gives the length of the longest happy prefix.
- Return the substring from the beginning of s up to that length. The algorithm ensures that we only traverse the string once with extra space proportional to n.