Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Count (possibly overlapping) occurrences of a pattern in a text with KMP.

Problem: Count (possibly overlapping) occurrences of a pattern in a text with KMP.
def kmp_count(t, p):
    f = [0] * len(p); k = 0
    for i in range(1, len(p)):
        while k and p[i] != p[k]: k = f[k-1]
        if p[i] == p[k]: k += 1
        f[i] = k
    cnt = k = 0
    for c in t:
        while k and c != p[k]: k = f[k-1]
        if c == p[k]: k += 1
        if k == len(p): cnt += 1; k = f[k-1]
    return cnt
print(kmp_count("aaaaaaa", "aaaa"), kmp_count("abababab", "abab"))
What is printed?
  1. A. 4 3
  2. B. 1 2
  3. C. 4 2
  4. D. 7 4

Correct answer: A. 4 3

After a full match KMP falls back to f[m − 1] instead of 0, so overlapping matches are kept: 'aaaa' starts at indices 0–3 of a 7-letter run (4 matches) and 'abab' at 0, 2, 4 (3 matches). str.count would give 1 and 2 because it skips past each match.

More Coding Interview Problems questions

Exams that ask this topic