Data Structures & AlgorithmsVery hardGoogle · Flipkart interview

Problem: Find the shortest palindrome obtainable by adding characters only in FRONT of s, using the KMP failure function of s + '#' + reverse(s).

Problem: Find the shortest palindrome obtainable by adding characters only in FRONT of s, using the KMP failure function of s + '#' + reverse(s).
def shortest(s):
    t = s + "#" + s[::-1]; p = [0] * len(t)
    for i in range(1, len(t)):
        k = p[i-1]
        while k and t[i] != t[k]: k = p[k-1]
        if t[i] == t[k]: k += 1
        p[i] = k
    return s[p[-1]:][::-1] + s
print(shortest("aacecaaa"), shortest("abcd"))
What is printed?
  1. A. aaacecaaaa dcbabcd
  2. B. aacecaaa dcbabcd
  3. C. aaacecaaa dcbabcd
  4. D. aaacecaaa dcbaabcd

Correct answer: C. aaacecaaa dcbabcd

The last failure value is the length of the longest palindromic PREFIX of s: 'aacecaa' (7) for 'aacecaaa', so only the final 'a' is mirrored in front. For 'abcd' only 'a' is a palindromic prefix, so 'dcb' is prepended. The '#' stops matches from crossing the middle.

More Coding Interview Problems questions

Exams that ask this topic