Longest Happy Prefix - Problem
Imagine a string that has a special property: its beginning and end share the same pattern! ๐ญ
A "happy prefix" is a non-empty substring that appears at both the beginning (prefix) and end (suffix) of a string, but is not the entire string itself.
Your Mission: Given a string s, find the longest happy prefix and return it. If no such prefix exists, return an empty string "".
Example: In the string "ababab", the substring "abab" appears at both the beginning and end, making it a happy prefix!
Input & Output
example_1.py โ Basic Happy Prefix
$
Input:
s = "level"
โบ
Output:
"l"
๐ก Note:
The only happy prefix is "l" which appears at both beginning and end. Other prefixes like "le" don't match their corresponding suffixes.
example_2.py โ Longer Happy Prefix
$
Input:
s = "ababab"
โบ
Output:
"abab"
๐ก Note:
The longest happy prefix is "abab". Other happy prefixes include "ab" and "abab", but "abab" is the longest.
example_3.py โ No Happy Prefix
$
Input:
s = "leetcodeleet"
โบ
Output:
"leet"
๐ก Note:
The string starts and ends with "leet", making it the longest happy prefix.
Visualization
Tap to expand
Understanding the Visualization
1
Examine the Evidence
Look at the string and identify potential patterns
2
Check for Matches
Compare patterns from start with patterns at the end
3
Find the Longest
Among all matches, identify the longest one
Key Takeaway
๐ฏ Key Insight: The KMP failure function is perfectly designed for this problem - it computes exactly what we need: the longest proper prefix that is also a suffix!
Time & Space Complexity
Time Complexity
O(n)
Single pass to build KMP failure function
โ Linear Growth
Space Complexity
O(n)
Space for the failure function array
โก Linearithmic Space
Constraints
- 1 โค s.length โค 105
- s consists of lowercase English letters only
- Happy prefix must be non-empty and not equal to the entire string
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code