Longest Happy Prefix - Problem
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.
Note: A prefix must be different from the string itself - we cannot use the entire string as both prefix and suffix.
Input & Output
Example 1 — Basic Case
$
Input:
s = "level"
›
Output:
"l"
💡 Note:
The longest happy prefix is "l" because it appears at both the beginning and end of "level". Other prefixes like "le", "lev", "leve" don't match their corresponding suffixes.
Example 2 — No Happy Prefix
$
Input:
s = "ababab"
›
Output:
"abab"
💡 Note:
The prefix "abab" also appears as suffix "abab" in "ababab". This is the longest such match.
Example 3 — No Match
$
Input:
s = "leetcodeleet"
›
Output:
"leet"
💡 Note:
The prefix "leet" matches the suffix "leet" in "leetcodeleet". No longer prefix has this property.
Constraints
- 1 ≤ s.length ≤ 105
- s consists of lowercase English letters.
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
Given string with potential prefix-suffix matches
2
Pattern Recognition
Find longest prefix that equals some suffix
3
Output Result
Return the matching prefix string
Key Takeaway
🎯 Key Insight: Use KMP failure function to find longest proper prefix that's also suffix in O(n) time
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code