Skip to the solution
HardDSA12 min read

How does the KMP string-matching algorithm work?

1.2k views

The problem

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 of p[0..i] that is also a suffix; built in O(m) with the k = lps[k - 1] fallback.
  • The search keeps the text index moving forward only; on a mismatch j = lps[j - 1]; after a full match j = 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); find returns -1 while index raises ValueError; strings are immutable sequences of code points, so t[i] is one character.

Code / implementation expected: Yes โ€” build_lps(p) and kmp_search(t, p) in Python, returning all match positions.

  • dsa
  • strings
  • pattern-matching

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonBuild the LPS table and find every match, overlaps included
PythonNaive search vs KMP, counting character comparisons

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 130 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextHard

How do you merge k sorted lists?

Continue