Data Structures & AlgorithmsVery hardProduct Company SDE · ICPC regional

Compute the sum of the prefix-function (KMP failure) array of the string "abacabab", where pi[i] is the length of the longest proper prefix of s[0..i] that is also a suffix of it.

Compute the sum of the prefix-function (KMP failure) array of the string "abacabab", where pi[i] is the length of the longest proper prefix of s[0..i] that is also a suffix of it.
s="abacabab"
pi=[0]*len(s)
for i in range(1,len(s)):
    j=pi[i-1]
    while j>0 and s[i]!=s[j]: j=pi[j-1]
    if s[i]==s[j]: j+=1
    pi[i]=j
print(sum(pi))
What is printed?
  1. A. 7
  2. B. 9
  3. C. 6
  4. D. 3

Correct answer: B. 9

The failure function falls back through earlier borders with pi[j-1] rather than jumping to zero. Dropping the fallback loses shorter borders, using the reversed string changes every border, and the maximum is a different statistic from the sum.

More Coding Interview Problems questions

Exams that ask this topic