DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

Longest Happy Prefix

A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).

Given a string s, return the longest happy prefix of s. Return an empty string "" if no such prefix exists.

Example 1:

Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".

Example 2:

Input: s = "ababab"
Output: "abab"
Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.


  • 1 <= s.length <= 105
  • s contains only lowercase English letters.


class Solution:
    def longestPrefix(self, s: str) -> str:
        M = len(s)
        lps = [0] * M
        l = 0
        i = 1
        while i < M:
            if s[i] == s[l]:
                l += 1
                lps[i] = l
                i += 1
                if l != 0:
                    l = lps[l-1]
                    lps[i] = 0
                    i += 1
        return s[:lps[-1]]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)