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:
Example 2:
Example 3:
Example 4:
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