Data Structures & AlgorithmsVery hardProduct company OA

A KMP prefix (failure) table and an overlapping-occurrence counter. What is printed?

A KMP prefix (failure) table and an overlapping-occurrence counter. What is printed?
def prefix(p):
    pi = [0] * len(p)
    for i in range(1, len(p)):
        k = pi[i - 1]
        while k and p[i] != p[k]: k = pi[k - 1]
        if p[i] == p[k]: k += 1
        pi[i] = k
    return pi
def count(t, p):
    pi, k, c = prefix(p), 0, 0
    for ch in t:
        while k and ch != p[k]: k = pi[k - 1]
        if ch == p[k]: k += 1
        if k == len(p): c += 1; k = pi[k - 1]
    return c
print(prefix("abaabab"), count("abaababaabaabab", "abaab"))
  1. A. [0, 0, 1, 1, 2, 3, 2] 2
  2. B. [0, 0, 1, 1, 2, 1, 2] 3
  3. C. [0, 0, 1, 0, 2, 3, 2] 3
  4. D. [0, 0, 1, 1, 2, 3, 2] 3

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

pi[i] is the length of the longest proper prefix of p[0..i] that is also its suffix. For abaabab: a b → 0 0, aba → 1, abaa → 1 (fall back from 'ab' to 'a'), abaab → 2, abaaba → 3, abaabab → after the mismatch fall back 3 → 1 → then 'ab' → 2. After a full match the matcher resumes from pi[m − 1] = 2 instead of 0, so overlapping matches are found: 'abaab' starts at 0, 5 and 8 → 3. Resetting k to 0 after a match finds only the non-overlapping ones.

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

Exams that ask this topic