Skip to problem
←

Longest Happy Prefix

Hard 0 attempts

Given a string s, return its longest happy prefix: a nonempty prefix that is also a suffix, but is shorter than the whole string. Return "" if no such prefix exists.

The prefix and suffix may overlap. For "ababab", the prefix at indices 0–3 and suffix at indices 2–5 are both "abab", so return "abab". For "aaaa", return "aaa"; returning the entire string is not allowed.

A one-character string always returns "".

Function contract

Implement longestPrefix(s). Receive a nonempty string of lowercase English letters.

Output: Return the longest nonempty proper prefix that is also a suffix, or "" if none exists.

Example 1

Input
s = "level"
Output
"l"

Example 2

Input
s = "ababab"
Output
"abab"
Constraints
  • 1 <= s.length <= 10^5
  • s contains only lowercase English letters

Approach: KMP Failure Function

This is directly solved by the KMP algorithm's LPS (Longest Proper Prefix which is also Suffix) array. Build the LPS array for the entire string. At a mismatch, fall back to lps[len - 1] to try the next shorter border without rescanning characters. The last entry gives the answer length. Because every entry describes a proper prefix, the whole string is excluded while overlapping occurrences remain allowed.

javascript
function longestPrefix(s) {
  const n = s.length;
  const lps = new Array(n).fill(0);
  let len = 0;
  let i = 1;

  while (i < n) {
    if (s[i] === s[len]) {
      len++;
      lps[i] = len;
      i++;
    } else if (len > 0) {
      len = lps[len - 1];
    } else {
      i++;
    }
  }
  return s.substring(0, lps[n - 1]);
}

Time Complexity: O(n)

Space Complexity: O(n) for the LPS array

Loading discussion…

Saved in this browser only. Private to you.

JavaScript