Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Compute the minimum number of characters to add at the end of s so that it becomes a palindrome, using the KMP prefix function.

Problem: Compute the minimum number of characters to add at the end of s so that it becomes a palindrome, using the KMP prefix function.
def prefix(s):
    pi = [0] * len(s)
    for i in range(1, len(s)):
        k = pi[i - 1]
        while k and s[i] != s[k]:
            k = pi[k - 1]
        if s[i] == s[k]:
            k += 1
        pi[i] = k
    return pi
s = "abcbab"
t = s[::-1] + "#" + s
print(prefix("aabaaab")[-1], len(s) - prefix(t)[-1])
What is printed?
  1. A. 2 3
  2. B. 3 2
  3. C. 2 4
  4. D. 3 3

Correct answer: D. 3 3

pi of "aabaaab": [0,1,0,1,2,2,3] – the last value 3 is the longest proper prefix that is also a suffix ("aab"). For s = "abcbab", the prefix function of reverse(s) + '#' + s gives the longest palindromic suffix of s ("bab", length 3), so 6 − 3 = 3 characters must be appended. Prefix function is O(n).

More Coding Interview Problems questions

Exams that ask this topic