计算机科学 · 第 4 册 · 本科二年级

University Computer Science — Year 2

本书暂未推出简体中文版。现有版本: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:

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 mm comparisons per letter for a pattern of mm 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 T=T[0..n−1]T = T[0..n-1] be a text and P=P[0..m−1]P = P[0..m-1] a pattern, words over an alphabet Σ\Sigma, with 1≤m1 \leq m. A shift is an integer ss with 0≤s≤n−m0 \leq s \leq n - m; it is an occurrence of PP when T[s+j]=P[j]T[s + j] = P[j] for 0≤j<m0 \leq j < m. 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
Listing 25.2. The naive search: every shift, letters compared from the left until a difference code/bachelor-2/25-text-algorithms/listings/naive.py

Proposition 25.2 (Cost of the naive search)

The naive search makes at most m(n−m+1)m(n - m + 1) comparisons, and exactly that many on the text ana^n with the pattern am−1ba^{m-1}b.

Proof. Each of the n−m+1n - m + 1 shifts compares at most mm letters. On ana^n with am−1ba^{m-1}b, every shift matches m−1m - 1 letters and fails on the last, so it makes exactly mm comparisons. ∎

On ordinary text the first comparison of a shift usually fails, and the cost is close to nn, 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 PP with the text at shift ss from the right, and let jj be the position of the first difference, with c=T[s+j]c = T[s + j] the bad character. Let λ(c)\lambda(c) be the last position of cc in PP, or −1-1 if cc does not occur in PP. The bad-character rule moves to the shift s+max⁡(1,j−λ(c))s + \max(1, j - \lambda(c)).

The bad-character rule. The pattern 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.
The bad-character rule. The pattern 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 s′s' with s<s′<s+max⁡(1,j−λ(c))s < s' < s + \max(1, j - \lambda(c)) is an occurrence.

Proof. A shift s′=s+ds' = s + d with 0<d<j−λ(c)0 < d < j - \lambda(c) puts the pattern’s position j−dj - d under the text position s+js + j, which holds cc. Since j−d>λ(c)j - d > \lambda(c), and λ(c)\lambda(c) is the last position of cc in PP, P[j−d]≠cP[j - d] \neq c: the shift s′s' is not an occurrence. If j−λ(c)≤1j - \lambda(c) \leq 1, the rule moves by 11 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
Listing 25.3. Boyer–Moore with the bad-character rule code/bachelor-2/25-text-algorithms/listings/boyer_moore.py

When the bad character does not occur in the pattern, the jump is j+1j + 1, up to mm; 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 m(n−m+1)m(n - m + 1), on ana^n with bam−1ba^{m-1}. 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 ana^n with ama^m every shift is an occurrence, and the good suffix moves by one and reads the mm 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 qq letters, it starts again one letter further and reads again text that it has already seen. Those qq letters are known: they are P[0..q−1]P[0..q-1]. Which shifts can still succeed depends only on the pattern.

Definition 25.5 (Border, failure function)

A border of a word uu is a word that is both a proper prefix and a proper suffix of uu (the empty word is always one). The failure function of PP is π(q)\pi(q), the length of the longest border of P[0..q−1]P[0..q-1], for 1≤q≤m1 \leq q \leq m.

A mismatch after q = 5 letters of 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 q = 3.
A mismatch after q=5q = 5 letters of 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 q=3q = 3.

If P[0..q−1]P[0..q-1] matches the text up to position i−1i - 1 and P[q]≠T[i]P[q] \neq T[i], a shift by dd with 0<d<q0 < d < q can only succeed if P[0..q−d−1]=P[d..q−1]P[0..q-d-1] = P[d..q-1], that is if P[0..q−d−1]P[0..q-d-1] is a border of P[0..q−1]P[0..q-1]. The smallest useful shift keeps the longest border: the new qq is π(q)\pi(q), and the text letter T[i]T[i] is compared again.

Method 25.6 (Knuth–Morris–Pratt)

Compute π\pi. Then read the text once, keeping qq, the number of pattern letters matched. For each text letter cc: while q>0q > 0 and P[q]≠cP[q] \neq c, set q←π(q)q \gets \pi(q); if P[q]=cP[q] = c, increase qq. When q=mq = m, report the occurrence ending here and set q←π(m)q \gets \pi(m). Stop when the pattern, placed at shift i−qi - q, 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
Listing 25.4. The failure function and the KMP search; the text index ii only moves forwards code/bachelor-2/25-text-algorithms/listings/kmp.py
$ 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
Output 25.2. Failure functions, written q:π(q)q{:}\pi(q). A pattern with no repeated prefix, such as a date, has π=0\pi = 0 everywhere.

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 k,π(k),π(π(k)),…k, \pi(k), \pi(\pi(k)), \dots of ever shorter borders otherwise. The chain lists all borders, because a border of a border of uu is a border of uu, and the longest border shorter than π(q)\pi(q) is π(π(q))\pi(\pi(q)).

Proposition 25.7 (The failure function in linear time)

failure computes π\pi in O⁡(m)\BigO(m) steps.

Proof. Correctness: if P[0..q−1]P[0..q-1] has a border of length k+1≥1k + 1 \geq 1, removing its last letter gives a border of length kk of P[0..q−2]P[0..q-2] followed by P[k]=P[q−1]P[k] = P[q - 1]; trying the borders of P[0..q−2]P[0..q-2] from the longest, the first one so extended is the longest border of P[0..q−1]P[0..q-1]. Cost: kk increases by at most 11 for each qq, so at most m−1m - 1 times in all; each iteration of the inner loop decreases kk and k≥0k \geq 0, so the inner loop runs at most m−1m - 1 times in all. ∎

Theorem 25.8 (KMP is linear)

The search of Listing 25.4 makes at most 2n−m2n - m comparisons on a text of length n≥mn \geq m.

Proof. When the letter T[i]T[i] is compared with P[q]P[q], the pattern is at the shift s=i−qs = i - q. Consider the sum i+si + s. A comparison that succeeds increases qq and then ii (the loop moves to the next letter): ii grows by 11 and ss is unchanged. A failure with q=0q = 0 moves to the next letter with q=0q = 0: ii and ss both grow by 11. A failure with q>0q > 0 replaces qq by π(q)<q\pi(q) < q at the same ii: ss grows. So between two comparisons i+si + s increases by at least 11. Every comparison happens with i≤n−1i \leq n - 1 and s≤n−ms \leq n - m, the program stopping before any other, so i+si + s takes at most the values 0,1,…,2n−m−10, 1, \dots, 2n - m - 1 at comparisons: at most 2n−m2n - m of them. ∎

The argument is a potential argument with the potential i+si + s, 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 PP over Σ\Sigma is the DFA with states 0,…,m0, \dots, m, start state 00, accepting state mm, and transition δ(q,c)\delta(q, c) the length of the longest prefix of PP that is a suffix of P[0..q−1]cP[0..q-1]c.

The automaton reads the text once, one transition per letter, and is in state mm exactly at the end of each occurrence. It is KMP with every chain of borders followed in advance: δ(q,c)=q+1\delta(q, c) = q + 1 when P[q]=cP[q] = c, and otherwise δ(q,c)=δ(π(q),c)\delta(q, c) = \delta(\pi(q), c), or 00 from state 00.

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
Listing 25.5. The automaton from the failure function, and a run that costs one lookup per letter code/bachelor-2/25-text-algorithms/listings/kmp_automaton.py
$ 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]
Output 25.3. The transition table of ababc over {a,b,c}\{a, b, c\}, and the two occurrences in a text.
The string-matching automaton of ababc, drawn from . The edges not drawn lead to state 0. From state 4 (abab read), an a leads to 3: ababa ends with aba.
The string-matching automaton of ababc, drawn from Output 25.3. The edges not drawn lead to state 00. From state 44 (abab read), an a leads to 33: ababa ends with aba.

The table has (m+1)∣Σ∣(m + 1)|\Sigma| entries. For bytes that is 256256 columns, which is why programs usually keep the failure function, of size mm, 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 mm letters is a number in base 256256, and two equal words give equal numbers; reduced modulo a prime qq, 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 T[s..s+m−1]T[s..s+m-1] is hs=∑j=0m−1T[s+j] 256m−1−j mod qh_s = \sum_{j=0}^{m-1} T[s + j]\, 256^{m-1-j} \bmod q. It satisfies hs+1=((hs−T[s]⋅256m−1)⋅256+T[s+m]) mod qh_{s+1} = ((h_s - T[s] \cdot 256^{m-1}) \cdot 256 + T[s + m]) \bmod q. A shift whose hash equals the pattern’s, hs=h(P)h_s = h(P), but which is not an occurrence, is a spurious hit.

Method 25.11 (Rabin–Karp)

Compute h(P)h(P) and h0h_0, then h1,h2,…h_1, h_2, \dots by the rolling formula. At each shift with hs=h(P)h_s = h(P), compare the window with PP 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
Listing 25.6. Rabin–Karp: a constant number of arithmetic operations per shift, and a check on equal hashes code/bachelor-2/25-text-algorithms/listings/rabin_karp.py

Proposition 25.12 (Expected spurious hits)

If every window different from PP has hs=h(P)h_s = h(P) with probability at most 1/q1/q, the expected number of spurious hits is at most (n−m+1)/q(n - m + 1)/q, and the expected cost of the checks on them at most m(n−m+1)/qm(n - m + 1)/q.

Proof. The number of spurious hits is a sum over the n−m+1n - m + 1 shifts of indicator variables, each of expectation at most 1/q1/q; the expectation of a sum is the sum of the expectations. Each spurious hit costs at most mm comparisons. ∎

The hypothesis is a model, not a theorem about a fixed qq: 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)
Output 25.4. Spurious hits on the archive. With q=97q = 97, hundreds, near the model’s estimate (n−m+1)/q(n - m + 1)/q; with q=1,000,003q = 1{,}000{,}003, none.

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
Listing 25.7. A trie: each node maps letters to subtries; the words under a prefix in alphabetical order code/bachelor-2/25-text-algorithms/listings/trie.py

Proposition 25.14 (Trie operations)

A trie of words of total length LL has at most L+1L + 1 nodes. Inserting or finding a word of length kk takes kk lookups in the children’s tables; listing the rr words that start with a prefix uu takes ∣u∣|u| lookups and a walk of the subtrie below uu, whose size is at most the total length of those rr words plus one.

Proof. Each node except the root is created by one letter of one inserted word, so there are at most LL of them. Insertion and search follow one edge per letter. The words under uu are those spelled by the marked nodes of the subtrie at uu, 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' *
Output 25.5. The 24 street names in 164 nodes instead of 258 letters, completions, and the compressed trie of eight names.
The compressed trie of eight street names, printed by : each chain of single children is one edge labelled by a word. A filled node ends a name. The trie itself has 47 nodes, this one 14.
The compressed trie of eight street names, printed by Output 25.5: each chain of single children is one edge labelled by a word. A filled node ends a name. The trie itself has 47 nodes, this one 14.

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 00 to 255255. It repeatedly reads the longest word ww of the dictionary that the input starts with, emits its number, and adds to the dictionary ww 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)
Listing 25.8. LZW: the encoder, and the decoder that rebuilds its dictionary, with the code that is not yet in it code/bachelor-2/25-text-algorithms/listings/lzw.py
$ 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
Output 25.6. LZW on two short texts. In 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 (k+1)(k+1)-st code, k≥1k \geq 1, its table holds the 256+k−1256 + k - 1 entries that the encoder’s held when it emitted the kk-th code.

Proof. Let w1,w2,…w_1, w_2, \dots be the words whose codes the encoder emits, in order; the input is their concatenation. The encoder adds the entry 256+k−1256 + k - 1 as wkw_k followed by the next input byte, which is the first byte of wk+1w_{k+1}, at the moment it emits the code of wkw_k. By induction on kk, assume the decoder has output w1,…,wkw_1, \dots, w_k and that its table holds the entries up to 256+k−2256 + k - 2, the encoder’s when it emitted wkw_k; this holds for k=1k = 1. The encoder emitted the code of wk+1w_{k+1} with entries up to 256+k−1256 + k - 1, so the code is at most 256+k−1256 + k - 1. If it is smaller, the decoder’s table holds it and gives wk+1w_{k+1}. If it equals 256+k−1256 + k - 1, the entry the decoder does not have yet, then wk+1w_{k+1} is wkw_k followed by the first byte of wk+1w_{k+1}; that byte is then the first byte of wkw_k, so wk+1=wk wk[0]w_{k+1} = w_k\, w_k[0], which is what the decoder computes. In both cases it then adds wkw_k followed by the first byte of wk+1w_{k+1}, the entry 256+k−1256 + k - 1 of the encoder. ∎

The special case happens whenever the input contains x v x v xx\,v\,x\,v\,x with xx a byte and xvxv in the dictionary, as in abababaabababa; 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
Output 25.7. The archive compressed three ways. Huffman codes bytes; LZW, with each code written on just enough bits for the dictionary’s size, codes repeated words; zlib combines both.

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 ana^n with the pattern a99ba^{99}b:

$ 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
Output 25.8. Measured on the author’s laptop: comparisons are exactly m(n−m+1)m(n - m + 1) and 2n−m2n - m, for m=100m = 100; times are the best of three runs.
On logarithmic axes, both times are lines of slope 1: both costs are linear in n for a fixed pattern. The comparisons are in the ratio m/2 = 50, the measured times about 33 apart: the naive search pays for every letter of the pattern at every shift, KMP for at most two comparisons per text letter.
On logarithmic axes, both times are lines of slope 1: both costs are linear in nn for a fixed pattern. The comparisons are in the ratio m/2=50m/2 = 50, the measured times about 33 apart: the naive search pays for every letter of the pattern at every shift, KMP for at most two comparisons per text letter.

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 nn; what grows without bound is the factor mm, 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 q=6q = 6, 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
Output 25.10. The failure function of aabaaab.

Exercise 25.2 ★

The function kmp_short of exo_kmp_bug.py is a shorter KMP: on a mismatch it sets q←π(q)q \gets \pi(q) 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]
Output 25.11. The shorter version against the expected occurrences.

After q←π(q)q \gets \pi(q) the pattern has moved, and the letter cc that caused the mismatch must be compared with P[π(q)]P[\pi(q)]; 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, qq becomes 11, and that a should have made it 22. When π(q)=0\pi(q) = 0 and c≠P[0]c \neq P[0], as in the first and last tests, nothing is lost. The correction is the inner while loop of Listing 25.4, which compares cc again until it matches or q=0q = 0.

Exercise 25.3 ★

After an occurrence, Listing 25.3 moves by one. Prove that moving by m−π(m)m - \pi(m) skips no occurrence, implement it, and compare the comparisons made on abababababa with aba, on a30a^{30} with a5a^5, and on the archive.

Solution

Solution of Exercise 25.3.

If ss and s+ds + d are both occurrences with 0<d<m0 < d < m, then P[d..m−1]=T[s+d..s+m−1]=P[0..m−d−1]P[d..m-1] = T[s+d..s+m-1] = P[0..m-d-1]: the pattern has a border of length m−dm - d. So m−d≤π(m)m - d \leq \pi(m), that is d≥m−π(m)d \geq m - \pi(m), 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
Boyer–Moore, with the period of the pattern as the shift after an occurrence code/bachelor-2/25-text-algorithms/listings/exo_bm_all.py
$ 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
Output 25.12. Comparisons before and after the change, with the same occurrences.

The gain is small: aba has period 22, a5a^5 period 11 (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 ana^n with am−1ba^{m-1}b, and on ana^n with bam−1ba^{m-1}. Do the same for Boyer–Moore with the bad-character rule.

Solution

Solution of Exercise 25.4.

Naive search: on ana^n with am−1ba^{m-1}b, every shift compares mm letters, m(n−m+1)m(n - m + 1) in all; with bam−1ba^{m-1}, every shift fails at once, n−m+1n - m + 1. Boyer–Moore compares from the right, so the roles swap. With am−1ba^{m-1}b, the b fails against a at j=m−1j = m - 1, with λ(a)=m−2\lambda(a) = m - 2: one comparison and a shift of 11, n−m+1n - m + 1 in all. With bam−1ba^{m-1}, the m−1m - 1 letters a match and the b fails at j=0j = 0, with λ(a)=m−1\lambda(a) = m - 1: the shift is max⁡(1,−(m−1))=1\max(1, -(m-1)) = 1, so m(n−m+1)m(n - m + 1) 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
Output 25.13. The codes (spaces written _) 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
Output 25.14. The decoder that looks every code up.

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 wk+1=wk wk[0]w_{k+1} = w_k\, w_k[0]: the input contains xvxvxx v x v x with xx a byte, xvxv the dictionary word wkw_k read at that point, and xvxxvx a new entry.

Exercise 25.7 ★★

Write first_k(trie, prefix, k), which returns the first kk 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 kk 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
The first kk completions, and the nodes visited code/bachelor-2/25-text-algorithms/listings/exo_autocomplete.py
$ 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
Output 25.15. Completions of four prefixes among the 80 book titles; the walk visits a fraction of the subtrie.

Exercise 25.8 ★★

Show that the bound of Theorem 25.8 is attained: KMP makes exactly 2n−m2n - m comparisons on ana^n with am−1ba^{m-1}b, for n≥m≥2n \geq m \geq 2.

Solution

Solution of Exercise 25.8.

Here π(q)=q−1\pi(q) = q - 1 for q≤m−1q \leq m - 1, since aq−1a^{q-1} is the longest border of aqa^q. The first m−1m - 1 letters each match with one comparison: q=m−1q = m - 1. For each letter at i=m−1,…,n−2i = m - 1, \dots, n - 2, the b of the pattern fails against a, qq becomes m−2m - 2, the shift i−(m−2)≤n−mi - (m - 2) \leq n - m still fits, and P[m−2]=aP[m - 2] = a matches: two comparisons, and q=m−1q = m - 1 again. At i=n−1i = n - 1 the b fails once, and the next shift, n−m+1n - m + 1, no longer fits. In all (m−1)+2(n−m)+1=2n−m(m - 1) + 2(n - m) + 1 = 2n - m. The C program confirms it for m=100m = 100: 399,900399{,}900 comparisons for n=200,000n = 200{,}000.

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
Rabin–Karp for several patterns: one rolling hash, a dictionary from hash values to patterns code/bachelor-2/25-text-algorithms/listings/exo_rk_multi.py
$ python exo_rk_multi.py
Forest: 88
Valley: 60
Bridge: 36
Silent: 72
Garden: 14
Hidden: 73
Output 25.16. Six words of six letters, each count checked against str.count.

The cost is O⁡(n)\BigO(n) 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 x≠yx \neq y be two windows of mm bytes, read as numbers below 256m256^m. Show that x−yx - y has fewer than 8m8m distinct prime divisors. Deduce that if qq is chosen at random among the KK smallest primes, a fixed window different from PP is a spurious hit with probability below 8m/K8m/K, and bound the expected number of spurious hits.

Solution

Solution of Exercise 25.10.

The difference x−yx - y is a non-zero integer with ∣x−y∣<256m=28m|x - y| < 256^m = 2^{8m}. If it had 8m8m distinct prime divisors, their product, at least 28m2^{8m}, would divide it, which is impossible: it has fewer than 8m8m. A window x≠Px \neq P is a spurious hit for the modulus qq when x≡P(modq)x \equiv P \pmod q, that is when qq divides x−Px - P. With qq uniform among the KK smallest primes, this has probability below 8m/K8m/K. Summing over the n−m+1n - m + 1 shifts, the expected number of spurious hits is below 8m(n−m+1)/K8m(n - m + 1)/K; with KK of the order of mnmn, it is a constant, and the expected cost is O⁡(n+m)\BigO(n + m) plus the occurrences’ checks. The bound holds for every text, chosen before qq: 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 π\pi. 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
A trie of patterns with failure links, and a search that reads the text once code/bachelor-2/25-text-algorithms/listings/exo_aho.py
$ python exo_aho.py
[(1, 'she'), (2, 'he'), (2, 'hers')]
2042 occurrences of 7 words in one pass, as str.count finds
Output 25.17. In 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 ii-th code that LZW writes stands for at most ii letters. Deduce that no text of nn letters is coded in fewer than ⌈(8n+1−1)/2⌉\lceil (\sqrt{8n+1}-1)/2 \rceil 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 ii. Before the ii-th code the dictionary holds the single letters and the i−1i - 1 entries added so far; the entry added after code jj is that code’s word plus one letter, so it has at most j+1≤ij + 1 \leq i letters by the hypothesis for j<ij < i. The ii-th code is a word of that dictionary: at most ii letters. A text of nn letters coded in cc codes therefore has n≤1+2+⋯+c=c(c+1)/2n \leq 1 + 2 + \dots + c = c(c+1)/2, and solving c2+c−2n≥0c^2 + c - 2n \geq 0 gives c≥⌈(8n+1−1)/2⌉c \geq \lceil (\sqrt{8n+1}-1)/2 \rceil. Code ii reaches its limit only if it is the entry just added, the word of code i−1i - 1 followed by the first letter of code ii, which is the first letter of code i−1i - 1; by induction every letter is the text’s first letter, so the text is one letter repeated, ana^n, 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
Output 25.18. The limit checked on random texts over a and b, and met by ana^n.

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
Output 25.9. The archive searched, its 60 borrowers’ names in a trie, LZW on ana^n, and LZW on growing parts of the archive.

Part I — Searching.

  1. Each line of the archive starts with On 2025-. What does this mean for the naive search of On 2025-12-1, compared with a phrase that starts with a rare letter?
  2. Explain why the naive search makes about 1.11.1 comparisons per letter on the archive and not mm.
  3. Boyer–Moore makes 6,8656{,}865 comparisons for returned Seven Forest. Estimate the average jump, and say which letters of the archive give the longest jumps.
  4. Give a phrase of the archive’s kind for which Boyer–Moore with the bad-character rule is slow, and explain why.
  5. Why can Boyer–Moore not report the occurrences in a stream, one letter at a time, as KMP does?
  6. 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.

  1. Compute the failure function of returned Under the.
  2. From it, explain why KMP and the naive search make almost the same number of comparisons on the archive.
  3. Using Theorem 25.8, bound the comparisons of KMP for this pattern, and compare with the 91,58191{,}581 observed.
  4. On the text ana^n with a99ba^{99}b, how many comparisons does each search make for n=106n = 10^6? Check with Output 25.8.
  5. The measured times grow linearly for both. Why is the naive search linear in nn here, and in which quantity is it not?
  6. Draw the string-matching automaton of aab over {a,b}\{a, b\}.

Part III — A trie for autocompletion.

  1. The 60 names have 751 letters and the trie 600 nodes, 599 below the root. What do the 152 letters saved correspond to?
  2. How many nodes does a lookup of Leo B visit, and how does that depend on the number of names?
  3. Compare with a sorted list of the names searched by halves: what does each structure cost for a prefix query?
  4. How many nodes would the compressed trie of the 60 names have at most?
  5. A user types G, then r, then a. How should the program avoid walking from the root at each letter?
  6. Should the trie store first names and last names separately for completing either? Discuss the size.

Part IV — Compression.

  1. Encode a10a^{10} by hand and list the entries added.
  2. Prove that LZW codes ana^n in ⌈(8n+1−1)/2⌉\lceil (\sqrt{8n+1}-1)/2 \rceil codes, and check the values printed for n=55n = 55, 50505050 and 50515051.
  3. The number of bytes per code grows from 2.22.2 to 7.77.7 along the archive. Explain why.
  4. 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.
  5. Why does Huffman coding of bytes give a ratio of 1.631.63 and no more, whatever the length of the archive?
  6. State the problem’s result: LZW on ana^n: exactly ⌈(8n+1−1)/2⌉\lceil (\sqrt{8n+1} - 1)/2 \rceil 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 nn plus the total length of the partial matches, small on ordinary text.

3. About 87,299/6,865≈1387{,}299 / 6{,}865 \approx 13 letters per comparison, and nearly every shift makes one comparison, so the average jump is about 13. The longest jumps, 2121, 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 mm 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 qq, saved at the end of the day. The other two must keep the last m−1m - 1 letters of yesterday.

7. π\pi is 00 everywhere except π(5)=1\pi(5) = 1 and π(14)=1\pi(14) = 1: the only borders are r, for retur and returned Under.

8. After a mismatch KMP falls back to q=0q = 0 or 11 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. 2n−m=2×87,299−18=174,5802n - m = 2 \times 87{,}299 - 18 = 174{,}580. The observed 91,58191{,}581 is about nn: the bound counts a second comparison for every letter, which only a pattern with long borders on a matching text forces.

10. Naive: 100×(106−99)=99,990,100100 \times (10^6 - 99) = 99{,}990{,}100; KMP: 2×106−100=1,999,9002 \times 10^6 - 100 = 1{,}999{,}900, as printed.

11. For a fixed pattern, m(n−m+1)m(n - m + 1) is linear in nn with slope mm. It is not linear in the size of the input n+mn + m: for m=n/2m = n/2 it is about n2/4n^2/4.

12. States 00 to 33: δ(0,a)=1\delta(0, a) = 1, δ(1,a)=2\delta(1, a) = 2, δ(2,a)=2\delta(2, a) = 2, δ(2,b)=3\delta(2, b) = 3, δ(3,a)=1\delta(3, a) = 1, and every other transition leads to 00.

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 152=751−599152 = 751 - 599 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, O⁡(∣u∣log⁡N)\BigO(|u| \log N) letter comparisons for NN names, then reads the rr answers in order. The trie needs ∣u∣|u| steps and the walk of the subtrie. Both are fast for 60 names; the trie does not depend on NN.

16. Each node other than the root has two children or more or ends a name, and there are 60 names, so at most 5959 branching nodes besides the 60 ends: at most 2×60=1202 \times 60 = 120 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 2×751+12 \times 751 + 1 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 97,256,257,25897, 256, 257, 258; the entries 256=aa256 = \texttt{aa}, 257=aaa257 = \texttt{aaa}, 258=aaaa258 = \texttt{aaaa}, and nothing after the last code, which ends the input.

20. By induction, the kk-th code is that of aka^k and adds ak+1a^{k+1}, as long as at least k+1k + 1 letters remain: before it, the dictionary holds a,a2,…,aka, a^2, \dots, a^k and no longer power of aa, and the input left starts with ak+1a^{k+1}, so the longest dictionary word is aka^k, followed by an a. After cc such codes, 1+2+⋯+c=c(c+1)/21 + 2 + \dots + c = c(c+1)/2 letters are coded. The last code takes the r≤c+1r \leq c + 1 letters left, which form a dictionary word. The number of codes is therefore the least cc with c(c+1)/2≥nc(c+1)/2 \geq n, the bound of Exercise 25.12: c=⌈(8n+1−1)/2⌉c = \lceil (\sqrt{8n+1}-1)/2 \rceil.

$ 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
Output 25.19. The number of codes for n=1,…,21n = 1, \dots, 21, and the formula checked up to 3000.

For n=55=10⋅11/2n = 55 = 10 \cdot 11/2, c=10c = 10; for 5050=100⋅101/25050 = 100 \cdot 101/2, c=100c = 100; one more letter needs one more code, 101101.

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. 11,383×2=22,76611{,}383 \times 2 = 22{,}766 bytes, against 18,09518{,}095 with codes of 9 to 14 bits; the largest code, 256+11,382256 + 11{,}382, 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 88 divided by the average code length, about 4.9 bits here, and it cannot use the repeated words.

24. LZW on ana^n: exactly ⌈(8n+1−1)/2⌉\lceil (\sqrt{8n+1}-1)/2 \rceil codes; on the archive, 11,38311{,}383 codes for 87,29987{,}299 bytes, 7.77.7 bytes per code and a ratio of 4.824.82 with growing code widths, against 1.631.63 for Huffman and 8.638.63 for zlib.

本章定义的术语

在术语表中查看全部 1050 个术语