Longest Happy Prefix
Longest Happy Prefix is a hard arrays & hashing problem solved with the string matching (kmp) pattern.
The best approach, optimal (kmp prefix function), runs in O(n) time and O(n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (try every length) up.
Problem
A happy prefix of a string is a non-empty prefix that is also a suffix of the same string, but is not the whole string itself.
Given a string s, return its longest happy prefix. If s has none, return the empty string "".
Examples
Example 1
- Input
s = "abcab"- Output
"ab"- Why
- "ab" starts the string and also ends it. The longer candidates "abc" and "abca" do not appear at the end.
Example 2
- Input
s = "zzzz"- Output
"zzz"- Why
- A happy prefix may overlap with the matching suffix: "zzz" is both s[0..2] and s[1..3].
Example 3
- Input
s = "rocket"- Output
""- Why
- No non-empty proper prefix is also a suffix.
Constraints
1 <= s.length <= 10^5scontains only lowercase English letters.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 14 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (try every length) | O(n²) | O(1) |
| Optimal (KMP prefix function) | O(n) | O(n) |
1Brute force (try every length)
O(n²)Up to n - 1 lengths, each compared in up to O(n) character steps (strings like "aaaa…ab" force long comparisons).O(1)Only indices; the returned substring is the output.Try lengths from n - 1 down to 1. For each length L, compare the first L characters with the last L characters. The first match is the longest happy prefix.
- For L = n - 1 down to 1:
- Compare s[i] with s[n - L + i] for i = 0 … L - 1.
- If all match, return s.substring(0, L).
- If no length matches, return "".
class Solution {
public String longestPrefix(String s) {
int n = s.length();
for (int len = n - 1; len >= 1; len--) {
boolean ok = true;
for (int i = 0; i < len; i++) {
if (s.charAt(i) != s.charAt(n - len + i)) {
ok = false;
break;
}
}
if (ok) {
return s.substring(0, len);
}
}
return "";
}
}class Solution:
def longestPrefix(self, s: str) -> str:
n = len(s)
for length in range(n - 1, 0, -1):
ok = True
for i in range(length):
if s[i] != s[n - length + i]:
ok = False
break
if ok:
return s[:length]
return ""class Solution {
public:
string longestPrefix(string s) {
int n = s.size();
for (int len = n - 1; len >= 1; len--) {
bool ok = true;
for (int i = 0; i < len; i++) {
if (s[i] != s[n - len + i]) {
ok = false;
break;
}
}
if (ok) {
return s.substr(0, len);
}
}
return "";
}
};function longestPrefix(s) {
const n = s.length;
for (let len = n - 1; len >= 1; len--) {
let ok = true;
for (let i = 0; i < len; i++) {
if (s[i] !== s[n - len + i]) {
ok = false;
break;
}
}
if (ok) {
return s.substring(0, len);
}
}
return "";
}2Optimal (KMP prefix function)
O(n)len grows by at most 1 per step and every fallback shrinks it, so the total number of fallbacks is at most n.O(n)The lps array has n entries.Build the KMP prefix function: lps[i] is the length of the longest proper prefix of s[0..i] that is also a suffix of it. While extending, if the next character does not continue the current border, fall back to the next shorter border lps[len - 1] instead of starting over. lps[n - 1] is the answer's length.
- lps[0] = 0, len = 0 (length of the current border).
- For i = 1 … n - 1: while len > 0 and s[i] != s[len], set len = lps[len - 1].
- If s[i] == s[len], increase len.
- lps[i] = len.
- Return s.substring(0, lps[n - 1]).
class Solution {
public String longestPrefix(String s) {
int n = s.length();
int[] lps = new int[n];
int len = 0;
for (int i = 1; i < n; i++) {
while (len > 0 && s.charAt(i) != s.charAt(len)) {
len = lps[len - 1];
}
if (s.charAt(i) == s.charAt(len)) {
len++;
}
lps[i] = len;
}
return s.substring(0, lps[n - 1]);
}
}class Solution:
def longestPrefix(self, s: str) -> str:
n = len(s)
lps = [0] * n
length = 0
for i in range(1, n):
while length > 0 and s[i] != s[length]:
length = lps[length - 1]
if s[i] == s[length]:
length += 1
lps[i] = length
return s[:lps[n - 1]]class Solution {
public:
string longestPrefix(string s) {
int n = s.size();
vector<int> lps(n, 0);
int len = 0;
for (int i = 1; i < n; i++) {
while (len > 0 && s[i] != s[len]) {
len = lps[len - 1];
}
if (s[i] == s[len]) {
len++;
}
lps[i] = len;
}
return s.substr(0, lps[n - 1]);
}
};function longestPrefix(s) {
const n = s.length;
const lps = new Array(n).fill(0);
let len = 0;
for (let i = 1; i < n; i++) {
while (len > 0 && s[i] !== s[len]) {
len = lps[len - 1];
}
if (s[i] === s[len]) {
len++;
}
lps[i] = len;
}
return s.substring(0, lps[n - 1]);
}Edge cases to test
- A single character: the only proper prefix is empty, so return ""
- All characters equal: the answer is s without its last character
- Prefix and suffix that overlap, like "abababa" -> "ababa"
- The first and last letters differ, so the answer is immediately ""
Hints
Hint 1
A happy prefix of length L means s[0..L-1] equals s[n-L..n-1]. Checking every L directly is quadratic.
Hint 2
The prefix function from KMP stores, for every position, the length of the longest proper prefix that is also a suffix of s[0..i].
Hint 3
The value of the prefix function at the last index is exactly the length you want.
FAQ
What is the best time complexity for Longest Happy Prefix?
Optimal (KMP prefix function) runs in O(n) time and O(n) extra space. len grows by at most 1 per step and every fallback shrinks it, so the total number of fallbacks is at most n.
Which pattern does Longest Happy Prefix use?
It is a arrays & hashing problem that uses the string matching (kmp) pattern. Other problems with the same pattern: Find the Index of the First Occurrence in a String.
Is there a brute force solution for Longest Happy Prefix?
Yes. Brute force (try every length) takes O(n²) time and O(1) space. Try lengths from n - 1 down to 1.
Which edge cases should I test for Longest Happy Prefix?
A single character: the only proper prefix is empty, so return ""; All characters equal: the answer is s without its last character; Prefix and suffix that overlap, like "abababa" - "ababa"; The first and last letters differ, so the answer is immediately "".