Zepruv › Coding problems

Longest Happy Prefix

Hard · String, Rolling Hash, String Matching, Hash Function

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"

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"

"abab" is the largest prefix which is also suffix. They can overlap in the original string.

Constraints

Starter code (python)

class Solution(object):
    def longestPrefix(self, s):
        """
        :type s: str
        :rtype: str
        """
        

Related problems

Previous: Construct K Palindrome Strings · Next: Find Lucky Integer in an Array · All problems

Zepruv is a technical interview practice platform. Read any problem for free; sign in to run your code, submit and keep your progress.