Advanced Topic 43 of 51 Algorithms
KMP Algorithm
Linear-time string matching using a failure table.
How it works
The Knuth-Morris-Pratt algorithm finds a pattern in a text in O(n + m) time by precomputing a failure function, the longest proper prefix of the pattern that is also a suffix for each position. When a mismatch occurs, the pattern is shifted using this table instead of restarting comparison, so the text pointer never moves backward.
Step-by-step walkthrough
- The pattern ABABC has a failure table of how much of a prefix repeats at each position.
- Compare text and pattern left to right.
- A mismatch at C means ABAB was matched, and its longest border is AB.
- Jump the pattern forward and keep the text pointer where it is.
- The text is never moved backward so the total time is O(n + m).
Where it is used
Text search in editors and tools, bioinformatics sequence matching, plagiarism detection, network intrusion detection signatures and implementing substring search in libraries use KMP.
Common pitfall
Building the failure table is subtle, and off-by-one errors are very common. Using zero-based versus one-based definitions inconsistently breaks the shifting rule. For a single occasional search, a simple library routine may be enough. For multiple patterns use Aho-Corasick instead.
Where it fits in the course
KMP Algorithm is topic 43 of 51 in Algorithms, rated Advanced. It follows Maximum Flow. The next topic is Rabin-Karp Algorithm.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Algorithms quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Algorithms quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is KMP Algorithm?
Where do people use KMP Algorithm?
What is the most common mistake with KMP Algorithm?
What should I learn before this topic?
How can I practice it?
Is KMP Algorithm hard to learn?
How long does it take to learn KMP Algorithm?
Which topics are related to KMP Algorithm?
What should I study after KMP Algorithm?
Related topics
- Maximum Flow (Algorithms)
- Rabin-Karp Algorithm (Algorithms)
- Strongly Connected Components (Algorithms)
- Huffman Coding (Algorithms)
- Shor's Algorithm (Emerging & Frontier Topics)
- Grover's Algorithm (Emerging & Frontier Topics)