String / Pattern Matching
Finding a needle in a very long haystack, without looking at every straw twice.
- compare brute force, Boyer–Moore and KMP on the same input
- compute a KMP failure function by hand
- explain why KMP is O(n + m)
- build and query a trie
The pattern-matching problem
Given a text T of length n and a pattern P of length m, find every position where P occurs in T. This is what Ctrl+F, grep, DNA search and plagiarism detectors do all day — often on texts with billions of characters, so efficiency matters.
T[i:i+m] == P means the pattern occurs at shift i. There are n − m + 1 possible shifts.
Brute force: try every shift
Line up the pattern at every shift and compare character by character, stopping at the first mismatch. Simple, no preparation, but the pattern can be compared almost fully before failing.
For T = aaaa…a and P = aaa…ab every shift matches almost all of P before failing on the last character. Natural English text is kinder, but DNA (alphabet of 4 letters) can be nasty.
How many shifts must brute force try for a text of length 100 and a pattern of length 10?
Boyer–Moore: skip ahead using the mismatch
Boyer–Moore compares the pattern from right to left and uses what it learns at a mismatch to skip several shifts at once. The bad-character rule: if the text character c that caused the mismatch does not appear in the pattern at all, the pattern can jump completely past it. If c appears in P, shift the pattern so its rightmost occurrence of c lines up with the text character.
With a good alphabet size the average case is sub-linear — roughly n/m comparisons, since most shifts jump by nearly m. The worst case of the simple rule is still O(nm); the full algorithm adds a good-suffix rule for O(n + m).
In Boyer–Moore, a mismatch occurs at a text character that does not occur in the pattern anywhere. The pattern can…
Which statements describe Boyer–Moore?
Knuth–Morris–Pratt: never move backwards in the text
Brute force wastes the information gained from partial matches. Suppose we matched abab of the pattern ababc and then failed. We know the last text characters are abab. The longest prefix of the pattern that is also a suffix of abab is ab — so the next candidate alignment already has ab matched; there is no need to re-read those text characters.
fail[j] = length of the longest proper prefix of P[0:j+1] that is also a suffix of it. It depends only on the pattern and tells us how far to fall back after a mismatch at position j + 1.
The pointer i into the text only moves forward. The value k increases at most once per text character and every fall-back decreases it, so the total number of fall-backs is at most n. Building the failure function is O(m) by the same argument.
| Algorithm | Preprocessing | Worst-case matching | Typical |
|---|---|---|---|
| Brute force | none | O(nm) | fine for short texts |
| Boyer–Moore | O(m + alphabet) | O(nm) simple rule / O(n+m) full | sub-linear, often the fastest in practice |
| KMP | O(m) | O(n + m) | guaranteed linear, never re-reads text |
What is the KMP failure array for 'aabaaab'?
def failure(P):
fail, k = [0] * len(P), 0
for j in range(1, len(P)):
while k > 0 and P[j] != P[k]:
k = fail[k - 1]
if P[j] == P[k]:
k += 1
fail[j] = k
return fail
print(failure("aabaaab"))What does fail[j] store in KMP?
Why is KMP's total matching time O(n + m) and not O(nm)?
Tries: searching many words at once
A trie (retrieval tree, pronounced 'try') stores a set of words in a tree where each edge is labelled by a letter and the path from the root spells a prefix. Words that share a prefix share a path. Lookup of a word of length L takes O(L) — independent of how many words are stored.
Autocomplete, spell-checking, IP routing tables, T9 keyboards. The shared prefixes also save memory when many words begin alike. A suffix trie of the text (all suffixes inserted) lets you test whether any pattern occurs in the text in O(m).
How long does it take to check whether a word of length 7 is in a trie holding a million words?
How many nodes (excluding the root) does a trie of these words have?
words = ["to", "tea", "ted", "ten", "in", "inn"]
nodes = set()
for w in words:
for i in range(1, len(w) + 1):
nodes.add(w[:i])
print(len(nodes))Chapter challenge — Week 10
Which algorithm never moves its text pointer backwards?
How many character comparisons does brute force make?
T, P = "aaaaab", "aab"
count = 0
for i in range(len(T) - len(P) + 1):
for j in range(len(P)):
count += 1
if T[i + j] != P[j]:
break
print(count)Pattern 'abcab' — what is the last entry of its KMP failure array?
KMP matching loop (for each text character).
Choose the true statements.
Searching for pattern P of length m: the number of candidate shifts in text of length n is…
For which scenario is a trie the most natural tool?
Practice on LeetCode
String matching and tries.
Try each problem first with a brute-force idea and estimate its cost, then improve it using this chapter's technique. Links open LeetCode in a new tab; all problems listed are free. Levels follow LeetCode's own labels.
| Problem | Level | Practises | |
|---|---|---|---|
| Find the Index of the First Occurrence in a String ↗ | Easy | brute force, then KMP | |
| Repeated Substring Pattern ↗ | Easy | failure-function idea | |
| Longest Happy Prefix ↗ | Hard | exactly the KMP failure function | |
| Shortest Palindrome ↗ | Hard | KMP on s + '#' + reverse(s) | |
| Repeated String Match ↗ | Medium | pattern search on a repeated text | |
| Longest Common Prefix ↗ | Easy | prefix thinking before tries | |
| Implement Trie (Prefix Tree) ↗ | Medium | build a trie | |
| Design Add and Search Words Data Structure ↗ | Medium | trie + DFS for wildcards | |
| Replace Words ↗ | Medium | shortest-prefix lookup in a trie | |
| Search Suggestions System ↗ | Medium | autocomplete | |
| Word Search II ↗ | Hard | trie + backtracking on a grid |
Key takeaways
- Pattern matching asks where a pattern of length m occurs in a text of length n. Brute force is O(nm).
- Boyer–Moore compares right to left and uses the bad-character rule to skip ahead — typically sub-linear.
- KMP precomputes a failure function in O(m) and then scans the text in O(n) with no backtracking.
- Tries index many words by their prefixes: lookup in O(word length), natural for autocomplete.