Question presented to candidate: "Explain how the Knuth-Morris-Pratt algorithm finds a pattern in a text, then implement it in Python: build the failure table and return every index where the pattern starts. Why is it linear?"
What a strong answer should cover:
- The naive search restarts the pattern after a mismatch and is O(n * m) on repetitive input.
- The LPS (failure) array:
lps[i]is the longest proper prefix ofp[0..i]that is also a suffix; built in O(m) with thek = lps[k - 1]fallback. - The search keeps the text index moving forward only; on a mismatch
j = lps[j - 1]; after a full matchj = lps[m - 1]to catch overlaps. - O(n + m) time by amortised analysis (j rises at most n times, so it falls at most n times); O(m) space.
- Python specifics: in production use
str.find/in(much faster than a pure-Python loop);findreturns -1 whileindexraisesValueError; strings are immutable sequences of code points, sot[i]is one character.
Code / implementation expected: Yes โ build_lps(p) and kmp_search(t, p) in Python, returning all match positions.