Data Structures & AlgorithmsVery hardICPC regional · string round

Problem: What is the KMP prefix-function array pi for the string 'ababaca'?

Problem: What is the KMP prefix-function array pi for the string 'ababaca'?
s = 'ababaca'
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
print(pi)
What is printed?
  1. A. [0, 0, 1, 2, 3, 1, 0]
  2. B. [0, 0, 1, 2, 3, 0, 1]
  3. C. [0, 1, 0, 1, 2, 0, 1]
  4. D. [0, 0, 1, 2, 2, 0, 1]

Correct answer: B. [0, 0, 1, 2, 3, 0, 1]

pi[i] is the longest proper border of s[0..i]. At index 4 ('ababa') the border 'aba' has length 3, and at index 6 the border is 'a' of length 1.

More Coding Interview Problems questions

Exams that ask this topic