Longest Happy Prefix Problem
Description
LeetCode Problem 1392.
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.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".
Example 2:
Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.
Constraints:
1 <= s.length <= 10^5scontains only lowercase English letters.
Solution
Approach: KMP Prefix Function
A happy prefix is what the KMP algorithm calls a border: a proper prefix that is also a suffix. The KMP prefix function computes it for every prefix of the string: pi[i] is the length of the longest border of s[0..i]. The answer is then s[0 : pi[n - 1]].
Build pi from left to right while keeping k, the length of the current border:
- If
s[i] == s[k], the border can grow by one character:k += 1. - Otherwise, fall back to the next shorter border,
k = pi[k - 1], and try again; whenkreaches 0 there is nothing left to extend.
The fallback works because any border of s[0..i] minus its last character is a border of s[0..i-1], and the borders of a string are exactly its longest border, the longest border of that, and so on.
Borders may overlap, as in Example 2 where "abab" is both a prefix and a suffix of "ababab"; the prefix function handles this naturally. Comparing every candidate length directly would be O(n2) for a string like "aaa...a"; string hashing is the other linear-time approach, but it relies on avoiding collisions.
Complexity: O(n) time, since k grows at most n times in total and each fallback shrinks it, and O(n) space for pi.
class Solution:
def longestPrefix(self, s: str) -> str:
n = len(s)
# pi[i] = length of the longest proper prefix of s[:i + 1] that is also its suffix
pi = [0] * n
k = 0
for i in range(1, n):
while k > 0 and s[i] != s[k]:
k = pi[k - 1] # fall back to the next shorter border
if s[i] == s[k]:
k += 1
pi[i] = k
return s[:pi[-1]]