Longest Happy Prefix

Hard Arrays & Hashing String Matching (KMP) Original on LeetCode

Reported atAmazon

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^5
  • s contains 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.

00:00
Testcase

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.

ApproachTimeSpace
Brute force (try every length)O(n²)O(1)
Optimal (KMP prefix function)O(n)O(n)

1Brute force (try every length)

TimeO(n²)Up to n - 1 lengths, each compared in up to O(n) character steps (strings like "aaaa…ab" force long comparisons).
SpaceO(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.

  1. For L = n - 1 down to 1:
  2. Compare s[i] with s[n - L + i] for i = 0 … L - 1.
  3. If all match, return s.substring(0, L).
  4. 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 "";
    }
}

2Optimal (KMP prefix function)

TimeO(n)len grows by at most 1 per step and every fallback shrinks it, so the total number of fallbacks is at most n.
SpaceO(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.

  1. lps[0] = 0, len = 0 (length of the current border).
  2. For i = 1 … n - 1: while len > 0 and s[i] != s[len], set len = lps[len - 1].
  3. If s[i] == s[len], increase len.
  4. lps[i] = len.
  5. 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]);
    }
}

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 "".