Data Structures & AlgorithmsVery hardTCS Digital · Infosys SP

KMP failure function (lps[i] = length of the longest proper prefix of p[0..i] that is also a suffix). What is printed?

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

Correct answer: D. [0, 1, 2, 0, 1, 2, 3, 3, 4, 0]

On a mismatch k falls back to lps[k − 1] (not straight to 0), which keeps partial matches alive. Result: [0, 1, 2, 0, 1, 2, 3, 3, 4, 0].

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic