Longest Happy Prefix
Pattern: Pattern matching
A happy prefix is a proper prefix that is also a suffix, a border. The last value of the KMP prefix function is the length of the longest one.
The problem
A happy prefix of a string is a non-empty prefix that is also a suffix, but not the whole string. Return the longest
happy prefix of s, or "" if there is none. For example, "level" gives "l" and "ababab" gives "abab".
The function name longestPrefix matches LeetCode. Use the link above for the exact statement and limits.
Think first
- Can a happy prefix overlap with the matching suffix? Look at
"ababab". - Checking every length from longest to shortest, what does each check cost?
- Which table from pattern matching stores exactly this for every prefix?
Hints
Brute force, and why it fails
For each length k from n - 1 down to 1, compare the prefix and suffix of length k: O(n²). The prefix function does
it in O(n).
The key insight
The prefix function is built from shorter borders: when the next character fails to extend a border, the next candidate is the border of that border. That is why it runs in linear time.
Dry run
| lps | 0 0 |
|---|
s = ababab. lps[i] is the longest proper prefix of s[0..i] that is also its suffix. lps[0] is 0, and b gives 0 too.
The plan
lps = n zeros, len = 0, i = 1
while i < n:
if s[i] == s[len]: len = len + 1; lps[i] = len; i = i + 1
else if len > 0: len = lps[len - 1]
else: i = i + 1
return s[0 .. lps[n - 1] - 1]
Complexity
- Time
O(n)- Space
O(n)
len rises by at most one per step of i and every fall makes it smaller, so the total work is linear. lps takes
O(n).
Edge cases
- One character:
"". - No border, as in
"abc":"". - All equal, as in
"aaaa":"aaa".
I've built my logic, show the code
Java
class Solution {
public String longestPrefix(String s) {
int n = s.length();
int[] lps = new int[n]; // lps[i]: longest proper prefix of s[0..i] that is also its suffix
for (int i = 1, len = 0; i < n; ) {
if (s.charAt(i) == s.charAt(len)) lps[i++] = ++len;
else if (len > 0) len = lps[len - 1]; // try the next shorter border
else lps[i++] = 0;
}
return s.substring(0, lps[n - 1]);
}
}C++
class Solution {
public:
string longestPrefix(string s) {
int n = static_cast<int>(s.size());
vector<int> lps(n, 0); // lps[i]: longest proper prefix of s[0..i] that is also its suffix
for (int i = 1, len = 0; i < n; ) {
if (s[i] == s[len]) lps[i++] = ++len;
else if (len > 0) len = lps[len - 1]; // try the next shorter border
else lps[i++] = 0;
}
return s.substr(0, lps[n - 1]);
}
};Python
class Solution:
def longestPrefix(self, s: str) -> str:
lps = [0] * len(s) # lps[i]: longest proper prefix of s[:i+1] that is also its suffix
i, length = 1, 0
while i < len(s):
if s[i] == s[length]:
length += 1
lps[i] = length
i += 1
elif length > 0:
length = lps[length - 1] # try the next shorter border
else:
i += 1
return s[:lps[-1]]Common mistakes
- Returning the whole string, which is not a proper prefix.
- Using
len = lps[len]on a mismatch instead oflps[len - 1]. - Resetting
lento 0 on every mismatch, which misses shorter borders.