Data Structures & AlgorithmsVery hardProduct company OA

Problem: KMP pattern search instrumented to count fallback steps k = π[k − 1] (total over the whole text). What is printed (matches, fallbacks) for three texts?

Problem: KMP pattern search instrumented to count fallback steps k = π[k − 1] (total over the whole text). What is printed (matches, fallbacks) for three texts?
def kmp_steps(t, 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
    k = steps = found = 0
    for ch in t:
        while k and ch != p[k]: k = pi[k - 1]; steps += 1
        if ch == p[k]: k += 1
        if k == len(p): found += 1; k = pi[k - 1]
    return found, steps
print(kmp_steps("aaaaaaaaab", "aaab"), kmp_steps("a" * 1000, "aaab"), kmp_steps("ab" * 500, "aab"))
What is printed?
  1. A. (1, 6) (0, 3000) (0, 500)
  2. B. (1, 3) (0, 997) (0, 1000)
  3. C. (2, 6) (0, 997) (0, 0)
  4. D. (1, 6) (0, 997) (0, 500)

Correct answer: D. (1, 6) (0, 997) (0, 500)

Each fallback strictly decreases k, and k grows by at most 1 per text character, so total fallbacks ≤ number of characters – the amortised argument behind KMP's O(n + m). For 'a'×1000 vs 'aaab', every position after the first three reaches k = 3 and falls back once: 997. For (ab)×500 vs 'aab' each 'b' after an 'a' causes one fallback: 500. A naive matcher would need up to ~4 comparisons per position, i.e. O(nm).

More Coding Interview Problems questions

Exams that ask this topic