ProgrammingHardTCS NQT · Accenture

The KMP prefix function pi[i] is the length of the longest proper prefix of s[0..i] that is also a suffix of it. For s = "abacabab" the procedure below fills pi. What is printed as the list of values pi[0..7] separated by spaces?

The KMP prefix function pi[i] is the length of the longest proper prefix of s[0..i] that is also a suffix of it. For s = "abacabab" the procedure below fills pi. What is printed as the list of values pi[0..7] separated by spaces?
pi[0] = 0; k = 0
for i = 1 to n - 1
    while k > 0 and s[i] != s[k]: k = pi[k-1]
    if s[i] == s[k] then k = k + 1
    pi[i] = k
end for
Print pi
  1. A. 0 0 1 0 1 2 3 2
  2. B. 0 0 1 1 1 2 3 3
  3. C. 0 1 2 1 2 3 4 3
  4. D. 0 0 0 0 0 0 0 0

Correct answer: A. 0 0 1 0 1 2 3 2

The prefix function of abacabab is 0 0 1 0 1 2 3 2, where pi[6] = 3 comes from the prefix aba. Dropping the fallback step, adding one to every value, and not updating pi at each index each change the output.

More Pseudocode and Code Tracing questions

Exams that ask this topic