---
title: "Text Algorithms and Compression"
book: "University Computer Science — Year 2"
subject: computer-science
language: en
chapter: 25
exercises: 12
source: https://one-course.com/books/computer-science/4/en/chapter/25-text-algorithms-and-compression
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 25 — Text 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:

```python
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)")
```

***Listing 25.1.** Two phrases looked for in the archive by the naive search, by Boyer–Moore and by Knuth–Morris–Pratt, counting letter comparisons code/bachelor-2/25-text-algorithms/listings/search.py*

```
$ 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)
```

***Output 25.1.** The same [occurrences](#def-b2-text-algorithms-matching), three costs: Boyer–Moore looks at about one letter in ten.*

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 $m$ comparisons per letter for a pattern of $m$ 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](#def-b2-text-algorithms-matching) in a text, the naive search, Horspool’s shift table. [Chapter 21](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#ch-b2-finite-automata): 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]$ be a *text* and $P = P[0..m-1]$ a *pattern*, words over an [alphabet](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-word) $\Sigma$, with $1 \leq
m$. A *shift* is an integer $s$ with $0 \leq s \leq n - m$; it is an *occurrence* of $P$ when $T[s + j] = P[j]$ for $0 \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.

```python
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)$ comparisons, and exactly that many on the text $a^n$ with the pattern $a^{m-1}b$.

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

On ordinary text the first comparison of a shift usually fails, and the cost is close to $n$, as in [Output 25.1](#out-b2-text-algorithms-search). 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 $P$ with the text at shift $s$ from the right, and let $j$ be the position of the first difference, with $c =
T[s + j]$ the *bad character*. Let $\lambda(c)$ be the last position of $c$ in $P$, or $-1$ if $c$ does not occur in $P$. The *bad-character rule* moves to the shift $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.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-text-algorithms/fig-6693adaf7234.svg)

*The [bad-character rule](#def-b2-text-algorithms-bad-char). 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](#def-b2-text-algorithms-bad-char) never jumps over an [occurrence](#def-b2-text-algorithms-matching): no shift $s'$ with $s < s' < s + \max(1, j - \lambda(c))$ is an [occurrence](#def-b2-text-algorithms-matching).

**Proof.** A shift $s' = s + d$ with $0 < d < j - \lambda(c)$ puts the pattern’s position $j - d$ under the text position $s + j$, which holds $c$. Since $j - d > \lambda(c)$, and $\lambda(c)$ is the last position of $c$ in $P$, $P[j - d] \neq c$: the shift $s'$ is not an [occurrence](#def-b2-text-algorithms-matching). If $j - \lambda(c) \leq 1$, the rule moves by $1$ and skips nothing. ∎

```python
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](#def-b2-text-algorithms-bad-char) code/bachelor-2/25-text-algorithms/listings/boyer_moore.py*

When the bad character does not occur in the pattern, the jump is $j + 1$, up to $m$; on ordinary text with a long pattern, most shifts are skipped unread, which explains the tenfold saving of [Output 25.1](#out-b2-text-algorithms-search). The worst case is still $m(n - m + 1)$, on $a^n$ with $ba^{m-1}$. Boyer and Moore’s algorithm adds a second rule, the *good [suffix](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-factor)*, which uses the part already matched; with it, the search for the first [occurrence](#def-b2-text-algorithms-matching) becomes linear. Reporting all [occurrences](#def-b2-text-algorithms-matching) in linear time needs one more refinement (Galil’s rule): on $a^n$ with $a^m$ every shift is an [occurrence](#def-b2-text-algorithms-matching), and the good [suffix](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-factor) moves by one and reads the $m$ letters again ([Exercise 25.3](#exo-b2-text-algorithms-3)). KMP reaches the linear bound for all [occurrences](#def-b2-text-algorithms-matching) with the matched part alone, and from the left.

## 25.3 Knuth–Morris–Pratt

When the naive search fails after matching $q$ letters, it starts again one letter further and reads again text that it has already seen. Those $q$ letters are known: they are $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 $u$ is a word that is both a proper prefix and a proper [suffix](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-factor) of $u$ (the [empty word](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-word) is always one). The *failure function* of $P$ is $\pi(q)$, the length of the longest border of $P[0..q-1]$, for $1 \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.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-text-algorithms/fig-47706a16420f.svg)

*A mismatch after $q = 5$ letters of `abababc`. The matched part `ababa` has the longest [border](#def-b2-text-algorithms-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$.*

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

**Method 25.6 (Knuth–Morris–Pratt).**

Compute $\pi$. Then read the text once, keeping $q$, the number of pattern letters matched. For each text letter $c$: while $q > 0$ and $P[q] \neq c$, set $q \gets \pi(q)$; if $P[q] = c$, increase $q$. When $q = m$, report the [occurrence](#def-b2-text-algorithms-matching) ending here and set $q \gets \pi(m)$. Stop when the pattern, placed at shift $i - q$, no longer fits in the text.

```python
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](#def-b2-text-algorithms-border) and the KMP search; the text index $i$ 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](#def-b2-text-algorithms-border), written $q{:}\pi(q)$. A pattern with no repeated prefix, such as a date, has $\pi = 0$ everywhere.*

The [failure function](#def-b2-text-algorithms-border) is computed by the same search, run on the pattern against itself: `k` is the longest [border](#def-b2-text-algorithms-border) of the prefix read so far, extended by one letter when the next letters agree, and shortened along the chain $k, \pi(k),
\pi(\pi(k)), \dots$ of ever shorter [borders](#def-b2-text-algorithms-border) otherwise. The chain lists all [borders](#def-b2-text-algorithms-border), because a [border](#def-b2-text-algorithms-border) of a [border](#def-b2-text-algorithms-border) of $u$ is a [border](#def-b2-text-algorithms-border) of $u$, and the longest [border](#def-b2-text-algorithms-border) shorter than $\pi(q)$ is $\pi(\pi(q))$.

**Proposition 25.7 (The failure function in linear time).**

`failure` computes $\pi$ in $\BigO(m)$ steps.

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

**Theorem 25.8 (KMP is linear).**

The search of [Listing 25.4](#lst-b2-text-algorithms-kmp) makes at most $2n - m$ comparisons on a text of length $n \geq m$.

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

The argument is a potential argument with the potential $i + 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](#def-b2-text-algorithms-border) is followed, but each of those comparisons moves the pattern forward for good.

**Definition 25.9 (String-matching automaton).**

The *string-matching automaton* of $P$ over $\Sigma$ is the DFA with states $0,
\dots, m$, start state $0$, [accepting state](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-dfa) $m$, and transition $\delta(q, c)$ the length of the longest prefix of $P$ that is a [suffix](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-factor) of $P[0..q-1]c$.

The automaton reads the text once, one transition per letter, and is in state $m$ exactly at the end of each [occurrence](#def-b2-text-algorithms-matching). It is KMP with every chain of [borders](#def-b2-text-algorithms-border) followed in advance: $\delta(q, c) = q + 1$ when $P[q] = c$, and otherwise $\delta(q, c) = \delta(\pi(q), c)$, or $0$ from state $0$.

```python
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](#def-b2-text-algorithms-border), 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\}$, and the two [occurrences](#def-b2-text-algorithms-matching) 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.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-text-algorithms/fig-e47cd8a7cf11.svg)

*The [string-matching automaton](#def-b2-text-algorithms-automaton) of `ababc`, drawn from [Output 25.3](#out-b2-text-algorithms-automaton). The edges not drawn lead to state $0$. From state $4$ (`abab` read), an `a` leads to $3$: `ababa` ends with `aba`.*

The table has $(m + 1)|\Sigma|$ entries. For bytes that is $256$ columns, which is why programs usually keep the [failure function](#def-b2-text-algorithms-border), of size $m$, 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 $m$ letters is a number in base $256$, and two equal words give equal numbers; reduced modulo a prime $q$, 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]$ is $h_s = \sum_{j=0}^{m-1} T[s + j]\, 256^{m-1-j}
\bmod q$. It satisfies $h_{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, $h_s = h(P)$, but which is not an [occurrence](#def-b2-text-algorithms-matching), is a *spurious hit*.

**Method 25.11 (Rabin–Karp).**

Compute $h(P)$ and $h_0$, then $h_1, h_2, \dots$ by the rolling formula. At each shift with $h_s = h(P)$, compare the window with $P$ letter by letter: report it if they agree, count a [spurious hit](#def-b2-text-algorithms-rolling) otherwise.

```python
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 $P$ has $h_s = h(P)$ with probability at most $1/q$, the expected number of [spurious hits](#def-b2-text-algorithms-rolling) is at most $(n - m + 1)/q$, and the expected cost of the checks on them at most $m(n - m + 1)/q$.

**Proof.** The number of [spurious hits](#def-b2-text-algorithms-rolling) is a sum over the $n - m + 1$ shifts of indicator variables, each of expectation at most $1/q$; the expectation of a sum is the sum of the expectations. Each [spurious hit](#def-b2-text-algorithms-rolling) costs at most $m$ comparisons. ∎

The hypothesis is a model, not a theorem about a fixed $q$: 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](#exo-b2-text-algorithms-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](#def-b2-text-algorithms-rolling) on the archive. With $q = 97$, hundreds, near the model’s estimate $(n - m + 1)/q$; with $q = 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](#exo-b2-text-algorithms-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.

```python
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](#def-b2-text-algorithms-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](#def-b2-text-algorithms-trie) of words of total length $L$ has at most $L + 1$ nodes. Inserting or finding a word of length $k$ takes $k$ lookups in the children’s tables; listing the $r$ words that start with a prefix $u$ takes $|u|$ lookups and a walk of the subtrie below $u$, whose size is at most the total length of those $r$ words plus one.

**Proof.** Each node except the root is created by one letter of one inserted word, so there are at most $L$ of them. Insertion and search follow one edge per letter. The words under $u$ are those spelled by the marked nodes of the subtrie at $u$, 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](#def-b2-text-algorithms-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.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-text-algorithms/fig-3b3d43dab4ca.svg)

*The compressed [trie](#def-b2-text-algorithms-trie) of eight street names, printed by [Output 25.5](#out-b2-text-algorithms-trie): each chain of single children is one edge labelled by a word. A filled node ends a name. The [trie](#def-b2-text-algorithms-trie) itself has 47 nodes, this one 14.*

In a *compressed [trie](#def-b2-text-algorithms-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](#def-b2-text-algorithms-trie) of patterns with, at each node, a link to the longest [suffix](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-factor) of its word that is also a node finds every [occurrence](#def-b2-text-algorithms-matching) of many patterns in one pass over a text, the way KMP does for one ([Exercise 25.11](#exo-b2-text-algorithms-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](#def-b2-text-algorithms-lzw) 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 $0$ to $255$. It repeatedly reads the longest word $w$ of the dictionary that the input starts with, emits its number, and adds to the dictionary $w$ 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.

```python
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)$-st code, $k \geq 1$, its table holds the $256 + k - 1$ entries that the encoder’s held when it emitted the $k$-th code.

**Proof.** Let $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 - 1$ as $w_k$ followed by the next input byte, which is the first byte of $w_{k+1}$, at the moment it emits the code of $w_k$. By induction on $k$, assume the decoder has output $w_1, \dots, w_k$ and that its table holds the entries up to $256 + k - 2$, the encoder’s when it emitted $w_k$; this holds for $k = 1$. The encoder emitted the code of $w_{k+1}$ with entries up to $256 + k - 1$, so the code is at most $256 + k - 1$. If it is smaller, the decoder’s table holds it and gives $w_{k+1}$. If it equals $256 + k - 1$, the entry the decoder does not have yet, then $w_{k+1}$ is $w_k$ followed by the first byte of $w_{k+1}$; that byte is then the first byte of $w_k$, so $w_{k+1}
= w_k\, w_k[0]$, which is what the decoder computes. In both cases it then adds $w_k$ followed by the first byte of $w_{k+1}$, the entry $256 + k - 1$ of the encoder. ∎

The special case happens whenever the input contains $x\,v\,x\,v\,x$ with $x$ a byte and $xv$ in the dictionary, as in $abababa$; a decoder without it works on most inputs and fails on these ([Exercise 25.6](#exo-b2-text-algorithms-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](#pb-b2-text-algorithms-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](#def-b2-text-algorithms-matching) (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](#prop-b2-text-algorithms-naive) and [Theorem 25.8](#thm-b2-text-algorithms-kmp-linear) turn into time. The same two searches in C, on the text $a^n$ with the pattern $a^{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)$ and $2n - m$, for $m = 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.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-text-algorithms/fig-794d8bc1a4f4.svg)

*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.*

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 $n$; what grows without bound is the factor $m$, and patterns of a thousand letters make it a thousand.

## 25.8 Exercises

**Exercise 25.1 ★.**

Compute the [failure function](#def-b2-text-algorithms-border) of `aabaaab` by hand, then check with `exo_failure.py`.

**Solution of Exercise 25.1.**

For the prefixes `a`, `aa`, `aab`, `aaba`, `aabaa`, `aabaaa`, `aabaaab` the longest [borders](#def-b2-text-algorithms-border) are the [empty word](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-word), `a`, the [empty word](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-word), `a`, `aa`, `aa` and `aab`. For $q = 6$, the [border](#def-b2-text-algorithms-border) `aa` of `aabaa` cannot be extended (`aab` is not a [suffix](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-factor) of `aabaaa`), but the shorter [border](#def-b2-text-algorithms-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](#def-b2-text-algorithms-border) of `aabaaab`.*

**Exercise 25.2 ★.**

The function `kmp_short` of `exo_kmp_bug.py` is a shorter KMP: on a mismatch it sets $q \gets \pi(q)$ and moves to the next letter. On which texts does it miss an [occurrence](#def-b2-text-algorithms-matching)? Correct it.

**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](#def-b2-text-algorithms-matching).*

After $q \gets \pi(q)$ the pattern has moved, and the letter $c$ that caused the mismatch must be compared with $P[\pi(q)]$; `kmp_short` skips it. It misses an [occurrence](#def-b2-text-algorithms-matching) whenever that letter is the start of the continued match: on `aaab`, after `aa` the third `a` fails against `b`, $q$ becomes $1$, and that `a` should have made it $2$. When $\pi(q) = 0$ and $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](#lst-b2-text-algorithms-kmp), which compares $c$ again until it matches or $q = 0$.

**Exercise 25.3 ★.**

After an [occurrence](#def-b2-text-algorithms-matching), [Listing 25.3](#lst-b2-text-algorithms-boyer-moore) moves by one. Prove that moving by $m - \pi(m)$ skips no [occurrence](#def-b2-text-algorithms-matching), implement it, and compare the comparisons made on `abababababa` with `aba`, on $a^{30}$ with $a^5$, and on the archive.

**Solution of Exercise 25.3.**

If $s$ and $s + d$ are both [occurrences](#def-b2-text-algorithms-matching) with $0 < d < m$, then $P[d..m-1] = T[s+d..s+m-1] = P[0..m-d-1]$: the pattern has a [border](#def-b2-text-algorithms-border) of length $m - d$. So $m - d \leq \pi(m)$, that is $d \geq m - \pi(m)$, and the shifts between are not [occurrences](#def-b2-text-algorithms-matching).

```python
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](#def-b2-text-algorithms-matching) 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](#def-b2-text-algorithms-matching).*

The gain is small: `aba` has period $2$, $a^5$ period $1$ (no gain), and the archive’s [occurrences](#def-b2-text-algorithms-matching) 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 $a^n$ with $a^{m-1}b$, and on $a^n$ with $ba^{m-1}$. Do the same for Boyer–Moore with the [bad-character rule](#def-b2-text-algorithms-bad-char).

**Solution of Exercise 25.4.**

Naive search: on $a^n$ with $a^{m-1}b$, every shift compares $m$ letters, $m(n - m + 1)$ in all; with $ba^{m-1}$, every shift fails at once, $n - m + 1$. Boyer–Moore compares from the right, so the roles swap. With $a^{m-1}b$, the `b` fails against `a` at $j = m - 1$, with $\lambda(a) = m - 2$: one comparison and a shift of $1$, $n - m + 1$ in all. With $ba^{m-1}$, the $m - 1$ letters `a` match and the `b` fails at $j = 0$, with $\lambda(a) = m - 1$: the shift is $\max(1, -(m-1)) = 1$, so $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 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 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](#thm-b2-text-algorithms-lzw), it fails exactly on the inputs where the encoder emits a code at the step right after creating it, that is where $w_{k+1} = w_k\,
w_k[0]$: the input contains $x v x v x$ with $x$ a byte, $xv$ the dictionary word $w_k$ read at that point, and $xvx$ a new entry.

**Exercise 25.7 ★★.**

Write `first_k(trie, prefix, k)`, which returns the first $k$ 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 of Exercise 25.7.**

The walk of `words` with a stop as soon as $k$ words are found; the smallest letter is on top of the stack, so the words come out in alphabetical order.

```python
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 $k$ 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](#thm-b2-text-algorithms-kmp-linear) is attained: KMP makes exactly $2n - m$ comparisons on $a^n$ with $a^{m-1}b$, for $n \geq m \geq 2$.

**Solution of Exercise 25.8.**

Here $\pi(q) = q - 1$ for $q \leq m - 1$, since $a^{q-1}$ is the longest [border](#def-b2-text-algorithms-border) of $a^q$. The first $m - 1$ letters each match with one comparison: $q = m - 1$. For each letter at $i = m - 1, \dots, n - 2$, the `b` of the pattern fails against `a`, $q$ becomes $m - 2$, the shift $i - (m - 2) \leq n - m$ still fits, and $P[m - 2] = a$ matches: two comparisons, and $q = m - 1$ again. At $i = n - 1$ the `b` fails once, and the next shift, $n - m + 1$, no longer fits. In all $(m - 1) + 2(n - m) + 1 = 2n - m$. The C program confirms it for $m = 100$: $399{,}900$ comparisons for $n = 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 of Exercise 25.9.**

```python
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](#def-b2-text-algorithms-rolling), 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 $\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 \neq y$ be two windows of $m$ bytes, read as numbers below $256^m$. Show that $x - y$ has fewer than $8m$ distinct prime divisors. Deduce that if $q$ is chosen at random among the $K$ smallest primes, a fixed window different from $P$ is a [spurious hit](#def-b2-text-algorithms-rolling) with probability below $8m/K$, and bound the expected number of [spurious hits](#def-b2-text-algorithms-rolling).

**Solution of Exercise 25.10.**

The difference $x - y$ is a non-zero integer with $|x - y| < 256^m = 2^{8m}$. If it had $8m$ distinct prime divisors, their product, at least $2^{8m}$, would divide it, which is impossible: it has fewer than $8m$. A window $x \neq P$ is a [spurious hit](#def-b2-text-algorithms-rolling) for the modulus $q$ when $x \equiv P \pmod q$, that is when $q$ divides $x - P$. With $q$ uniform among the $K$ smallest primes, this has probability below $8m/K$. Summing over the $n - m + 1$ shifts, the expected number of [spurious hits](#def-b2-text-algorithms-rolling) is below $8m(n - m + 1)/K$; with $K$ of the order of $mn$, it is a constant, and the expected cost is $\BigO(n + m)$ plus the [occurrences](#def-b2-text-algorithms-matching)’ checks. The bound holds for every text, chosen before $q$: the randomness is in the algorithm, not in the input.

**Exercise 25.11 ★★★.**

Write a matcher for several patterns at once: a [trie](#def-b2-text-algorithms-trie) of the patterns, and for each node a failure link to the node of the longest proper [suffix](https://one-course.com/books/computer-science/4/en/chapter/21-finite-automata#def-b2-finite-automata-factor) of its word that is in the [trie](#def-b2-text-algorithms-trie), computed breadth first. Test it on `ushers` with `he`, `she`, `his`, `hers`, then on the archive.

**Solution of Exercise 25.11.**

This is the algorithm of Aho and Corasick. The [trie](#def-b2-text-algorithms-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.

```python
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](#def-b2-text-algorithms-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 $i$-th code that LZW writes stands for at most $i$ letters. Deduce that no text of $n$ letters is coded in fewer than $\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 of Exercise 25.12.**

By induction on $i$. Before the $i$-th code the dictionary holds the single letters and the $i - 1$ entries added so far; the entry added after code $j$ is that code’s word plus one letter, so it has at most $j + 1 \leq i$ letters by the hypothesis for $j < i$. The $i$-th code is a word of that dictionary: at most $i$ letters. A text of $n$ letters coded in $c$ codes therefore has $n \leq 1 + 2 + \dots + c = c(c+1)/2$, and solving $c^2 + c - 2n \geq 0$ gives $c \geq
\lceil (\sqrt{8n+1}-1)/2 \rceil$. Code $i$ reaches its limit only if it is the entry just added, the word of code $i - 1$ followed by the first letter of code $i$, which is the first letter of code $i - 1$; by induction every letter is the text’s first letter, so the text is one letter repeated, $a^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 $a^n$.*

## 25.9 Problem: The town archive

**Problem 25.1.**

Weekend problem — The town archive

The archive of [Listing 25.1](#lst-b2-text-algorithms-search) 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](#def-b2-text-algorithms-trie), LZW on $a^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.1$ comparisons per letter on the archive and not $m$ .
3. Boyer–Moore makes $6{,}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](#def-b2-text-algorithms-bad-char) is slow, and explain why.
5. Why can Boyer–Moore not report the [occurrences](#def-b2-text-algorithms-matching) 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.**

7. Compute the [failure function](#def-b2-text-algorithms-border) of `returned Under the` .
8. From it, explain why KMP and the naive search make almost the same number of comparisons on the archive.
9. Using [Theorem 25.8](#thm-b2-text-algorithms-kmp-linear) , bound the comparisons of KMP for this pattern, and compare with the $91{,}581$ observed.
10. On the text $a^n$ with $a^{99}b$ , how many comparisons does each search make for $n = 10^6$ ? Check with [Output 25.8](#out-b2-text-algorithms-bench) .
11. The measured times grow linearly for both. Why is the naive search linear in $n$ here, and in which quantity is it not?
12. Draw the [string-matching automaton](#def-b2-text-algorithms-automaton) of `aab` over $\{a, b\}$ .

**Part III — A trie for autocompletion.**

13. The 60 names have 751 letters and the [trie](#def-b2-text-algorithms-trie) 600 nodes, 599 below the root. What do the 152 letters saved correspond to?
14. How many nodes does a lookup of `Leo B` visit, and how does that depend on the number of names?
15. Compare with a sorted list of the names searched by halves: what does each structure cost for a prefix query?
16. How many nodes would the compressed [trie](#def-b2-text-algorithms-trie) of the 60 names have at most?
17. A user types `G` , then `r` , then `a` . How should the program avoid walking from the root at each letter?
18. Should the [trie](#def-b2-text-algorithms-trie) store first names and last names separately for completing either? Discuss the size.

**Part IV — Compression.**

19. Encode $a^{10}$ by hand and list the entries added.
20. Prove that LZW codes $a^n$ in $\lceil (\sqrt{8n+1}-1)/2 \rceil$ codes, and check the values printed for $n = 55$ , $5050$ and $5051$ .
21. The number of bytes per code grows from $2.2$ to $7.7$ along the archive. Explain why.
22. 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](#out-b2-text-algorithms-ratio) .
23. Why does Huffman coding of bytes give a ratio of $1.63$ and no more, whatever the length of the archive?
24. State the problem’s result: LZW on $a^n$ : exactly $\lceil (\sqrt{8n+1} - 1)/2 \rceil$ codes, and the measured ratio on the archive.

**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 $n$ plus the total length of the partial matches, small on ordinary text.

**3.** About $87{,}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, $21$, 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 $m$ 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](#def-b2-text-algorithms-matching) ends there.

**6.** KMP, or the automaton: its whole state is $q$, saved at the end of the day. The other two must keep the last $m - 1$ letters of yesterday.

**7.** $\pi$ is $0$ everywhere except $\pi(5) = 1$ and $\pi(14) = 1$: the only [borders](#def-b2-text-algorithms-border) are `r`, for `retur` and `returned Under`.

**8.** After a mismatch KMP falls back to $q = 0$ or $1$ 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 \times 87{,}299 - 18 = 174{,}580$. The observed $91{,}581$ is about $n$: the bound counts a second comparison for every letter, which only a pattern with long [borders](#def-b2-text-algorithms-border) on a matching text forces.

**10.** Naive: $100 \times (10^6 - 99) = 99{,}990{,}100$; KMP: $2 \times 10^6 - 100 = 1{,}999{,}900$, as printed.

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

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

**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 - 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, $\BigO(|u| \log N)$ letter comparisons for $N$ names, then reads the $r$ answers in order. The [trie](#def-b2-text-algorithms-trie) needs $|u|$ steps and the walk of the subtrie. Both are fast for 60 names; the [trie](#def-b2-text-algorithms-trie) does not depend on $N$.

**16.** Each node other than the root has two children or more or ends a name, and there are 60 names, so at most $59$ branching nodes besides the 60 ends: at most $2 \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](#def-b2-text-algorithms-trie) of the names written as “last first” as well doubles the letters inserted, at most $2 \times 751 +
1$ nodes, and lets a prefix of either name be completed; two separate [tries](#def-b2-text-algorithms-trie) are the same size.

**19.** The codes of `a`, `aa`, `aaa`, `aaaa`, that is $97, 256, 257, 258$; the entries $256 = \texttt{aa}$, $257 = \texttt{aaa}$, $258 = \texttt{aaaa}$, and nothing after the last code, which ends the input.

**20.** By induction, the $k$-th code is that of $a^k$ and adds $a^{k+1}$, as long as at least $k + 1$ letters remain: before it, the dictionary holds $a, a^2, \dots, a^k$ and no longer power of $a$, and the input left starts with $a^{k+1}$, so the longest dictionary word is $a^k$, followed by an `a`. After $c$ such codes, $1 + 2 +
\dots + c = c(c+1)/2$ letters are coded. The last code takes the $r \leq c + 1$ letters left, which form a dictionary word. The number of codes is therefore the least $c$ with $c(c+1)/2 \geq n$, the bound of [Exercise 25.12](#exo-b2-text-algorithms-12): $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, \dots, 21$, and the formula checked up to 3000.*

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

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

**24.** LZW on $a^n$: exactly $\lceil (\sqrt{8n+1}-1)/2 \rceil$ codes; on the archive, $11{,}383$ codes for $87{,}299$ bytes, $7.7$ bytes per code and a ratio of $4.82$ with growing code widths, against $1.63$ for Huffman and $8.63$ for zlib.
