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
Longest Happy Prefix: Find Prefix That's Also SuffixInput: "level"levelPREFIXSUFFIX"l" = "l" ✓ Match!Try other lengths:"le" ≠ "el" ✗"lev" ≠ "vel" ✗"leve" ≠ "evel" ✗Output: "l"
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
Asked in
Facebook 15 Google 12 Amazon 8
23.4K Views
Medium Frequency
~25 min Avg. Time
987 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen