Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: Find the longest proper prefix of s that is also a suffix (the 'happy prefix').

Problem: Find the longest proper prefix of s that is also a suffix (the 'happy prefix').
def happy(s):
    p = [0] * len(s); k = 0
    for i in range(1, len(s)):
        while k and s[i] != s[k]: k = p[k-1]
        if s[i] == s[k]: k += 1
        p[i] = k
    return s[:p[-1]]
print(happy("ababab"), happy("aabcaa"))
What is printed?
  1. A. abab aa
  2. B. ab aa
  3. C. abab a
  4. D. ababa aab

Correct answer: A. abab aa

The last KMP prefix-function value is the answer. 'ababab' has border 'abab' (overlapping is allowed); 'aabcaa' has border 'aa'.

More Coding Interview Problems questions

Exams that ask this topic