Data Structures & AlgorithmsVery hardGATE CS · DSA

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("aabbbabaaa"))
  1. A. [0, 1, 0, 0, 0, 1, 0, 1, 2, 2]
  2. B. [0, 0, 1, 0, 0, 1, 0, 1, 2, 2]
  3. C. [0, 1, 0, 0, 0, 0, 1, 1, 2, 2]
  4. D. [0, 1, 0, 0, 0, 1, 0, 1, 2, 1]

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

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

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

Exams that ask this topic