Problem
A string is called a happy prefix if 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.
Examples
Example 1:
| |
Example 2:
| |
Solution
Method 1 - Using KMP
To solve this problem, we can use the concept of the KMP (Knuth-Morris-Pratt) algorithm’s prefix function, also known as the pi function. The pi function for a string provides the length of the longest proper prefix which is also a suffix for every substring ending at each index.
Here is the approach:
- Compute the KMP prefix function for the given string
s. - The value at the last index of the pi array will give us the length of the longest happy prefix.
- Extract the substring from the start of
sup to this length.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n), as the KMP prefix function itself is computed inO(n)time, wherenis the length of the strings. - 🧺 Space complexity:
O(n), mainly for storing the pi array.