Data Structures & AlgorithmsVery hardGoogle · Flipkart interview

Problem: Compute the KMP prefix function (pi[i] = length of the longest proper prefix of s[0..i] that is also its suffix).

Problem: Compute the KMP prefix function (pi[i] = length of the longest proper prefix of s[0..i] that is also its suffix).
def pi(s):
    p = [0] * len(s)
    for i in range(1, len(s)):
        k = p[i-1]
        while k and s[i] != s[k]: k = p[k-1]
        if s[i] == s[k]: k += 1
        p[i] = k
    return p
print(pi("aabaaab"))
What is printed?
  1. A. [0, 1, 0, 1, 2, 2, 3]
  2. B. [0, 1, 0, 1, 2, 3, 3]
  3. C. [0, 1, 0, 1, 2, 2, 2]
  4. D. [0, 0, 0, 1, 2, 2, 3]

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

At i = 5 ('a' after 'aabaa'), k = 2 but s[5] = 'a' ≠ s[2] = 'b', so k falls back to pi[1] = 1 and then matches, giving 2 (not 3). At i = 6, s[6] = 'b' = s[2], so pi = 3: the prefix 'aab' equals the suffix 'aab'.

More Coding Interview Problems questions

Exams that ask this topic