27. Longest Happy Prefix (imp)
Longest Prefix Suffix
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.Example 3:
Input: s = "leetcodeleet"
Output: "leet"Example 4:
Input: s = "a"
Output: ""Solution: (Brute Force)
Checking for all prefix which are present in suffix.
Solution: (Rolling hash)
Approach:
Hash for string:
For the string of i size, the hash is: s[0] * 26 ^ (i - 1) + s[1] * 26 ^ (i -2) + ... + s[i - 2] * 26 + s[i - 1].
Computing Prefix hash:
we will multiply the previous value by 26 and add a new letter.
"a", hash[0]: a "ab", hash[1]: a*26 + b, or hash[0] * 26 + b "abc", hash[2]: a * 26 * 26 + b * 26 + c, or hash[1] *26 + c.
Computing Suffix hash:
we add a new letter multiplied by 26 ^ (i - 1)
Time Complexity: O(n)
Last updated
Was this helpful?