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
๐Ÿ” Pattern Detective Case: "ababab"a b a b a b๐ŸŽฏ EVIDENCE Aabab๐ŸŽฏ EVIDENCE Bababโœ… CASE SOLVED!Longest Happy Prefix: "abab"
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

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Space for the failure function array

n
2n
โšก 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
Asked in
Google 12 Facebook 8 Amazon 6 Microsoft 4
28.4K Views
Medium Frequency
~25 min Avg. Time
892 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