6. KMP & Boyer-Moore
Pattern matching with the skip insight
You press Ctrl+F and type a word. Your text editor highlights every match instantly -- even in a million-line file. Search engines find patterns in gigabytes of text. DNA sequencers scan genomes for known motifs. All of these need the same primitive: find every occurrence of a short pattern inside a long text.
The naive approach is slow. Two algorithms -- Knuth-Morris-Pratt (KMP) and Boyer-Moore -- independently discovered that when a mismatch happens, you don't have to start over. You can skip.
The Naive Approach
The simplest idea: slide the pattern along the text one position at a time, checking every character.
function naiveSearch(text, pattern):
n = length(text)
m = length(pattern)
for i from 0 to n - m:
j = 0
while j < m and text[i + j] == pattern[j]:
j++
if j == m:
report match at position i
This works, but when a mismatch occurs at position j, we throw
away everything we learned about the characters we already matched. We shift
the pattern by just one position and start comparing from scratch.
Worst case: O(nm)
Text: AAAAAAAAAAAB
Pattern: AAAAB
Attempt 1: AAAA✗ (matched 4, failed on 5th)
Attempt 2: AAAA✗ (shift by 1, match 4 again...)
Attempt 3: AAAA✗
...
Attempt 8: AAAAB ✓
Each attempt matches almost the entire pattern before failing. With text length n and pattern length m, the worst case is O(nm) comparisons.
KMP's Key Insight
Don't re-examine characters you've already matched
When a mismatch happens at position j in the pattern, you've
already successfully matched pattern[0..j-1] against the text.
Some suffix of that matched portion might also be a prefix of the pattern.
If so, you can slide the pattern forward to align that prefix -- without
rechecking any text characters.
The information about how far to skip is encoded in the failure function (also called the prefix function). It's computed from the pattern alone, before you ever look at the text.
Building the Failure Function
For each position j in the pattern, the failure function
F[j] answers: what is the length of the longest proper
prefix of pattern[0..j] that is also a suffix?
Worked example: pattern = "ABABC"
j=0: "A" → no proper prefix that is also a suffix → F[0] = 0
j=1: "AB" → prefixes: "A" suffixes: "B" → no match → F[1] = 0
j=2: "ABA" → prefixes: "A","AB" suffixes: "A","BA" → "A" matches → F[2] = 1
j=3: "ABAB" → prefixes: "A","AB","ABA" suffixes: "B","AB","BAB"
→ "AB" matches → F[3] = 2
j=4: "ABABC" → prefixes: "A","AB","ABA","ABAB"
suffixes: "C","BC","ABC","BABC" → no match → F[4] = 0
| j | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Pattern | A | B | A | B | C |
| F[j] | 0 | 0 | 1 | 2 | 0 |
Pseudocode: Building the failure function
function buildFailure(pattern):
m = length(pattern)
F = new array[m], all zeros
k = 0 // length of previous longest prefix-suffix
for j from 1 to m - 1:
while k > 0 and pattern[j] != pattern[k]:
k = F[k - 1] // fall back
if pattern[j] == pattern[k]:
k++
F[j] = k
return F
This looks like it could be slow because of the inner while loop,
but k can only increase once per iteration of the outer loop.
Since it starts at 0 and never goes negative, the total number of decreases
is bounded by the total number of increases: O(m) overall.
KMP Search: Step by Step
Searching for "ABABC" in "ABABABABC"
Failure table F = [0, 0, 1, 2, 0]
Text: A B A B A B A B C
Pattern: A B A B C
✗ mismatch at j=4 (C vs A)
F[j-1] = F[3] = 2 → slide pattern so j=2
Text: A B A B A B A B C
A B A B C
✗ mismatch at j=4 (C vs A)
F[3] = 2 → slide so j=2
Text: A B A B A B A B C
A B A B C
✓ match at position 4!
Notice how the text pointer never moves backward. Each text
character is examined at most once. The pattern pointer jumps using
F to avoid redundant comparisons.
Pseudocode: KMP search
function kmpSearch(text, pattern):
n = length(text)
m = length(pattern)
F = buildFailure(pattern)
j = 0 // characters matched so far
for i from 0 to n - 1:
while j > 0 and text[i] != pattern[j]:
j = F[j - 1] // skip using failure function
if text[i] == pattern[j]:
j++
if j == m:
report match at position (i - m + 1)
j = F[j - 1] // continue searching for overlapping matches
// Total comparisons: O(n + m)
Why it's O(n + m)
Building the failure function takes O(m). The search
loop iterates exactly n times (one per text character), and by
the same amortized argument as the failure function, the total number of
j fallbacks across all iterations is at most n.
Total: O(n + m).
Boyer-Moore's Different Insight
KMP scans left-to-right. Boyer-Moore flips the script: it aligns the pattern with the text and compares from right to left -- starting at the last character of the pattern. This sounds counterintuitive, but it enables a powerful trick.
Start from the end, skip more
If the rightmost character of the text window doesn't appear anywhere in the pattern, you can skip the entire pattern length in one jump. Even partial mismatches let you skip multiple positions. On average, Boyer-Moore examines fewer characters than are in the text.
Boyer-Moore uses two skip rules. The bad character rule is the simpler and more commonly used one. The good suffix rule provides additional skips in certain cases.
The Bad Character Rule
When a mismatch occurs between text[i] and
pattern[j], the bad character rule asks: does the
mismatched text character appear anywhere else in the pattern?
-
Character not in pattern
If the mismatched text character doesn't appear in the pattern at all, slide the entire pattern past it.
-
Character in pattern
If it does appear, shift the pattern to align the rightmost occurrence of that character in the pattern with the mismatched position.
Bad character rule in action
Text: H E R E _ I S _ A _ S I M P L E
Pattern: E X A M P L E
↑ compare right-to-left
text[6]='S' vs pattern[6]='E' → mismatch
'S' not in pattern → skip entire pattern length (7)
Text: H E R E _ I S _ A _ S I M P L E
E X A M P L E
↑
text[13]='P' vs pattern[6]='E' → mismatch
'P' is in pattern at position 4 → shift to align
Text: H E R E _ I S _ A _ S I M P L E
E X A M P L E
... continue comparing
In the first step, a single comparison let us skip 7 positions. The naive approach would have needed 7 comparisons to move that far.
The Good Suffix Rule
When some characters at the end of the pattern matched before the mismatch, those matched characters form a "good suffix." The good suffix rule shifts the pattern to align:
- Another occurrence of that suffix elsewhere in the pattern, or
- A prefix of the pattern that matches a suffix of the good suffix
In practice, the bad character rule alone provides excellent performance for most inputs. The good suffix rule helps with pathological cases and is what guarantees Boyer-Moore's worst-case behavior in the refined variants.
KMP vs Boyer-Moore
| KMP | Boyer-Moore | |
|---|---|---|
| Scan direction | Left to right | Right to left |
| Skip info from | Failure function (prefix-suffix overlaps) | Bad character + good suffix tables |
| Best case | O(n) -- must examine every text character | O(n/m) -- can skip entire pattern lengths |
| Worst case | O(n + m) -- always linear | O(nm) -- but O(n + m) with Galil's optimization |
| Preprocessing | O(m) | O(m + |alphabet|) |
| Practical speed | Good -- consistent performance | Often faster -- skips more on average |
Why is Boyer-Moore often faster? Consider searching for "ALGORITHM" in English text. Most characters in the text won't match the last character 'M'. Each time that happens, Boyer-Moore can skip up to 9 positions. On natural language text with large alphabets, Boyer-Moore frequently achieves sublinear performance -- it finds the pattern while examining fewer characters than the text contains.
KMP's advantage is guaranteed linear time regardless of input. It's the safer choice when you need worst-case guarantees, such as in real-time systems or when processing adversarial input.
Complexity
| Algorithm | Preprocessing | Best Case | Worst Case | Space |
|---|---|---|---|---|
| Naive | None | O(n) | O(nm) | O(1) |
| KMP | O(m) | O(n + m) | O(n + m) | O(m) |
| Boyer-Moore | O(m + |Σ|) | O(n/m) | O(nm) | O(m + |Σ|) |
Here n is the text length, m is the pattern length, and |Σ| is the alphabet size. Boyer-Moore's worst case can be improved to O(n + m) with refinements like the Galil rule or the Apostolico-Giancarlo variant.
Where They're Used
| Application | Which algorithm and why |
|---|---|
| grep | GNU grep uses a Boyer-Moore variant -- its sublinear best case makes it blazing fast on large files |
| Text editors | Ctrl+F / Cmd+F typically uses Boyer-Moore or its simplified variant (Horspool) for interactive search |
| DNA sequence matching | KMP and its extensions are used when searching for motifs in genomic data, where guaranteed linear time matters |
| Intrusion detection | Network security systems use multi-pattern variants (Aho-Corasick, based on KMP's failure function) to scan traffic for attack signatures |
| Compilers | Lexical analyzers use pattern matching to tokenize source code |
| Spam filters | Scan email content for known spam phrases using multi-pattern matching |
Key Takeaways
- The naive pattern matching algorithm is O(nm) because it restarts from scratch after every mismatch
- KMP's failure function encodes prefix-suffix overlaps in the pattern, enabling skips that guarantee O(n + m) time
- The text pointer in KMP never moves backward -- each text character is examined at most once
- Boyer-Moore compares right-to-left and can skip entire pattern lengths when mismatched characters don't appear in the pattern
- Boyer-Moore is often faster in practice (sublinear best case of O(n/m)), but KMP has a better worst-case guarantee
- Both algorithms preprocess the pattern to build skip tables -- the search itself is where the speedup happens
- These ideas are the foundation for tools you use every day: grep, find-and-replace, and DNA alignment
Try It Yourself -- KMP Pattern Matching
Enter a text and pattern to watch KMP search step by step. The failure function table is shown, and each step highlights matches, mismatches, and how far the pattern skips.
Failure Function Table
Search Visualization
Step Log
Press "Step" or "Run All" to begin.
KMP and Boyer-Moore are two sides of the same coin: both exploit structure in the pattern to avoid redundant work. KMP never looks back. Boyer-Moore looks from the end and leaps forward. Together, they show that clever preprocessing can turn a brute-force O(nm) problem into something far better -- and they power the search tools we rely on every day.