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?- A. aaacecaaaa dcbabcd
- B. aacecaaa dcbabcd
- C. aaacecaaa dcbabcd
- 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
- Problem: Is s made of one substring repeated two or more times? Trick: check whether s occurs in (s + s) with the first and last…
- Problem: Delete the fewest characters so that no two letters have the same (nonzero) frequency. python from collections import Counter def…
- Problem: An array of n + 1 integers holds values 1..n with exactly one value repeated (possibly several times). Find it in O(1) extra…
- Problem: Find all values appearing more than ⌊n/3⌋ times with the extended Boyer–Moore vote (two candidates), then verify. python def…
- Find the bug: Boyer–Moore majority vote is used WITHOUT the verification pass on an array that may have no majority. python def…
- A 'shuffle' swaps each position i with a position chosen uniformly from the WHOLE array (0..n−1), for i = 0..n−1. Why is this not a…