本书暂未推出简体中文版。现有版本:English。
University Computer Science — Year 2 · 本科二年级
25Text Algorithms and Compression
The town keeps an archive: a line for every loan, every return and every weather reading of the year, 87,299 characters. Finding a phrase in it is the oldest text problem, and three algorithms solve it with very different amounts of work:
text = archive()
print(f"archive: {len(text)} characters, {text.count(chr(10))} lines")
for pattern in ["returned Seven Forest", "On 2025-12-1"]:
print(f"looking for {pattern!r}, {len(pattern)} letters")
for name, matcher in [("naive", naive), ("Boyer-Moore", boyer_moore), ("KMP", kmp)]:
found, comparisons = matcher(text, pattern)
print(f" {name:12} {len(found):3} occurrences, first at {found[0]:5},"
f" {comparisons:6} comparisons ({comparisons / len(text):.2f} a letter)")
$ python search.py
archive: 87299 characters, 1503 lines
looking for 'returned Seven Forest', 21 letters
naive 8 occurrences, first at 197, 96162 comparisons (1.10 a letter)
Boyer-Moore 8 occurrences, first at 197, 6865 comparisons (0.08 a letter)
KMP 8 occurrences, first at 197, 91636 comparisons (1.05 a letter)
looking for 'On 2025-12-1', 12 letters
naive 22 occurrences, first at 40738, 99951 comparisons (1.14 a letter)
Boyer-Moore 22 occurrences, first at 40738, 10698 comparisons (0.12 a letter)
KMP 22 occurrences, first at 40738, 88920 comparisons (1.02 a letter)
The naive search and KMP look at about one comparison per letter of the text, Boyer–Moore at a tenth of that. Yet the naive search can be forced into comparisons per letter for a pattern of letters, and KMP never makes more than two. This chapter proves these costs, adds a search by hashing and a tree of words for completing names, and ends with the other thing one does with an archive: store it in less space.
You already know
The grade 12 volume: a pattern and its occurrences in a text, the naive search, Horspool’s shift table. Chapter 21: deterministic finite automata. The Year 1 volume: Huffman codes, the optimal prefix code for given letter frequencies; hash functions and hash tables; the potential method of amortised analysis, in which a quantity that never goes below zero pays for expensive steps.
25.1 String matching
Definition 25.1 (String matching, occurrence, shift)
Let be a text and a pattern, words over an alphabet , with . A shift is an integer with ; it is an occurrence of when for . String matching is the problem of finding every occurrence.
The cost measure in this chapter is the number of comparisons of two letters, which the listings count.
def naive(text, pattern):
"""The shifts where pattern occurs in text, and the letter comparisons made."""
n, m = len(text), len(pattern)
found, comparisons = [], 0
for s in range(n - m + 1):
j = 0
while j < m:
comparisons += 1
if text[s + j] != pattern[j]:
break
j += 1
if j == m:
found.append(s)
return found, comparisons
Proposition 25.2 (Cost of the naive search)
The naive search makes at most comparisons, and exactly that many on the text with the pattern .
Proof. Each of the shifts compares at most letters. On with , every shift matches letters and fails on the last, so it makes exactly comparisons. ∎
On ordinary text the first comparison of a shift usually fails, and the cost is close to , as in Output 25.1. The worst case is not exotic, though: a log file of repeated lines, a DNA sequence or a binary file are close to it.
25.2 Boyer–Moore and the bad-character rule
The grade 12 volume compared the pattern from its right end and jumped with a table of letters. The same idea, made exact:
Definition 25.3 (Bad-character rule)
Compare with the text at shift from the right, and let be the position of the first difference, with the bad character. Let be the last position of in , or if does not occur in . The bad-character rule moves to the shift .
River is compared from its right end; the text’s - differs from r and occurs nowhere in the pattern, so no shift that puts a letter of the pattern under it can match, and the pattern jumps past it.Proposition 25.4 (No occurrence is skipped)
The bad-character rule never jumps over an occurrence: no shift with is an occurrence.
Proof. A shift with puts the pattern’s position under the text position , which holds . Since , and is the last position of in , : the shift is not an occurrence. If , the rule moves by and skips nothing. ∎
def last_occurrence(pattern):
"""For each letter of the pattern, its last position; other letters: -1."""
return {c: j for j, c in enumerate(pattern)}
def boyer_moore(text, pattern):
"""The shifts where pattern occurs, comparing from the right; the comparisons."""
n, m = len(text), len(pattern)
last = last_occurrence(pattern)
found, comparisons, s = [], 0, 0
while s <= n - m:
j = m - 1
while j >= 0:
comparisons += 1
if text[s + j] != pattern[j]:
break
j -= 1
if j < 0:
found.append(s)
s += 1 # an occurrence: the next shift
else: # bring the last c of the pattern under the text's c, or past it
s += max(1, j - last.get(text[s + j], -1))
return found, comparisons
When the bad character does not occur in the pattern, the jump is , up to ; on ordinary text with a long pattern, most shifts are skipped unread, which explains the tenfold saving of Output 25.1. The worst case is still , on with . Boyer and Moore’s algorithm adds a second rule, the good suffix, which uses the part already matched; with it, the search for the first occurrence becomes linear. Reporting all occurrences in linear time needs one more refinement (Galil’s rule): on with every shift is an occurrence, and the good suffix moves by one and reads the letters again (Exercise 25.3). KMP reaches the linear bound for all occurrences with the matched part alone, and from the left.
25.3 Knuth–Morris–Pratt
When the naive search fails after matching letters, it starts again one letter further and reads again text that it has already seen. Those letters are known: they are . Which shifts can still succeed depends only on the pattern.
Definition 25.5 (Border, failure function)
A border of a word is a word that is both a proper prefix and a proper suffix of (the empty word is always one). The failure function of is , the length of the longest border of , for .
abababc. The matched part ababa has the longest border aba; the pattern moves so that its prefix aba sits under the text’s aba, and the comparison resumes at the same text letter, with .If matches the text up to position and , a shift by with can only succeed if , that is if is a border of . The smallest useful shift keeps the longest border: the new is , and the text letter is compared again.
Method 25.6 (Knuth–Morris–Pratt)
Compute . Then read the text once, keeping , the number of pattern letters matched. For each text letter : while and , set ; if , increase . When , report the occurrence ending here and set . Stop when the pattern, placed at shift , no longer fits in the text.
def failure(pattern):
"""pi[q] = the length of the longest proper border of pattern[:q], for q = 1..m."""
m = len(pattern)
pi = [0] * (m + 1)
k = 0 # the length of the current border
for q in range(2, m + 1):
while k > 0 and pattern[k] != pattern[q - 1]:
k = pi[k] # the next shorter border
if pattern[k] == pattern[q - 1]:
k += 1
pi[q] = k
return pi
def kmp(text, pattern):
"""The shifts where pattern occurs in text, and the letter comparisons made."""
pi, n, m = failure(pattern), len(text), len(pattern)
found, comparisons, q = [], 0, 0 # q letters of the pattern are matched
for i, c in enumerate(text):
while True:
if i - q > n - m: # the pattern now starts too far right to fit
return found, comparisons
comparisons += 1
if pattern[q] == c:
q += 1
break
if q == 0:
break
q = pi[q] # shift the pattern; compare c again
if q == m:
found.append(i - m + 1)
q = pi[q]
return found, comparisons
$ python kmp.py
'ababc' 1:0 2:0 3:1 4:2 5:0
'abcabd' 1:0 2:0 3:0 4:1 5:2 6:0
'aaaab' 1:0 2:1 3:2 4:3 5:0
'On 2025-0' 1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0
The failure function is computed by the same search, run on the pattern against itself: k is the longest border of the prefix read so far, extended by one letter when the next letters agree, and shortened along the chain of ever shorter borders otherwise. The chain lists all borders, because a border of a border of is a border of , and the longest border shorter than is .
Proposition 25.7 (The failure function in linear time)
failure computes in steps.
Proof. Correctness: if has a border of length , removing its last letter gives a border of length of followed by ; trying the borders of from the longest, the first one so extended is the longest border of . Cost: increases by at most for each , so at most times in all; each iteration of the inner loop decreases and , so the inner loop runs at most times in all. ∎
Theorem 25.8 (KMP is linear)
The search of Listing 25.4 makes at most comparisons on a text of length .
Proof. When the letter is compared with , the pattern is at the shift . Consider the sum . A comparison that succeeds increases and then (the loop moves to the next letter): grows by and is unchanged. A failure with moves to the next letter with : and both grow by . A failure with replaces by at the same : grows. So between two comparisons increases by at least . Every comparison happens with and , the program stopping before any other, so takes at most the values at comparisons: at most of them. ∎
The argument is a potential argument with the potential , and it bounds the total work without bounding the work on one letter: one text letter may be compared many times, as the chain of borders is followed, but each of those comparisons moves the pattern forward for good.
Definition 25.9 (String-matching automaton)
The string-matching automaton of over is the DFA with states , start state , accepting state , and transition the length of the longest prefix of that is a suffix of .
The automaton reads the text once, one transition per letter, and is in state exactly at the end of each occurrence. It is KMP with every chain of borders followed in advance: when , and otherwise , or from state .
def automaton(pattern, alphabet):
"""delta[q][c] for q = 0..m: the longest prefix of pattern that is a suffix of
pattern[:q] + c."""
pi, m = failure(pattern), len(pattern)
delta = [{} for _ in range(m + 1)]
for q in range(m + 1):
for c in alphabet:
if q < m and pattern[q] == c:
delta[q][c] = q + 1
else: # the same move as from the longest border (state 0: stay)
delta[q][c] = delta[pi[q]][c] if q > 0 else 0
return delta
def run(delta, m, text):
"""One table lookup per letter: the end positions of the occurrences."""
q, ends = 0, []
for i, c in enumerate(text):
q = delta[q].get(c, 0)
if q == m:
ends.append(i)
return ends
$ python kmp_automaton.py
state a b c
0 1 0 0
1 1 2 0
2 3 0 0
3 1 4 0
4 3 0 5
5 1 0 0
in abababcababcabc: occurrences end at [6, 11]
ababc over , and the two occurrences in a text.ababc, drawn from Output 25.3. The edges not drawn lead to state . From state (abab read), an a leads to : ababa ends with aba.The table has entries. For bytes that is columns, which is why programs usually keep the failure function, of size , and follow it at run time.
History
Donald Knuth, James Morris and Vaughan Pratt published their algorithm in 1977; the same year Robert Boyer and J Strother Moore published the search from the right with its two rules.
25.4 Rabin–Karp
Comparing letters is not the only way to compare words. A word of letters is a number in base , and two equal words give equal numbers; reduced modulo a prime , the numbers are small, and the number of the next window is computed from the current one in constant time.
Definition 25.10 (Rolling hash, spurious hit)
The rolling hash of a window is . It satisfies . A shift whose hash equals the pattern’s, , but which is not an occurrence, is a spurious hit.
Method 25.11 (Rabin–Karp)
Compute and , then by the rolling formula. At each shift with , compare the window with letter by letter: report it if they agree, count a spurious hit otherwise.
def rabin_karp(text, pattern, q):
"""The occurrences, and the number of spurious hits."""
n, m = len(text), len(pattern)
if m > n:
return [], 0
high = pow(BASE, m - 1, q) # the weight of the window's first letter
hp = hw = 0
for j in range(m):
hp = (hp * BASE + ord(pattern[j])) % q
hw = (hw * BASE + ord(text[j])) % q
found, spurious = [], 0
for s in range(n - m + 1):
if hw == hp:
if text[s:s + m] == pattern:
found.append(s)
else:
spurious += 1
if s < n - m: # roll: remove text[s], append text[s + m]
hw = ((hw - ord(text[s]) * high) * BASE + ord(text[s + m])) % q
return found, spurious
Proposition 25.12 (Expected spurious hits)
If every window different from has with probability at most , the expected number of spurious hits is at most , and the expected cost of the checks on them at most .
Proof. The number of spurious hits is a sum over the shifts of indicator variables, each of expectation at most ; the expectation of a sum is the sum of the expectations. Each spurious hit costs at most comparisons. ∎
The hypothesis is a model, not a theorem about a fixed : a text could be built to collide with the pattern for one modulus. Karp and Rabin choose the prime at random, and then the bound is proved (Exercise 25.10). In practice the model is close:
$ python rk_demo.py
'Riverside' q = 97: 363 occurrences, 755 spurious (estimate 899.9)
'Riverside' q = 1000003: 363 occurrences, 0 spurious (estimate 0.1)
'borrowed Seven Forest' q = 97: 9 occurrences, 838 spurious (estimate 899.8)
'borrowed Seven Forest' q = 1000003: 9 occurrences, 0 spurious (estimate 0.1)
'Hilltop, -2.3' q = 97: 1 occurrences, 603 spurious (estimate 899.9)
'Hilltop, -2.3' q = 1000003: 1 occurrences, 0 spurious (estimate 0.1)
Rabin–Karp is slower than KMP for one pattern, but it extends at no cost to many patterns of the same length: put their hashes in a hash table, and check the windows whose hash is in it (Exercise 25.9). It also compares other objects than words, such as the blocks of two files.
Richard Karp and Michael Rabin published the method in 1987, with a random prime as the modulus.
25.5 Tries
Completing a name as it is typed asks for every word of a set that starts with a given prefix. Sorting the words and searching by halves answers it; a tree indexed by letters answers it in time that depends on the prefix, not on the size of the set.
Definition 25.13 (Trie)
A trie of a finite set of words is a rooted tree whose edges are labelled by letters, the edges out of a node having distinct labels, with a mark on some nodes: the word spelled from the root to a node is in the set exactly when the node is marked, and every leaf is marked.
class Trie:
def __init__(self):
self.children = {} # a letter -> the subtrie
self.end = False # a word ends here
def insert(self, word):
node = self
for c in word:
node = node.children.setdefault(c, Trie())
node.end = True
def find(self, prefix):
"""The node reached by reading prefix, or None."""
node = self
for c in prefix:
node = node.children.get(c)
if node is None:
return None
return node
def __contains__(self, word):
node = self.find(word)
return node is not None and node.end
def words(self, prefix=""):
"""The words that start with prefix, in alphabetical order."""
node, out = self.find(prefix), []
stack = [(node, prefix)] if node else []
while stack:
node, word = stack.pop()
if node.end:
out.append(word)
for c in sorted(node.children, reverse=True): # smallest letter on top
stack.append((node.children[c], word + c))
return out
Proposition 25.14 (Trie operations)
A trie of words of total length has at most nodes. Inserting or finding a word of length takes lookups in the children’s tables; listing the words that start with a prefix takes lookups and a walk of the subtrie below , whose size is at most the total length of those words plus one.
Proof. Each node except the root is created by one letter of one inserted word, so there are at most of them. Insertion and search follow one edge per letter. The words under are those spelled by the marked nodes of the subtrie at , and each node of that subtrie lies on the path of at least one of them. ∎
$ python trie_demo.py
24 names, 258 letters, 164 nodes
'Mill' -> ['Mill Avenue', 'Mill Row', 'Mill Street']
'Ch' -> ['Church Lane', 'Church Way']
'S' -> ['School Avenue', 'School Lane', 'School Way', 'Station Row']
'River Lane' -> ['River Lane']
'Riv' -> ['River Avenue', 'River Lane']
'Bridge Road ' -> []
'Z' -> []
'Mill Row' in the trie: True 'Mill' in the trie: False
eight names: 47 nodes; compressed (* = a name ends):
'Castle '
'Ro'
'ad' *
'w' *
'Way' *
'M'
'arket Ro'
'ad' *
'w' *
'ill '
'Avenue' *
'Row' *
'Street' *
In a compressed trie (also called a radix tree) every node has two children or more, or ends a word, so the number of nodes is at most twice the number of words. A trie of patterns with, at each node, a link to the longest suffix of its word that is also a node finds every occurrence of many patterns in one pass over a text, the way KMP does for one (Exercise 25.11).
25.6 Compression: Lempel–Ziv–Welch
A Huffman code gives each byte a code word of a length that suits its frequency. The archive repeats whole words, “borrowed”, “returned”, “degrees and”, which a code for single bytes cannot exploit. A dictionary coder codes the repeated words themselves.
Definition 25.15 (Dictionary coder, Lempel–Ziv–Welch coding)
A dictionary coder replaces pieces of the input by their numbers in a dictionary of words. Lempel–Ziv–Welch coding (LZW) starts with the dictionary of the 256 single bytes, numbered to . It repeatedly reads the longest word of the dictionary that the input starts with, emits its number, and adds to the dictionary followed by the next byte of the input, under the next free number.
The dictionary is not sent. The decoder builds the same one as it reads the codes, one entry behind: when it reads a code, it knows the word just decoded and the first byte of the new one, which is what the encoder added.
def encode(data, log=None):
"""A list of codes: each one is the longest word of the dictionary that starts here;
that word plus the next byte becomes a new entry (appended to log if given)."""
table = {bytes([b]): b for b in range(256)}
codes, w = [], b""
for b in data:
wb = w + bytes([b])
if wb in table:
w = wb
else:
codes.append(table[w])
table[wb] = len(table)
if log is not None:
log.append((len(table) - 1, wb))
w = bytes([b])
if w:
codes.append(table[w])
return codes
def decode(codes):
"""Rebuild the encoder's dictionary one step late."""
table = [bytes([b]) for b in range(256)]
out, prev = [], None
for code in codes:
if code < len(table):
word = table[code]
elif code == len(table) and prev is not None: # not yet in the table:
word = prev + prev[:1] # it can only be prev followed by its first byte
else:
raise ValueError(f"bad code {code}")
out.append(word)
if prev is not None:
table.append(prev + word[:1])
prev = word
return b"".join(out)
$ python lzw_demo.py
banana_bandana: 14 bytes -> 10 codes: b a n 257 a _ 256 n d 259
new entries: 256=ba, 257=an, 258=na, 259=ana, 260=a_, 261=_b, 262=ban, 263=nd, 264=da
decoded back: True
abababa: 7 bytes -> 4 codes: a b 256 258
new entries: 256=ab, 257=ba, 258=aba
decoded back: True
abababa the last code, 258, is used by the encoder right after creating it.Theorem 25.16 (The decoder rebuilds the dictionary)
On the codes emitted by the encoder, the decoder outputs the input. Before it reads the -st code, , its table holds the entries that the encoder’s held when it emitted the -th code.
Proof. Let be the words whose codes the encoder emits, in order; the input is their concatenation. The encoder adds the entry as followed by the next input byte, which is the first byte of , at the moment it emits the code of . By induction on , assume the decoder has output and that its table holds the entries up to , the encoder’s when it emitted ; this holds for . The encoder emitted the code of with entries up to , so the code is at most . If it is smaller, the decoder’s table holds it and gives . If it equals , the entry the decoder does not have yet, then is followed by the first byte of ; that byte is then the first byte of , so , which is what the decoder computes. In both cases it then adds followed by the first byte of , the entry of the encoder. ∎
The special case happens whenever the input contains with a byte and in the dictionary, as in ; a decoder without it works on most inputs and fails on these (Exercise 25.6).
$ python ratio.py
archive: 87299 bytes, 63 distinct
Huffman 53702 bytes ratio 1.63
LZW 18095 bytes ratio 4.82
zlib -9 10113 bytes ratio 8.63
LZW: 11383 codes, 7.7 bytes a code
Huffman saves the bytes’ unequal frequencies: 63 distinct bytes would need 6 bits each with a fixed code, and their unequal frequencies bring Huffman’s average down to 4.9 bits. LZW saves the repetitions, and its gain grows with the text, as its dictionary learns the archive’s phrases (Problem 25.1).
In practice
Terry Welch described LZW in 1984, as a variant of the dictionary method that Jacob Ziv and Abraham Lempel published in 1978. The zlib library writes DEFLATE, which combines LZ77, a coder that replaces a repeated piece by a reference to its previous occurrence (a distance and a length), with Huffman codes for those references and for the bytes; it compresses the archive almost twice as well as LZW.
25.7 The cost on a hostile text
The comparisons of Proposition 25.2 and Theorem 25.8 turn into time. The same two searches in C, on the text with the pattern :
$ gcc -std=c17 -O2 -Wall -Wextra -o kmp_bench kmp_bench.c -lm && ./kmp_bench
n naive comparisons naive (ms) KMP comparisons KMP (ms)
200000 19990100 7.22 399900 0.21
400000 39990100 14.17 799900 0.42
600000 59990100 20.95 1199900 0.63
800000 79990100 27.95 1599900 0.85
1000000 99990100 36.14 1999900 1.07
1200000 119990100 42.05 2399900 1.29
1400000 139990100 50.21 2799900 1.49
1600000 159990100 56.22 3199900 1.71
The ratio of the times, about 33, is smaller than the ratio of the comparisons, 50: KMP’s loop does more work around each comparison. For a fixed pattern the naive search is still linear in ; what grows without bound is the factor , and patterns of a thousand letters make it a thousand.
25.8 Exercises
Exercise 25.1 ★
Compute the failure function of aabaaab by hand, then check with exo_failure.py.
Solution
Solution of Exercise 25.1.
For the prefixes a, aa, aab, aaba, aabaa, aabaaa, aabaaab the longest borders are the empty word, a, the empty word, a, aa, aa and aab. For , the border aa of aabaa cannot be extended (aab is not a suffix of aabaaa), but the shorter border a can: aa.
$ python exo_failure.py
pi[1]=0 pi[2]=1 pi[3]=0 pi[4]=1 pi[5]=2 pi[6]=2 pi[7]=3
aabaaab.Exercise 25.2 ★
The function kmp_short of exo_kmp_bug.py is a shorter KMP: on a mismatch it sets and moves to the next letter. On which texts does it miss an occurrence? Correct it.
Solution
Solution of Exercise 25.2.
$ python exo_kmp_bug.py
'abcabd' 'abd' [3] expected [3]
'aaab' 'aab' [] expected [1]
'abababc' 'ababc' [] expected [2]
'On 2025-12-1, On 2025-12-12' '2025-12-12' [17] expected [17]
After the pattern has moved, and the letter that caused the mismatch must be compared with ; kmp_short skips it. It misses an occurrence whenever that letter is the start of the continued match: on aaab, after aa the third a fails against b, becomes , and that a should have made it . When and , as in the first and last tests, nothing is lost. The correction is the inner while loop of Listing 25.4, which compares again until it matches or .
Exercise 25.3 ★
After an occurrence, Listing 25.3 moves by one. Prove that moving by skips no occurrence, implement it, and compare the comparisons made on abababababa with aba, on with , and on the archive.
Solution
Solution of Exercise 25.3.
If and are both occurrences with , then : the pattern has a border of length . So , that is , and the shifts between are not occurrences.
def boyer_moore_all(text, pattern):
n, m = len(text), len(pattern)
last, period = last_occurrence(pattern), m - failure(pattern)[m]
found, comparisons, s = [], 0, 0
while s <= n - m:
j = m - 1
while j >= 0:
comparisons += 1
if text[s + j] != pattern[j]:
break
j -= 1
if j < 0:
found.append(s)
s += period # no occurrence starts closer: it would give a longer border
else:
s += max(1, j - last.get(text[s + j], -1))
return found, comparisons
$ python exo_bm_all.py
'aba' 5 occurrences; comparisons 19 -> 15
'aaaaa' 26 occurrences; comparisons 130 -> 130
'On 2025-12' 74 occurrences; comparisons 12167 -> 12028
The gain is small: aba has period , period (no gain), and the archive’s occurrences are rare. The good-suffix rule of Boyer and Moore generalises this shift to every partial match.
Exercise 25.4 ★
Count the comparisons of the naive search on with , and on with . Do the same for Boyer–Moore with the bad-character rule.
Solution
Solution of Exercise 25.4.
Naive search: on with , every shift compares letters, in all; with , every shift fails at once, . Boyer–Moore compares from the right, so the roles swap. With , the b fails against a at , with : one comparison and a shift of , in all. With , the letters a match and the b fails at , with : the shift is , so comparisons, the worst case.
Exercise 25.5 ★★
Encode she sells sea shells with LZW by hand: list the codes and the entries added. Check with exo_lzw.py.
Solution
Solution of Exercise 25.5.
The encoder emits s, h, e, the space, s, e, l, l, s, then 259 for ␣s, e, a, 259 again, 257 for he, 262 for ll and s; each code adds the word followed by the next byte.
$ python exo_lzw.py
s h e _ s e l l s 259 e a 259 257 262 s
256=sh, 257=he, 258=e_, 259=_s, 260=se, 261=el, 262=ll, 263=ls, 264=s_, 265=_se, 266=ea, 267=a_, 268=_sh, 269=hel, 270=lls
_) and the entries added.Exercise 25.6 ★★
The decoder of exo_lzw_bug.py looks every code up in its table. On which of its three inputs does it fail, and why? Characterise the inputs on which it fails.
Solution
Solution of Exercise 25.6.
$ python exo_lzw_bug.py
b'banana bandana' True
b'she sells sea shells' True
b'abababa' IndexError: list index out of range
It fails on abababa: the last code, 258, is the entry the encoder created when it emitted the code before it, and the decoder, one entry behind, does not have it yet. By the proof of Theorem 25.16, it fails exactly on the inputs where the encoder emits a code at the step right after creating it, that is where : the input contains with a byte, the dictionary word read at that point, and a new entry.
Exercise 25.7 ★★
Write first_k(trie, prefix, k), which returns the first words in alphabetical order that start with prefix and stops as soon as it has them. Count the nodes it visits on the book titles.
Solution
Solution of Exercise 25.7.
The walk of words with a stop as soon as words are found; the smallest letter is on top of the stack, so the words come out in alphabetical order.
def first_k(trie, prefix, k):
"""At most k words starting with prefix, in alphabetical order; stops early."""
node, out, visited = trie.find(prefix), [], 0
stack = [(node, prefix)] if node else []
while stack and len(out) < k:
node, word = stack.pop()
visited += 1
if node.end:
out.append(word)
for c in sorted(node.children, reverse=True):
stack.append((node.children[c], word + c))
return out, visited
$ python exo_autocomplete.py
'The' k=3: 28 nodes visited of 292
The Clockwork Code; The Clockwork Engine; The Clockwork Forest
'The S' k=2: 14 nodes visited of 47
The Silent Code; The Silent Comet
'S' k=4: 25 nodes visited of 52
Seven Code; Seven Comet; Seven Forest; Seven Island
'Under' k=5: 37 nodes visited of 51
Under the Bridge; Under the Engine; Under the Forest; Under the Garden; Under the Library
Exercise 25.8 ★★
Show that the bound of Theorem 25.8 is attained: KMP makes exactly comparisons on with , for .
Solution
Solution of Exercise 25.8.
Here for , since is the longest border of . The first letters each match with one comparison: . For each letter at , the b of the pattern fails against a, becomes , the shift still fits, and matches: two comparisons, and again. At the b fails once, and the next shift, , no longer fits. In all . The C program confirms it for : comparisons for .
Exercise 25.9 ★★
Extend Rabin–Karp to several patterns of the same length, in one pass, with a dictionary from hash values to patterns. Find six title words of six letters in the archive and check the counts.
Solution
Solution of Exercise 25.9.
def rk_multi(text, patterns):
m = len(patterns[0])
assert all(len(p) == m for p in patterns)
def h(word):
v = 0
for c in word:
v = (v * BASE + ord(c)) % Q
return v
wanted = {} # a hash value -> the patterns that have it
for p in patterns:
wanted.setdefault(h(p), []).append(p)
high, hw = pow(BASE, m - 1, Q), h(text[:m])
found = {p: [] for p in patterns}
for s in range(len(text) - m + 1):
for p in wanted.get(hw, []):
if text[s:s + m] == p:
found[p].append(s)
if s < len(text) - m:
hw = ((hw - ord(text[s]) * high) * BASE + ord(text[s + m])) % Q
return found
$ python exo_rk_multi.py
Forest: 88
Valley: 60
Bridge: 36
Silent: 72
Garden: 14
Hidden: 73
str.count.The cost is for the hashes plus the checks of the windows whose hash is one of the patterns’, whatever the number of patterns, against one pass per pattern for KMP.
Exercise 25.10 ★★★
Let be two windows of bytes, read as numbers below . Show that has fewer than distinct prime divisors. Deduce that if is chosen at random among the smallest primes, a fixed window different from is a spurious hit with probability below , and bound the expected number of spurious hits.
Solution
Solution of Exercise 25.10.
The difference is a non-zero integer with . If it had distinct prime divisors, their product, at least , would divide it, which is impossible: it has fewer than . A window is a spurious hit for the modulus when , that is when divides . With uniform among the smallest primes, this has probability below . Summing over the shifts, the expected number of spurious hits is below ; with of the order of , it is a constant, and the expected cost is plus the occurrences’ checks. The bound holds for every text, chosen before : the randomness is in the algorithm, not in the input.
Exercise 25.11 ★★★
Write a matcher for several patterns at once: a trie of the patterns, and for each node a failure link to the node of the longest proper suffix of its word that is in the trie, computed breadth first. Test it on ushers with he, she, his, hers, then on the archive.
Solution
Solution of Exercise 25.11.
This is the algorithm of Aho and Corasick. The trie is built first; the failure links are then set breadth first, so that the link of a node’s parent, which points to a shorter word, is already known, and followed as KMP follows . A node also reports the patterns that end at its failure link.
def build(patterns):
goto, fail, out = [{}], [0], [[]] # node 0 is the root
for p in patterns:
v = 0
for c in p:
if c not in goto[v]:
goto.append({})
fail.append(0)
out.append([])
goto[v][c] = len(goto) - 1
v = goto[v][c]
out[v].append(p)
queue = deque(goto[0].values()) # breadth first: shorter words first
while queue:
v = queue.popleft()
for c, w in goto[v].items():
f = fail[v]
while f and c not in goto[f]:
f = fail[f]
fail[w] = goto[f][c] if c in goto[f] and goto[f][c] != w else 0
out[w] += out[fail[w]] # what ends at the longest border ends here too
queue.append(w)
return goto, fail, out
def search(text, patterns):
goto, fail, out = build(patterns)
v, found = 0, []
for i, c in enumerate(text):
while v and c not in goto[v]:
v = fail[v]
v = goto[v].get(c, 0)
found += [(i - len(p) + 1, p) for p in out[v]]
return found
$ python exo_aho.py
[(1, 'she'), (2, 'he'), (2, 'hers')]
2042 occurrences of 7 words in one pass, as str.count finds
ushers: she, he and hers; on the archive, seven words in one pass.Alfred Aho and Margaret Corasick published the method in 1975, for searching bibliographies for many keywords at once.
Exercise 25.12 ★★★
Prove that, whatever the text, the -th code that LZW writes stands for at most letters. Deduce that no text of letters is coded in fewer than codes, and say what a text must look like for each code to reach its limit. Check with exo_lzw_bound.py.
Solution
Solution of Exercise 25.12.
By induction on . Before the -th code the dictionary holds the single letters and the entries added so far; the entry added after code is that code’s word plus one letter, so it has at most letters by the hypothesis for . The -th code is a word of that dictionary: at most letters. A text of letters coded in codes therefore has , and solving gives . Code reaches its limit only if it is the entry just added, the word of code followed by the first letter of code , which is the first letter of code ; by induction every letter is the text’s first letter, so the text is one letter repeated, , which the problem shows meets the bound.
$ python exo_lzw_bound.py
2199 texts: the i-th code covers at most i letters; no text beats the bound
1036 random texts of 100 letters or more: 19 or more codes above it
a^n meets it: n = 100, 14 codes, bound 14
a and b, and met by .25.9 Problem: The town archive
Problem 25.1
Weekend problem — The town archive
The archive of Listing 25.1 is to be searched, its borrowers’ names completed as they are typed, and the whole stored in less space. The program below gathers the measurements.
$ python archive_problem.py
I-II 'returned Under the': 37 occurrences; naive 96229, KMP 91581 comparisons
III 60 borrowers' names, 751 letters, 600 trie nodes
'Wen': ['Wen Glenfield', 'Wen Yewmore']
'Gr': ['Grace Elmfield']
'Leo B': ['Leo Brookley']
IV LZW on a^n: n, codes = 1:1, 3:2, 6:3, 10:4, 55:10, 5050:100, 5051:101
first 1000 bytes: 461 codes, 2.2 a code
first 4000 bytes: 1307 codes, 3.1 a code
first 16000 bytes: 3425 codes, 4.7 a code
first 64000 bytes: 9489 codes, 6.7 a code
first 87299 bytes: 11383 codes, 7.7 a code
Part I — Searching.
- Each line of the archive starts with
On 2025-. What does this mean for the naive search ofOn 2025-12-1, compared with a phrase that starts with a rare letter? - Explain why the naive search makes about comparisons per letter on the archive and not .
- Boyer–Moore makes comparisons for
returned Seven Forest. Estimate the average jump, and say which letters of the archive give the longest jumps. - Give a phrase of the archive’s kind for which Boyer–Moore with the bad-character rule is slow, and explain why.
- Why can Boyer–Moore not report the occurrences in a stream, one letter at a time, as KMP does?
- The archive grows by a line a day. Which of the three searches can continue from where it stopped yesterday?
Part II — KMP against naive, counted.
- Compute the failure function of
returned Under the. - From it, explain why KMP and the naive search make almost the same number of comparisons on the archive.
- Using Theorem 25.8, bound the comparisons of KMP for this pattern, and compare with the observed.
- On the text with , how many comparisons does each search make for ? Check with Output 25.8.
- The measured times grow linearly for both. Why is the naive search linear in here, and in which quantity is it not?
- Draw the string-matching automaton of
aabover .
Part III — A trie for autocompletion.
- The 60 names have 751 letters and the trie 600 nodes, 599 below the root. What do the 152 letters saved correspond to?
- How many nodes does a lookup of
Leo Bvisit, and how does that depend on the number of names? - Compare with a sorted list of the names searched by halves: what does each structure cost for a prefix query?
- How many nodes would the compressed trie of the 60 names have at most?
- A user types
G, thenr, thena. How should the program avoid walking from the root at each letter? - Should the trie store first names and last names separately for completing either? Discuss the size.
Part IV — Compression.
- Encode by hand and list the entries added.
- Prove that LZW codes in codes, and check the values printed for , and .
- The number of bytes per code grows from to along the archive. Explain why.
- Compute the size of the LZW output if every code is written on 16 bits, and compare with the growing widths of Output 25.7.
- Why does Huffman coding of bytes give a ratio of and no more, whatever the length of the archive?
- State the problem’s result: LZW on : exactly codes, and the measured ratio on the archive.
Solution
Solution of Problem 25.1.
1. Every line starts with the first eight letters of the pattern, so the naive search compares about nine letters at each of the 1,503 line starts, instead of one; a pattern whose first letter is rare fails at once almost everywhere.
2. At most shifts the first letter differs, one comparison; the shifts where a prefix matches add a few more. The cost is plus the total length of the partial matches, small on ordinary text.
3. About letters per comparison, and nearly every shift makes one comparison, so the average jump is about 13. The longest jumps, , come from letters absent from the pattern: digits, most capitals, punctuation.
4. A date such as 2025-12-12: its last letters are digits and the bad character is almost always a digit, which occurs near the end of the pattern, so the jumps are of one to three letters.
5. It reads each window from its right end and jumps ahead, so it needs the letters of a window before deciding anything, and it reads text letters out of order. KMP reads each letter once, in order, and knows after each one whether an occurrence ends there.
6. KMP, or the automaton: its whole state is , saved at the end of the day. The other two must keep the last letters of yesterday.
7. is everywhere except and : the only borders are r, for retur and returned Under.
8. After a mismatch KMP falls back to or and compares the same letter again, which is what the naive search does at the next shift when the match was short; both make about one comparison per letter plus the partial matches.
9. . The observed is about : the bound counts a second comparison for every letter, which only a pattern with long borders on a matching text forces.
10. Naive: ; KMP: , as printed.
11. For a fixed pattern, is linear in with slope . It is not linear in the size of the input : for it is about .
12. States to : , , , , , and every other transition leads to .
13. Each node below the root stands for one distinct prefix of a name; a letter is saved each time a name reaches a prefix that an earlier name had already created, such as the W, e, n, ␣ shared by the two names starting with Wen. The saved letters are the letters of shared prefixes, counted once for each extra name sharing them.
14. Six nodes, the root and one per letter, whatever the number of names; each step is one lookup in a small table of children.
15. A sorted list finds the first name with the prefix by halving, letter comparisons for names, then reads the answers in order. The trie needs steps and the walk of the subtrie. Both are fast for 60 names; the trie does not depend on .
16. Each node other than the root has two children or more or ends a name, and there are 60 names, so at most branching nodes besides the 60 ends: at most nodes with the root.
17. Keep the node reached by the prefix typed so far, and move down one edge when a letter is added, or back up when one is deleted.
18. A trie of the names written as “last first” as well doubles the letters inserted, at most nodes, and lets a prefix of either name be completed; two separate tries are the same size.
19. The codes of a, aa, aaa, aaaa, that is ; the entries , , , and nothing after the last code, which ends the input.
20. By induction, the -th code is that of and adds , as long as at least letters remain: before it, the dictionary holds and no longer power of , and the input left starts with , so the longest dictionary word is , followed by an a. After such codes, letters are coded. The last code takes the letters left, which form a dictionary word. The number of codes is therefore the least with , the bound of Exercise 25.12: .
$ python exo_lzw_an.py
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6
n = 1..3000: the number of codes equals the formula
For , ; for , ; one more letter needs one more code, .
21. The dictionary learns the archive’s phrases as it reads: at the start it holds pairs of bytes; after thousands of lines it holds borrowed␣, names, titles and the frame of the weather lines, and each code covers more bytes.
22. bytes, against with codes of 9 to 14 bits; the largest code, , needs 14 bits.
23. A Huffman code of bytes depends only on the bytes’ frequencies, which are about the same in any long part of the archive: the ratio is divided by the average code length, about 4.9 bits here, and it cannot use the repeated words.
24. LZW on : exactly codes; on the archive, codes for bytes, bytes per code and a ratio of with growing code widths, against for Huffman and for zlib.