Practice › Strings
Longest Happy Prefix
Hard · Strings · Asked at Google, Amazon, Microsoft
A happy prefix is a non-empty prefix of the string that is also a suffix, but is not the whole string. Print the longest happy prefix, or EMPTY if there is none.
Input
A single line with the string (lowercase letters).
Output
The longest happy prefix, or EMPTY.
Constraints
- 1 ≤ length ≤ 10^5
This is exactly the KMP prefix function: pi[i] is the length of the longest proper prefix of s[0..i] that is also its suffix. The answer has length pi[n − 1]. Comparing every candidate length directly is O(n²).
Example 1
Input
level
Output
l
Example 2
Input
ababab
Output
abab
Hints
- Checking every length by comparing prefix and suffix is O(n²) on strings like "aaaa…".
- The KMP prefix function answers exactly this question for every prefix of s.
- pi[n − 1] is the length of the longest proper prefix of s that is also a suffix.
Approach
Build the prefix function: pi[i] = length of the longest proper border of s[0..i]. To compute pi[i], start from k = pi[i − 1] and fall back with k = pi[k − 1] while s[i] ≠ s[k]; if they match, k + 1. Each step of the fallback is paid for by an earlier increase, so the whole thing is O(n). Print the first pi[n − 1] characters, or EMPTY when it is 0.
Complexity: O(n) time · O(n) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
int n = s.size();
vector<int> pi(n, 0);
for (int i = 1; i < n; i++) {
int k = pi[i - 1];
while (k && s[i] != s[k]) k = pi[k - 1];
if (s[i] == s[k]) k++;
pi[i] = k;
}
cout << (pi[n - 1] ? s.substr(0, pi[n - 1]) : "EMPTY") << "\n";
return 0;
}Python solution
s = input().strip()
n = len(s)
pi = [0] * n
for i in range(1, n):
k = pi[i - 1]
while k and s[i] != s[k]:
k = pi[k - 1]
if s[i] == s[k]:
k += 1
pi[i] = k
print(s[: pi[-1]] if pi[-1] else "EMPTY")Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
String s = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
int n = s.length();
int[] pi = new int[n];
for (int i = 1; i < n; i++) {
int k = pi[i - 1];
while (k > 0 && s.charAt(i) != s.charAt(k)) k = pi[k - 1];
if (s.charAt(i) == s.charAt(k)) k++;
pi[i] = k;
}
System.out.println(pi[n - 1] > 0 ? s.substring(0, pi[n - 1]) : "EMPTY");
}
}