3  Strings

Call me Ishmael.

Herman Melville, Moby-Dick (1851)

3.1 How did that line go?

Leo is the life of the party. Somebody tells a story about a disastrous first date, and before the laughter settles Leo adds one line from a film everybody at the table has seen, and suddenly the story is bigger than itself. The line carries that whole film with it: the scene, the actor’s face, the night each of them first watched it. For a moment the table is in sync. Everyone is inside the shared experience, feeling part of something, understood. A good quote does that. That is Leo’s gift, and it is why he is invited everywhere. He never looked anything up. He just had the line.

Lately Leo’s memory is slipping. There is simply too much now: ten years of series watched late at night, podcasts on the way to work, films half-seen on planes, songs he never chose to learn but knows by heart. What used to fit on one shelf has become a flood, far more than anyone can keep track of. The lines are still in there, but they surface in pieces: a word, a rhythm, the place it fell in a scene. But a quote has to arrive in time. A minute late, the right line is just a man reciting. The moment it belonged to is gone. More than once the perfect line has come to him on the way home, word for word, with nobody left to whom he could say it. It doesn’t count. A nearly right quote is no better. It ruins the moment, someone corrects him, and everyone laughs at him instead of with him.

Tonight the conversation has turned to something that a book he loves has already put into words. There is a line for exactly this moment. Leo can feel its shape, something about November, something about weather inside a person. He can’t say it. He knows roughly where it lives, near the beginning of Moby-Dick, a few sentences after the three words everybody knows.

So he reaches under the table for his phone. The whole novel is there for free, about 1.2 million bytes of it. He types the fragment he’s surest of, drizzly November, into the search box. A pause, and there it is, “whenever it is a damp, drizzly November in my soul.” He says it, and it lands.

This chapter is about that pause. Leo’s phone just read the novel, all of it. It went through the text from the first character, lining his fragment up against it, until the characters agreed. Ask again a minute later, about a different line, and it reads the whole novel again from the start. Nothing it did the first time helps it the second time.

There is an older way to find things in a book, and it fails in the opposite direction. The index at the back is built once and answers instantly forever after. Look up whale, and there are the pages. But somebody built it by hand, it covers only the words that an editor chose to include, and it runs for pages. Nobody indexes drizzly. A search engine indexes it. It builds the same kind of list by machine, for every word of every page. That list, an inverted index, finds drizzly, and drizzly November as a phrase. The engine still can’t find a piece of a word, like zzly Nov, because it knows only the words into which it cut the text.

One way re-reads everything every time. The other answers at once, but it answers only what someone thought to include, and it takes up room doing it. Each idea in this chapter fixes what broke in the one before. The chapter starts by making the reading itself cheaper. Then it prepares the text once, first for fragments from the start of a quote and then for fragments from anywhere. Each preparation is bigger than the one before, until the index is larger than the book it indexes. The final one is an index that is smaller than the book, so complete that you could delete the book and still read any line of it back out of the index.

Leo’s phone held one novel. The ten books on which this chapter’s code was tested hold nearly seven million bytes of text.1 A service that answers “where is this line from?” for everyone holds every book, script and lyric anyone can quote, Leo’s whole flood and everyone else’s flood. That service is what makes each idea below necessary.

3.2 Reading the whole book, every time

Scanning and rolling fingerprints

Start with the plain way, the one that Leo’s phone used. The text has n characters and the fragment, the pattern, has m characters. Lay the pattern against the text at position 0 and compare character by character. The first time two characters differ, stop, slide the pattern one place to the right, and start comparing again. If you get through all m characters without a difference, you’ve found it. Every placement of the pattern is called a window of the text, the m characters it covers.

NoteTry first (no AI)

The text is abababababab and the pattern is ababc. Slide the pattern along by hand and count every single character comparison you make before you can say not found. Then say what the worst case costs in general, for a text of n characters and a pattern of m characters, and point at the characters you compared more than once.

Five minutes, with a pencil. You’re done when you have a count for this text, a formula for the general case, and one character you can show was read at least twice.

3.2.1 Sliding a window

Count it on that text. At position 0, abab agrees and c does not agree, which makes five comparisons. Slide one place, and b against a fails at once, which is one more comparison. Slide again, and four agree before the fifth fails, which makes five more. The pattern alternates between failing at once and failing at the last moment, and the windows that fail late cost the full five. By the end you’ve made 24 comparisons against a text of twelve characters. Most of those characters were looked at several times.

In the worst case every window is compared all the way to its last character, so the scan costs about n \times m comparisons. A pattern of twenty characters against the ten books comes to over a hundred million comparisons. Yet each window shares all but one character with the window before it, and the scan throws all of that away and starts again.

NoteTry first (no AI)

You have a five-letter pattern and a text of millions of letters, and comparing letter by letter at every position is too slow. Design something that dismisses almost every position with a single comparison, and still never misses a match or reports a false one. Go in two steps.

First, pretend each letter is a digit, so a five-letter window is a five-digit number. The window 17676 slides one place to 76764. Get 76764 from 17676 in a few arithmetic steps that use only the old number, the digit that leaves and the digit that enters. Windows of twenty letters make numbers too big for a computer to add or multiply in one step. What small number could you keep instead?

Then write down what must always be true of that small number, and what breaks without each one.

Ten minutes. You’re done when you have three or four invariants, and for each one, what goes wrong without it.

Look at your list. Did one of your invariants say what happens when two different windows get the same small number?

The design 3.1

Goal: find every place a pattern occurs in a text.

Promise: every occurrence, overlapping ones too, and nothing else.

Idea: fingerprint the windows: compare small numbers that stand for them, not the windows themselves.

Invariants:

  1. Equal windows get equal numbers.
  2. The number kept is always the current window’s number, however far the window has slid.
  3. Equal numbers only make a window a candidate: every candidate is checked letter by letter before it is reported.

Cost: one pass over the text, each slide updating the number from the previous window’s in a few operations, plus a letter-by-letter check of the whole pattern at every candidate, real matches included.

Assumes: a large prime modulus, picked at random, independently of the text. Otherwise many windows become false candidates. It is slower, never wrong.

3.2.2 A number for each window

Go back to the puzzle you tried. If every character were a digit, a window of five characters would simply be a five-digit number. Comparing a window with the pattern would then mean comparing two numbers, one step instead of five. Better still, sliding the window would be arithmetic. The window 17676 becomes 76764 by removing the leading 1 (subtract 1 \times 10^4), shifting what’s left one place (multiply by 10), and adding the new last digit, 4. The slide takes three operations, however long the window is.

But a window of twenty digits is a twenty-digit number. A computer adds or multiplies two numbers in one step only if they fit in a register. A register holds 64 bits, enough for any number of up to 19 digits, and this one has twenty digits.

So keep only the remainder after dividing by some fixed number, the modulus. The remainder is small whatever the window’s length. The three-step slide still works on remainders, because taking the remainder after every step gives the same result as taking it once at the end. That remainder is the window’s fingerprint⁠⬢.

Here it is with real numbers, on a made-up text that starts with that same window, the nineteen digits 1767640259219659478. The pattern to find is 40259, and every remainder is taken after dividing by 13, the modulus. These numbers are small enough to follow by hand. The real search, further down, uses every byte value as a digit and a modulus far larger, chosen at random. Write x \bmod 13 for the remainder of x divided by 13. The first window has fingerprint 17676 \bmod 13 = 9, and a leading digit weighs 10^4 \bmod 13 = 3. So one slide is:

One slide. The dashed digit leaves, the heavy one enters, and the new fingerprint comes from the old one in three operations.
Figure 3.1: One slide. The dashed digit leaves, the heavy one enters, and the new fingerprint comes from the old one in three operations.

That is (9 - 1 \cdot 3) \cdot 10 + 4 = 64, and 64 \bmod 13 = 12. From scratch, 76764 \bmod 13 = 12 too. That has to happen every time. The slide never drifts away from the true fingerprint, however many times you repeat it (invariant 2).

Now roll it all the way across. The pattern’s own fingerprint is 40259 \bmod 13 = 11, so a window needs a closer look only when its fingerprint is also 11.

Every window’s fingerprint. Two of them equal the pattern’s 11. Only one of those is the pattern.
Figure 3.2: Every window’s fingerprint. Two of them equal the pattern’s 11. Only one of those is the pattern.

Fifteen windows give fifteen fingerprints, and two of them are elevens. The window at position 5 is 40259, the pattern itself. The window at position 13 is 65947, which is nothing like it, and still has fingerprint 11.

3.2.3 When two numbers agree by accident

Look again at that second eleven. Thirteen remainders are possible, so plenty of different windows must share each one. A fingerprint match only says maybe. The fingerprint is a fast filter that tells you where it makes sense to check. So every time two fingerprints agree, the search goes back and compares the actual characters, and only reports a position when they really match (invariant 3). At position 13 they don’t match, and that window is thrown out as a false alarm, or spurious hit.

That one comparison is what makes the method exact. A false alarm costs a wasted check, never a wrong answer, whatever modulus you pick. The modulus decides only how often the check is wasted. With 13, the check is often wasted, which breaks the design’s assumption. A large modulus picked at random⁠⬢ restores it (the box below).

Roll it yourself below. Step through the windows one at a time. Then, before you change the modulus, guess whether 7 will give more false alarms on this text than 13, or fewer, and what 101 will do. Change it, and watch how often the fingerprints agree by accident.

Figure 3.3: Interactive rolling fingerprint: slide the window, change the modulus.

This is the Rabin–Karp search [1]. Here is the search’s main loop.

Listing 3.1: Rabin–Karp search, Python.
def search(text, pattern, *, base, mod): ... result = [] for i in range(n - m + 1): if hp == ht and text[i:i + m] == pattern: result.append(i) if i < n - m: ht = ((ht - text[i] * high) * base + text[i + m]) % mod return result
Fingerprint the pattern and the first window.
Every window, left to right: check bytes only when the numbers agree, then slide.one slide: the leading 1 leaves, a 4 enters, and the fingerprint 9 becomes 121767697676412

In that code, text and pattern are bytes, so text[i] is already a number from 0 to 255, and a base of 256 makes every byte one digit. The slide is the 64 mod 13 step from above, with high standing in for the weight of the leaving digit. The companion library has the whole function in rabin_karp.py, with the set-up and the two edge cases (an empty pattern is everywhere, a too-long one is nowhere). There base and mod are passed by name. Run it on the hand trace, with each digit’s value as one byte, base 10 and modulus 13, and it reports the real match at position 5 and drops the false alarm at 13:

Listing 3.2: The hand trace, run against the library, Python.
from algodesign.strings.rabin_karp import search

text = bytes([1, 7, 6, 7, 6, 4, 0, 2, 5, 9, 2, 1, 9, 6, 5, 9, 4, 7, 8])
pattern = bytes([4, 0, 2, 5, 9])
print(search(text, pattern, base=10, mod=13))   # [5]

With a large prime modulus picked at random, the whole search is expected to take about n + m steps, plus a full comparison for each real occurrence. The box below says why.

With a small fixed modulus like 13, false alarms are common, which is why the design assumes a large random prime. A fixed modulus has a worse problem. Anyone who knows it can write a text in which many windows have the pattern’s fingerprint. Then each of those windows triggers a full comparison, and the search is back to about n \times m. It still gives the right answer. It just stops being fast.

The defense is to choose the modulus at random each time, from all the primes below a threshold, so nobody can aim at it. Motwani and Raghavan work out how big the threshold must be [2, Sec. 7.6]. For a text of N bits and a pattern of M bits, a prime drawn below about N^2 M \log_2(N^2 M) produces a false alarm anywhere in the text with probability only about 1/N. This holds on any text, because the randomness is in the prime. That is the random prime the design assumes.

A method that is always right and leaves only its running time to chance is called Las Vegas. Skip the letter-by-letter check of each candidate, and this one becomes Monte Carlo, always fast and now and then wrong.

In practice, the library caps the threshold at 2^{61}, so that every product fits in 128-bit arithmetic. For a text the size of the ten books, and any pattern longer than one byte, that cap is lower than the formula requires. That makes the bound weaker than 1/N.

The guarantee has a price on ordinary text. On the ten books, a plain scan that compares each window letter by letter is about 1.6 times faster than Rabin–Karp.2 In English the first letter of a window almost always differs from the pattern’s first letter, so the scan usually stops after one comparison, while the fingerprint does its arithmetic at every step. The scan’s cost climbs only where every window almost matches. For a long run of as searched for 255 as and a b, the two take about the same time. The fingerprint wins outright when many patterns of one length are searched at once, with all their fingerprints in one set.

Searching with borders: Knuth–Morris–Pratt and Aho–Corasick

Fingerprints are one way to stop re-reading the text. There is another, which uses no randomness at all. It lets the pattern’s own shape tell you how far to slide.

Say the pattern is ababc, and the text has just matched abab before failing. You don’t have to start again from scratch, because you already know what the text just said. It ended in ab, and ab is also how the pattern begins. So slide the pattern until its opening ab sits on top of that ab, and carry on comparing from there. A border is a shorter piece that appears at both the start and the end of what you have matched. Work out the longest border of every beginning of the pattern once, before the search, and keep them in a table, the prefix function. Then the search never has to step back in the text. On every text it is guaranteed to take a number of steps proportional to n + m, and it has no false alarms to check. Searching this way is the Knuth–Morris–Pratt method [3].

Dice make Rabin–Karp simple and fast on average, for every text, as long as nobody can guess the prime. The pattern’s structure makes the guarantee hold every single time, though Knuth–Morris–Pratt is trickier.

Borders also work for thousands of patterns at once. Store the patterns in a tree that keeps their shared beginnings once, the trie of the next section. Give each node a link to where to carry on when the next letter fails. The link goes to the longest piece that ends what has matched, is shorter than it, and begins one of the patterns. That is a border, worked out across all the patterns. Then one pass over the text finds every pattern in it. That is the Aho–Corasick method [4], and building it lies beyond this chapter.

Many standard libraries search without dice, with a relative of Knuth–Morris–Pratt called Two-Way [5], among them glibc’s memmem for patterns over 256 bytes and Rust’s str::find. For patterns of 3 to 256 bytes, memmem uses a method from the Boyer–Moore family [6], [7].

3.2.4 Too much to read

Rolling fingerprints make one search cheap, with one pass over the text and a few arithmetic steps per window. But one pass is still a pass over everything, every time anyone asks.

GitHub worked through exactly this arithmetic when it rebuilt its code search [8]. The code it wanted searchable came to about 115 TB. Take one of the fastest scanning tools there is and spread the work perfectly over 2048 processor cores. Scanning that much would still take about 96 seconds per query, with every core busy, so the whole system could answer about one query every hundred seconds. Their conclusion, “we need to build an index,” is the one that this chapter reaches next.

An index is the other road from the start of the chapter. It reads the text once, before anyone asks, and keeps something that lets each question touch only a small part of it. What to keep depends on what Leo remembers, and the simplest case is a quote’s start.

3.3 I remember how it starts

Trie and Patricia tree

A week later, another dinner. Somebody is describing their sister’s wedding, down to the speeches and the mother-in-law. Leo knows there is a perfect opening line for it. The line is the famous first sentence of Pride and Prejudice, a novel about marriage and money. He has the start of it, “It is a truth…”, and then nothing.

This time the fragment he holds is a beginning, and you do something with beginnings many times a day without thinking about it. Type the first letters of a name into your phone’s contacts, or the first word into a search box, and the list below narrows with every letter you add. Nobody is reading every entry from the start each time you press a key. The list is ready for exactly this question, what starts like this?, before you ask it.

NoteTry first (no AI)

You want to store a few thousand quote openings so that typing the first words lists every opening that begins that way, with the list narrowing as you type. A sorted list and binary search, from the search chapter, would find the matching block. But look at the openings themselves: “It is a truth”, “It is a far, far better thing”, “It was the best of times”. What do they share, and could your structure store the shared part only once? Design it, and say what one keystroke costs.

Ten minutes. Draw your structure for the five words she, shells, sea, shore, seashore. You’re done when you can count how many pieces your drawing uses, and say how much work typing one more letter takes.

3.3.1 A tree of first letters

Look at what your drawing did with she and shells. Did it store she twice, or once, with lls hanging off its end? The three openings do the same. All three share “It”, and two of them share “It is a”.

The design 3.2

Goal: look up words in a large dictionary.

Promise: a map from words to values. Get gives a word’s stored value, or nothing. Insert stores or replaces one word’s value; remove deletes it. Other words stay unchanged. Every word that starts with a given prefix can be listed.

Idea: tie common prefixes, the beginnings words share, together, so they are checked once for all the words that share them.

Invariants:

  1. A word is a path of letters from one common starting point to a mark that says it ends there.
  2. Paths leaving the same point carry different letters.
  3. Every branch leads to a stored word.

Cost: each operation grows with its word, not with the dictionary; memory, up to a node per letter stored.

Start with one empty node, a point that branches will hang from, called the root. To store a word, walk down from the root one letter at a time. If there is already a branch for the next letter, follow it, and if there isn’t, make one. When the letters run out, mark the node you stand on: a word ends here. That’s the whole structure, and it is called a trie, from retrieval [9].

Here are the five words, stored that way.

The trie of she, shells, sea, shore and seashore. A double ring marks a node where a word ends. No node stores a letter: the letters are on the branches, and a word is the path from the root to its ring.
Figure 3.4: The trie of she, shells, sea, shore and seashore. A double ring marks a node where a word ends. No node stores a letter: the letters are on the branches, and a word is the path from the root to its ring.

No node in the picture holds a word, or even a letter. The letters live on the branches, and a word is nothing but the path you walk to reach its ring. she and shells share their first three branches, and shells keeps going. Seventeen nodes are enough for all five words, root included.

The order in which the words arrive makes no difference. The same words always build the same tree. The search chapter’s trees could not keep that, and needed rules to stay balanced. A trie never needs them, because its depth is the length of its longest word.

The design’s first invariant is all a search needs. Follow the letters, and the mark tells you whether the word is stored. The second is why there is only ever one way to follow them.

Here is the insert in code. Each node keeps its children in a small dictionary, filed by the next byte, and a flag that says whether a word ends there. A node where a word ends also keeps whatever is stored with it, its value. _Node() makes an empty node. Every walk starts at self.root.

Listing 3.3: Trie insert, Python.
def insert(self, key, value): node = self.root for byte in key: child = node.children.get(byte) if child is None: child = _Node() node.children[byte] = child node = child node.value = value node.has_value = True
Walk down one byte at a time, from the root.
A missing branch is made on the way.one step per byte down the tree; the missing branch is made, and the last node marks the word
The bytes ran out: this node ends the word.

Finding a word is the same walk without the building. Follow the branches letter by letter, and check the flag where you stop. Count what that costs. Every step uses one letter of the word you are looking for, so a word of m letters takes m steps, however many words are stored. Whether the trie holds a thousand openings or ten million, typing one more letter is one more step down. Binary search over a sorted list cannot say that, because its number of steps grows with the size of the list.

3.3.2 Everything that starts with…

Now Leo’s question. Walk down the letters he remembers, and stop. Every word that starts that way is below the node where you stopped, and nothing else is. So the answer is that one branch, read off from the top. The walk down is the walk that finds a word, so the code below (Listing 3.4) is only the reading off. It starts at the node where the walk stopped, with path holding the letters that led there, and puts every word it meets into the list out.

Listing 3.4: Trie: collecting every word below a node, Python.
def _collect(self, node, path, out): if node.has_value: out.append(path) for byte in sorted(node.children): child = node.children[byte] step = path + bytes([byte]) self._collect(child, step, out)
Its own word first, then each branch in byte order: the words come out sorted.a node first, then its branches in byte order: the words come out sorted1234

Try it on the picture. For sh, walk s, then h. Below that node sit she, shells and shore, and nothing else, because every other word went another way at the first branch. For se, the answer is sea and seashore. For x, the walk fails at the first letter, and the answer is empty immediately, without looking at a single stored word.

The answers come out in byte order for free, which for lowercase words like these is alphabetical order. _collect visits a node before the nodes below it and takes the branches in order of their letters. That is exactly byte order, in which a word comes before every longer word it begins. A hash table finds one word fast, but it can answer starts with only by looking at every word, because it gave up the order to get its speed. The whole of keys_with_prefix, walk included, is in the companion library, in trie.py.

A careless remove breaks invariant 3. It clears a word’s mark and leaves the branch that spelled the word, now leading to no word at all. The library’s check_valid() returns None when every invariant holds, and otherwise names the first one that fails, numbered as in the box:

Listing 3.5: Breaking a trie by hand: one dead branch, Python.
from algodesign.strings import Trie

trie = Trie()
for word in [b"tea", b"ten", b"to"]:
    trie.insert(word, len(word))
print(trie.check_valid())      # None
node = trie.root
for byte in b"to":
    node = node.children[byte]
node.has_value = False         # clear the mark, keep the branch
print(trie.check_valid())      # invariant 3 (no_dead_branches)

3.3.3 When the tree is bigger than the words

The five words have 25 letters between them, and the trie spends 17 nodes on them. That sounds reasonable until you ask what a node costs.

The fast version of this structure, in the library’s Rust, gives every node 256 slots, one for every possible next byte. Following a branch is then a single lookup with no search at all. Each slot is a pointer of 8 bytes, so a node is about 2 kilobytes. Seventeen nodes come to about 35 kilobytes, to store 25 bytes of words. The Python above saves the empty slots by using a dictionary, but every entry in a dictionary has its own cost, and the shape of the waste is the same.

That shape is the long chains. Look at seashore. After sea come four nodes in a row that each have exactly one child and hold no word. They are there only to spell out s, h, o, r before the e where seashore finally ends. There is one node per letter, and nothing to choose at any of them. The same happens to shells after she, and to shore after sh. A trie is small when its words share a lot. When they share little, it is mostly chains, and every link of a chain is a node paid for in full.

The design 3.3

Goal: the trie’s job, when the words are long.

Promise: the trie’s.

Idea: squeeze every chain into a single branch.

Invariants:

  1. A word is the path from the root, now several letters to a branch, to a mark that says it ends there.
  2. The branches leaving a node start with different letters.
  3. Every node below the root where no word ends has two children or more.
  4. Every branch carries at least one letter.

Cost: at most two nodes per word, however long the words are, once one word is stored.

The two nodes per word come from invariant 3. The promise needs the other three: without invariant 4, a search would get stuck at a branch with no letters on it.

3.3.4 Squeezing the chains

So squeeze them. Wherever a node has exactly one child and no word ends at it, merge it with that child, and write the merged letters on the branch, so that one branch labeled shore replaces five branches labeled s, h, o, r, e. The result is called a Patricia tree [10]. A compressed trie like this is also called a radix tree, where radix is the number of different digits with which a key is written: 2 for bits, 256 for bytes, 26 for lowercase letters.

The same five words after squeezing. Eight nodes instead of seventeen. Every node below the root now either ends a word or branches.
Figure 3.5: The same five words after squeezing. Eight nodes instead of seventeen. Every node below the root now either ends a word or branches.

Squeezing establishes the design’s third invariant, that every node below the root ends a word or branches⁠⬢. The same words still build the same tree, in whatever order they arrive. That one shape is the set’s canonical form.

Keeping it pays off. Such a tree has at most two nodes for every word stored, however long the words are. The root is the one node that the third invariant leaves out. It has nothing above it to merge into, so it may keep a single child, as it does here, where every word starts with s.

Say the tree stores k \ge 1 words. Its nodes come in three kinds. There is the root. There are the nodes below the root where a word ends, at most k of them, one for each word. And every other node below the root ends no word, so by the third invariant it branches, with two children or more.

Count that last kind. Every leaf ends a word, so there are at most k leaves. And in any tree, the nodes with two or more children are fewer than the leaves. A single path down ends in one leaf, and every split adds at least one more leaf. So at most k - 1 nodes branch without ending a word.

All together that makes at most 1 + k + (k - 1) = 2k nodes, however long the words are.

Invariants like these only help if they stay true after every change, which is where the work is. Inserting walks down whole branch labels while they agree with the new word, and ends in one of three ways:

  • the word runs out exactly at a node: mark it;
  • no branch starts with the next letter: add one new branch that carries the whole rest of the word;
  • the word agrees with only the start of a branch’s label: split the branch there, so the branches leaving a node still start with different letters (invariant 2). The new node ends the word if the word ran out there, and otherwise holds the rest of the word as a second branch.

To see the third, insert she, then shells, then sea:

Before: she and shells.
Figure 3.6: Before: she and shells.
After inserting sea. The branch she agreed with sea for one letter, so it splits after s. The new node and the new branch are drawn heavy.
Figure 3.7: After inserting sea. The branch she agreed with sea for one letter, so it splits after s. The new node and the new branch are drawn heavy.

sea agrees with the branch she for one letter, s, and then the two differ. So the branch is cut after s, and a new node goes there. Below it, the old branch keeps the rest of its label, he, and a new branch carries sea’s own remainder, ea. The new node branches, so every node still ends a word or branches (invariant 3).

In the code, each node keeps the label of the branch that leads into it. _Node(label) makes an empty node with that label. _leaf(rest, value) makes a node that ends a word, with rest as its label. _common_prefix_len(label, rest) counts the letters on which the two agree from the start. The code keeps each branch in a dictionary, under its first letter.

Listing 3.6: Patricia tree insert, Python.
def insert(self, key, value): node, rest = self.root, key while True: if not rest: node.value = value node.has_value = True return child = node.children.get(rest[0]) if child is None: leaf = _leaf(rest, value) node.children[rest[0]] = leaf return label = child.label common = _common_prefix_len(label, rest) if common == len(label): node, rest = child, rest[common:] continue split = _Node(label[:common]) child.label = label[common:] split.children[child.label[0]] = child if common == len(rest): split.value = value split.has_value = True else: tail = _leaf(rest[common:], value) split.children[tail.label[0]] = tail node.children[rest[0]] = split return
Walk down with what is left of the word.
Nothing left of it: this node ends the word.
No such branch: a new branch carries the rest.no branch for the next byte: one new branch carries the whole rest of the wordrest
The branch's label agrees all the way: step down and keep going.
Only part agrees: a new node cuts the branch there and takes its place.
The new node ends the word, or grows the rest as a second branch.only part of a branch agrees: it is cut there, and the new node at the cut holds the old remainder and the new tail

Taking a word out runs the same rules the other way. Clear the word’s mark, then remove any node left with no word and no children, walking back up. In the squeezed tree, the removal can leave a node that has a single child but does not end a word. That node is merged with its child at once, so every node again ends a word or branches (invariant 3).

Try both structures below. Insert words of your own and watch where the branches split, switch the squeezing on and off and compare the node counts, and remove a word to see a chain merge back together.

Figure 3.8: Interactive trie and Patricia tree.

3.3.5 What a beginning can’t do

Leo, with his trie, finds “It is a truth universally acknowledged” in a few keystrokes. But a trie answers only the question for which it was built. It needs the start. Give it “universally acknowledged”, the part he actually remembers, and it has nothing to offer. Every path in it begins at the first letter of a stored opening, and that fragment is no opening.

Asked a slightly different question, the same structure is also one of the ways a router decides where to send each packet it receives. The router appendix at the end of the chapter shows how.

3.4 It was somewhere in the middle

Suffix array and LCP

Most nights, Leo remembers only “…universally acknowledged…”, two words and a rhythm from the middle. He has no idea what came before them.

The index at the back of a book has the same blind spot from another side. It lists the words that an editor expected someone to look up, and nobody expects anyone to look up universally. What Leo needs is an index that can be entered from anywhere: from any word, from the middle of a word, from any position in the text at all.

NoteTry first (no AI)

You want an index over a text of n characters that finds any fragment wherever it sits, not only at the start of a line. Take the six-letter text banana. Every fragment of it starts at some position. Before building anything, write down what must always be true of your index. Then say what one entry of it would be, how many entries there are, and how many bytes the whole index takes for a text of n characters.

Ten minutes, with the word banana. You’re done when three things hold. Your invariants must guarantee that no occurrence is missed and that finding one leads to the rest. You have written your index for banana and found ana in it by hand. And you have put a size in bytes on it for a text of n characters.

3.4.1 Every fragment starts a tail

Look at your index for banana. If each entry held a fragment’s letters, how many entries did you need, and how long were they? Now count something smaller. How many places can a fragment start?

A fragment of the text starts somewhere, and from that position the text runs on to its end. That tail, from some position to the end, is called a suffix. ana occurs at position 1 of banana, which is exactly the same as saying that the suffix starting at position 1, anana, begins with ana.

So finding a fragment anywhere in the text is the same as finding a suffix that begins with it. Write the text with a $ at the end. This marker, called a sentinel, means the text stops here and sorts before every letter. The sentinel stops one suffix from being the start of another.

The last section’s trie answers exactly what begins like this?, so put every suffix into one. It works. Walk the fragment’s letters from the root, and the suffixes below that point are its occurrences. With the sentinel, every suffix ends at a leaf of its own, so no node needs the trie’s end-of-word mark. But it does not fit. Two suffixes of ordinary prose share only a few letters before they part, so nearly every suffix lays down its own chain to the end of the text, about n^2/2 nodes, well over 700 billion for Moby-Dick. Squeezing the chains, as the Patricia tree did, gives the suffix tree [11], [12], [13]. On ordinary prose it has about 1.4 nodes per letter (Project 9 measures it).

But a node cannot keep the letters of its branch, since the copies would add up to about n^2/2 letters again. It keeps two 4-byte numbers that point into the text, where its letters start and how many there are, and two 8-byte memory addresses, one for its first child and one for its next sibling. That is 24 bytes a node. At 1.4 nodes per letter, the index takes about 34 bytes for every byte of book. The book must also be kept beside it.

The suffix tree of banana$, drawn as usual (top) and as stored (middle). Eleven records of 24 bytes keep each label as a start and a length in the text. The root has no label. Below, the suffix array of the same text, seven 4-byte numbers pointing into it.
Figure 3.9: The suffix tree of banana$, drawn as usual (top) and as stored (middle). Eleven records of 24 bytes keep each label as a start and a length in the text. The root has no label. Below, the suffix array of the same text, seven 4-byte numbers pointing into it.

For Leo’s flood, 34 times the size of the book is far too much. All that is needed is where each suffix starts.

3.4.2 Keep where it starts, not what it says

A trie keeps its branches in letter order, so reading the suffixes off it from left to right gives them in alphabetical order. In that order, the suffixes that begin with the same fragment sit side by side, so binary search over a sorted list finds them all, with no tree at all. So keep the order and drop the costly tree.

The design 3.4

Goal: find any fragment, wherever it starts, in one fixed text asked many questions.

Promise: every place the fragment starts, and nothing else.

Idea: every occurrence is the beginning of a suffix.

Invariants:

  1. Every position of the text appears once, so no occurrence can be missed.
  2. The suffixes are kept in sorted order, so the occurrences of any fragment lie side by side, and finding one stretch finds them all.

Cost: one stored position per letter beside the text, not the suffix tree’s 34 bytes; a search grows with the fragment times \log n, plus one step per place found.

Assumes: the text stays as it was when the array was built. Otherwise a search returns places where the fragment no longer is, and misses places where it now is.

Sort the suffixes (invariant 2), and for each one store just one number, the position where it starts, each position once (invariant 1). The letters are already in the text, so there is no need to copy them.

The seven suffixes of banana$, sorted. The suffix array is the boxed column SA, the start position of the suffix in each row, and nothing else. The suffixes are drawn for your eyes: the array never stores them. Later sections add columns to this same table, with the same rows in the same places.
Figure 3.10: The seven suffixes of banana$, sorted. The suffix array is the boxed column SA, the start position of the suffix in each row, and nothing else. The suffixes are drawn for your eyes: the array never stores them. Later sections add columns to this same table, with the same rows in the same places.

banana$ sorted this way is the array 6 5 3 1 0 4 2, seven numbers for seven characters. This is the suffix array [14]. In Python, the suffix array is sorted(range(n), key=lambda i: text[i:]), the start positions, sorted by the suffix that starts at each. Any faster way to build it must give exactly this.

Each sorted suffix sits in its own row of the table, numbered from 0 at the top, so row 0 is $ and row 4 is the whole text. A suffix’s row is its place in this sorted table, and its position is where it starts in the text. Whenever a search needs the letters of the suffix in some row, it looks them up in the text, starting at the number stored there.

3.4.3 Searching the sorted suffixes

The array is sorted, so the search chapter’s binary search applies, with one twist. It compares the pattern against just the first few letters of a suffix, as many as the pattern has.

Find ana. The rows whose suffixes begin with ana form one stretch, so the search looks for its top and its bottom. For the top, it halves toward the first row whose first three letters do not come before ana in sorted order. It looks at row 3 (ana, not before, so the top is at row 3 or earlier), then row 1 (a$, before ana, so the top is after row 1), then row 2 (ana, not before). The top is row 2. The bottom is found the same way, as the first row whose first three letters come after ana: row 3 (ana, not after), row 5 (na$, after), row 4 (ban, after). The bottom is row 4, just past the stretch, so the stretch runs from row 2 up to, but not including, row 4. That is rows 2 and 3, holding positions 3 and 1. Six looks at the array find the stretch of every occurrence.

Table 3.1: The six looks that find ana.
Looking for Rows looked at Answer
the top: first row not before ana 3, 1, 2 row 2
the bottom: first row after ana 3, 5, 4 row 4

In code it is shorter than the explanation, because Python’s bisect does the halving and key cuts each suffix down to the pattern’s length.

Listing 3.7: Suffix array search, Python.
def search(text, sa, pattern): if not pattern: return [len(text), *sa] m = len(pattern) first_m = lambda p: text[p:p + m] lo = bisect_left(sa, pattern, key=first_m) hi = bisect_right(sa, pattern, key=first_m) return sa[lo:hi]
The empty pattern is at every position, end included.
Binary search bounds the matching rows.binary search finds the top and the bottom; every row between them begins with the patterntopbottom

Count what that costs. Each look is a jump to a random place in the text, a fetch in the search chapter’s terms. It compares at most m characters there. Each of the two searches takes about \log_2 n looks. The ten books from the start of the chapter hold 6,793,686 bytes, so each search needs at most 23 looks. The fragment “universally acknowledged” has 24 characters, so its two searches make at most 46 looks of at most 24 comparisons each, about a thousand character comparisons in all. By contrast, the scan of the first section compared the pattern against every one of almost seven million windows.

And Leo’s two words come back with two answers. One is the line he was looking for, the first sentence of Pride and Prejudice. The other is in Great Expectations, where a small-town newspaper praises “our as yet not universally acknowledged townsman TOOBY, the poet of our columns”. Perhaps Dickens had read Austen. Two words can’t tell.

Build an array yourself below, then search it, one look at a time.

Figure 3.11: Interactive suffix array: build one, then search it one look at a time.

3.4.4 Sorting by doubling

Leo never sees this part, but the service sees it whenever it builds the index. Searching was easy because the hard work was done in advance. The suffixes had to be sorted. Hand them to any sort, and each comparison between two suffixes reads letters until they differ. In ordinary prose that is quick. In a text with long repeats it is slow. In a text of a million as, every pair of suffixes agrees until one of them runs out, and the sort spends most of its time re-reading the same letters.

The way out is the same move that the fingerprints made in the first section. Stop comparing letters, and compare small numbers that stand for many letters at once.

Start by giving each position a tag, a number that sorts the suffixes by their first letter alone, with equal letters getting equal tags. In banana$, $ gets 1, every a gets 2, b gets 3, every n gets 4. Unlike a fingerprint, a tag never agrees by accident. Equal tags mean equal letters, so nothing needs checking.

Follow position 1. Its first letter is a, so its tag is 2. In round 1 its pair is (2, 4), its own a and then the n at position 2, so it is tagged by an. In round 2 its pair is (3, 3), an and then the an at position 3, so it is tagged by anan. By then every position has a tag of its own. Reading the positions in order of tag gives 6 5 3 1 0 4 2. That is the suffix array, and no two suffixes were ever compared letter by letter.

Prefix doubling on banana$. Each round tags the suffixes by twice as many letters as the round before, using a pair of numbers from the round before. After round 2 every tag is different, and the order of the tags is the suffix array.
Figure 3.12: Prefix doubling on banana$. Each round tags the suffixes by twice as many letters as the round before, using a pair of numbers from the round before. After round 2 every tag is different, and the order of the tags is the suffix array.

The same step works in every round. Suppose the tags sort the suffixes by their first w letters, and two suffixes share a tag exactly when those letters agree. The first 2w letters of the suffix at position i are its own first w letters, then the first w letters of the suffix at i + w. Both already have tags. So the pair (tag of i, tag of i + w) sorts the suffixes by their first 2w letters, without looking at a single letter. Sort the pairs, hand out new tags, and the prefix that each tag covers has doubled [15, Sec. 32.5]. A suffix that would start past the end of the text gets tag 0, smaller than every other, because a suffix that runs out sorts first.

Each round sorts the pairs in a number of steps proportional to n. The prefix that a tag covers doubles every round, so for a text of n characters the doubling needs about \log_2 n rounds at most. That makes about n \log_2 n steps in all.

It usually stops much sooner. The tags become all different as soon as that prefix is longer than the longest passage that occurs twice in the text. That passage, in the ten books, is 145 bytes long, so the prefix stops at 256 letters, after 8 rounds, not the 23 that \log_2 n allows.

Faster constructions exist. DC3 [16] and SA-IS [17] build the suffix array in a number of steps proportional to n. Libraries built for very large texts use methods of their kind.

The appendix shows why two old tags are enough, and how a round sorts its pairs that fast. The code for a round, with its tests, is in the companion library, in suffix_array.py.

3.4.5 Neighbors that agree

The sorted order holds one more thing for free. Look at any two neighboring rows. They share some opening letters, then part. ana$ and anana$ share ana, three letters. na$ and nana$ share na. Write down, for each row, how many letters its suffix shares with the row above, and you have the LCP array, for longest common prefix. For banana$ it is 0 0 1 3 0 0 2. In the trie of all suffixes, each entry is how far a suffix and the one before it in sorted order walk down together before their paths part.

The same table, with the LCP array added: how many opening letters each row’s suffix shares with the row above.
Figure 3.13: The same table, with the LCP array added: how many opening letters each row’s suffix shares with the row above.

That array answers a new question in one pass, what is the longest passage that occurs twice? A passage that occurs twice starts two suffixes that share it. Suffixes that share a long opening sort close together. So the largest number in the LCP array is the length of the longest repeat, and the row where it sits says where. In banana$, the 3 in row 3 is ana.

In the ten books, the largest entry is 145 bytes, the repeat that stopped the doubling after 8 rounds. The passage it points to is two lines from Alice’s Adventures in Wonderland, the chorus of the Mock Turtle’s song:

Will you, won’t you, will you, won’t you, will you join the dance?
Will you, won’t you, will you, won’t you, won’t you join the dance?

Both lines together appear in two verses.

Computing each entry from scratch means comparing two suffixes letter by letter, and in a text full of repeats that is slow again. But the whole array can be computed in one pass, in time proportional to n, by walking the suffixes in text order and carrying the count of matching letters from one suffix to the next. This is Kasai’s method [15, Sec. 32.5], [18]. The rolling fingerprint did the same in the first section, keeping what the last step learned instead of reading it again.

The appendix gives Kasai’s method step by step, and why the count drops by at most one. Its code, with its tests, is in the companion library, in lcp.py.

3.4.6 How big is the index?

Add it up. The text is n bytes. The suffix array holds one number per character, and a 4-byte number per entry is enough for any text up to about 4.29 billion characters. Together that is 5n bytes, five times the book. For the ten books, that comes to about 34 MB to search 6.8 MB of text. Past that each entry needs more than 4 bytes, and with 8-byte numbers the index grows to 9n. Keep the LCP array as well, one more number per character, and the total is 9n with 4-byte numbers or 17n with 8-byte ones. Even then it is far below the suffix tree’s 34 bytes for every byte of book, with the book kept beside the tree. And it gives up none of the tree’s answers. With the LCP array and a little more bookkeeping, any algorithm written for the suffix tree can run on the sorted order instead, just as fast [19].

A suffix array of this kind was built in 2024 over five trillion tokens, the pieces of text from which language models learn. The array counted in milliseconds how often any phrase appears [20].

For Leo’s flood, five times the text, or more, is a lot of disks to answer a question at dinner.

3.5 What is this all about?

Text indexes: count, locate, extract

Step back from fingerprints, trees and sorted suffixes for a moment. Under all of them, Leo has been asking the same three questions, and every structure so far answers them differently:

  • Is that really the line, and how often does it come up? Whether the fragment occurs in the text, and how many times. (count)
  • Where is it? The positions where it occurs, which say which book and which page. (locate)
  • Give me the words. The text around a position, so he can say the whole line. (extract)

A structure that answers those three questions is a text index. The questions are not only about quotes. GitHub’s code search, from the first section, asks where a line of code occurs across millions of repositories. A DNA sequencer produces short pieces of DNA, called reads. Each one has to be placed on a reference genome three billion letters long. And when a language model writes a paragraph, someone eventually asks whether that paragraph was copied from what it was trained on: count, locate, and show me. The same three questions come up every time, with the same tension between preparing the text once and answering fast.

3.5.1 What is a character, actually?

Under the three questions sits a fourth, older one. What counts as the fragment? Leo’s drizzly November worked. Try another line from the same chapter of Moby-Dick, “growing grim about the mouth”, and search the ten books for it. Nothing. The quote is there. But the file starts a new line after about, so the byte between about and the is a newline, not a space. The search compares bytes.

It gets worse with apostrophes. Search the same ten books for don't, typed with the apostrophe on your keyboard, and there are zero hits. Search for don’t with the curly apostrophe with which the books were typeset, and there are 1,085. The two look nearly the same on screen but are different bytes in the file. The search is not wrong. It found exactly what it was asked for, and what it was asked for was not what you meant.

Everything in this chapter treats text as a row of bytes, and compares bytes. That is a choice, and it has drawbacks:

  • One letter can be written in more than one way. é is stored either as one character or as e followed by a combining accent. The two forms compare unequal even though they look identical.
  • “Sorted” depends on the language. Alphabetical order is a convention, and different languages have different conventions, so the order of words is not a property of the bytes alone. The suffix array you just built sorted bytes, and nothing else.

Fixing these is a separate job, done before the search ever sees the text. That job rewrites every character into one agreed form and decides which differences count. The code in this chapter does none of that, on purpose. It answers exactly what it is asked, and deciding what to ask stays with you.

3.5.2 What has been bought so far

Here is the ledger, for a text of n characters and a fragment of m characters:

Table 3.2: What each structure so far costs, for a text of n characters and a fragment of m characters.
structure prepare answer one fragment size which fragments
Scan, with rolling fingerprints nothing about n + m steps, expected, plus m per occurrence the text any
Trie, Patricia tree build once m steps, plus the answers a node per letter, or per branch, of the stored openings beginnings only
Suffix array sort once about 2m \log_2 n comparisons 5n: the text plus the array any

The pattern across the table is the same one that the search chapter found. What a structure wins in one column, it pays for in another. The suffix array answers any fragment fast, and pays for it in space.

In every one of the three rows, the text is kept, whole and untouched, and the answers depend on it. The scan compares against it, the trie was built from copies of it, and the suffix array reads it on every comparison. extract has been free all along, because the text was sitting right there.

3.6 Useful mess?

Burrows–Wheeler transform

What if the text were rearranged, kept at exactly its own size, into an order that does the index’s job, and nothing were lost?

NoteTry first (no AI)

Here is a way to do it by hand. Take the text banana$ and write out all seven of its rotations. The first is the text itself, the next is the text with its first character moved to the end, and so on (banana$, anana$b, nana$ba, …). Sort the seven rows, $ before every letter. Now keep only the last character of each sorted row, top to bottom. You get annb$aa.

Suppose all you were given was annb$aa, and the rule that made it. Could you get banana$ back? Start with the first character of every sorted row. What do you know about it, if you know the last ones?

Fifteen minutes. You’re done when you have recovered the first two characters of the text, or can say exactly what stops you.

The column you just made is called the Burrows–Wheeler transform⁠⬢ of the text, BWT for short [21]. Here is the design behind it, to check your answer against.

The design 3.5

Goal: drop the suffix array, but keep what it said: how the suffixes sort.

Promise: from these letters alone, the text comes back exactly. The sorted suffixes come with it.

Idea: store a permutation of the text’s letters, chosen so a fixed rule can rebuild everything from it.

Invariants:

  1. It is a permutation of the text: the same letters, each as often, n in all.
  2. It follows the sorted suffixes: for each suffix, in their sorted order, the letter just before it.

Cost: n letters, instead of the text plus 4n.

Assumes: the text ends with one $, found nowhere else. Otherwise it is rejected with an error.

Before seeing how to undo it, look at what it is.

3.6.1 Sort the rotations

Start from the suffix array’s table, before it is sorted, and step it into the transform.

Figure 3.14: From the suffixes to the transform: the suffixes run on into rotations, one row is rebuilt from the first and last columns alone, the rows are sorted and the row is rebuilt again, and then it is rebuilt once more from the last column alone.
The same table again. Each suffix now goes on past the $, around to the start of the text (the gray letters), so every row is a rotation, and the rows are the seven rotations of banana$, sorted. The first column, F, is the text’s letters in sorted order. The last column, L, is the transform. Each row’s last letter comes, in the text, just before its first letter. The small number on each letter of L says how many copies of that letter sit above it in L, counting from 0. The next section uses them.
Figure 3.15: The same table again. Each suffix now goes on past the $, around to the start of the text (the gray letters), so every row is a rotation, and the rows are the seven rotations of banana$, sorted. The first column, F, is the text’s letters in sorted order. The last column, L, is the transform. Each row’s last letter comes, in the text, just before its first letter. The small number on each letter of L says how many copies of that letter sit above it in L, counting from 0. The next section uses them.

Leo’s lines come back in pieces and out of order, and he still knows they are all in there. The last column keeps every letter, only in another order.

Two columns matter. The first, F, is just the text’s letters sorted, $aaabnn. The last, L, is the transform, annb$aa. And because every row is a rotation, a row’s last letter comes just before its first letter in the text, wrapping around from the end to the start. Row 2 is ana$ban, and its last letter, n, comes just before the a at the start of ana$ in banana$.

The rows of the sorted rotations are almost the sorted suffixes of the suffix array. Cut each rotation at the $ and you get a suffix, and because $ is unique and smaller than every letter, the cut never changes the order. So row i is the suffix that the suffix array stores in row i, and the transform needs no rotations at all. It is L[i] = text[sa[i] - 1], the letter just before each sorted suffix (at position 0, Python’s text[-1] wraps around to the $). That is how the library computes it, from the suffix array in one pass.

3.6.2 Reading it backwards

The question from the box is how to get the text back from annb$aa alone.

The first step is the one you probably found. Sorting annb$aa gives $aaabnn, which is F, because the first column is the text’s letters in sorted order and the transform holds exactly the text’s letters (invariant 1). Now every row gives a pair, last letter then first letter, and each pair is two consecutive characters of the text, reading around from its end to its start: a$, na, na, ba, $b, an, an. Sort those pairs and you have the first two columns of the matrix. Put the last column in front of them again and sort, and you have the first three columns. Repeat, and after n rounds the whole matrix is back, and the text is the row that ends in $. The transform alone rebuilt it (the design’s promise).

That works, and it costs n sorts of n rows. The faster way rests on one fact about equal letters.

There are three as in each column. Number the copies of each letter down the column, starting from 0, and write the number small beside the letter. The number is how many copies of the same letter sit above it. In L, a0 is in row 0, a1 is in row 5 and a2 is in row 6. In F, a0, a1 and a2 are in rows 1, 2 and 3.

Take row 6, nana$b + a. Rotate it once, moving its last a to the front, and you get a + nana$b, which is row 3. The a that ends row 6 and the a that starts row 3 are the same character of the text, and both are a2. The table does the same for all three as.

Table 3.3: The three as of banana$, in L and in F.
copy its row, with the a last in L its row, with the a first in F
a0 row 0: $banan + a row 1: a + $banan
a1 row 5: na$ban + a row 2: a + na$ban
a2 row 6: nana$b + a row 3: a + nana$b

Take the a off, and both columns hold the same three strings, $banan, na$ban and nana$b, in the same sorted order. So the numbers match: a2 in L is the same character of the text as a2 in F, and so on for every letter and every number. Equal letters keep their order from one column to the other.

Here is why that holds for any text. The as in F are in sorted order of what follows them in the text, because that is the rest of their rows. The rows with an a in L are also in sorted order. Each of those rows, read from the start, is exactly what follows its a in the text. Both columns hold the same as, sorted by the same thing, so the as come in the same order.

Reading banana$ back from its transform. Equal letters are numbered from 0 in both columns, and a2 in L is a2 in F, for every letter and number. Each arrow is one jump, and the walk emits the text from the end backwards.
Figure 3.16: Reading banana$ back from its transform. Equal letters are numbered from 0 in both columns, and a2 in L is a2 in F, for every letter and number. Each arrow is one jump, and the walk emits the text from the end backwards.

Standing on one row, with only L, which row starts one letter earlier in the text?

Each arrow in the figure answers it. That jump is called the LF mapping, or LF, for last to first. From the row whose last letter is c_k in L, it jumps to the row whose first letter is c_k in F. Each row’s last letter comes just before its first letter, so the row you land on starts one position earlier. When LF is read off L, the one column kept, it walks the text backwards, one fetch per step.

LF is cheap to compute, and both of its parts can be read off the figure. For each character c, let C[c] be the number of characters in the text smaller than c, which is the row where c’s block starts in F. Let occ(c, i), for occurrences, be the number of cs in L above row i. That count is the search chapter’s rank, how many come before, asked of one letter. For banana$, C is 0 for $, 1 for a, 4 for b and 5 for n. Then

\text{LF}(i) = C[c] + \text{occ}(c, i), \tag{3.1}

where c = L[i]. For that c, \text{occ}(c, i) is just the small number on L[i]. Row 1 ends in n0, and \text{occ}(\texttt{n}, 1) = 0, so \text{LF}(1) = C[\texttt{n}] + \text{occ}(\texttt{n}, 1) = 5 + 0 = 5.

Walk it, reading the numbers off the figure. Start at the row whose last letter in L is $, row 4. That row is the whole text, banana$. Row 4 ends in $0, so emit $. $0 heads row C[\$] + 0 = 0. Row 0 ends in a0, so emit a. a0 heads row C[\texttt{a}] + 0 = 1. Row 1 ends in n0, so emit n. n0 heads row C[\texttt{n}] + 0 = 5.

Now take the last four steps yourself, from row 5, until you emit b.

Rows 5, 2, 6 and 3 end in a1, n1, a2 and b0, so you jump to 1 + 1 = 2, 5 + 1 = 6 and 1 + 2 = 3, and emit a, n, a, b. Seven steps, and the characters came out as $ a n a n a b, which is banana$ read backwards.

Here is the walk in code, with the LF of every row worked out first. The whole function, including the count that builds C, is in the companion library, in bwt.py.

Listing 3.8: Burrows–Wheeler decode, Python.
def decode(last): ... seen = [0] * 256 lf = [0] * n for row, byte in enumerate(last): lf[row] = block_start[byte] + seen[byte] seen[byte] += 1 row = last.index(SENTINEL) backwards = bytearray(n) for step in range(n): backwards[step] = last[row] row = lf[row] backwards.reverse() return bytes(backwards)
Start from the last column and where each letter's block begins.
LF per row: block start plus same bytes above.each a in the last column is the a with the same number in the first columnannb$aa$aaabnnLF
Start at the row that ends in $.
Emit its letter and jump by LF, n times.
The text came out backwards: turn it around.

Step the walk yourself below, and try the slow way, by sorting, beside it.

Figure 3.17: Interactive Burrows–Wheeler transform: step the decoding walk, or decode by sorting.

In this chapter’s construction, the marker $ has to appear exactly once and sort before every letter. Without a unique end, the walk would not know which row is the whole text. The rotations would also no longer sort in the same order as the suffixes. The text abaa shows it. Its rotations sort as positions 2 3 0 1 and its suffixes sort as 3 2 0 1, because a suffix that runs out sorts first while a rotation wraps around and keeps going. With $ at the end the two orders agree, and the library refuses any text that holds a second $. In the library, $ is byte 0, which ordinary text never holds, so a dollar sign in a book is just another letter.

3.6.3 It is not compression

The walk shows that the transform loses nothing. It saves nothing either. It has exactly as many characters as the text, and exactly the same ones. What it changes is order, and that order has a habit that becomes visible on real text.

The rows are sorted by how they begin, which is what follows each row’s last character in the text. So characters that come before similar contexts land next to each other. In English, what comes before he is most often t. In Moby-Dick, of the 14,623 places where he occurs, 12,455 have a t in front of it. All those rows are neighbors in the sorted matrix, so their last characters form a long stretch of the transform that looks like this:

ttttttTttt tttttt tttttttttttt

The text itself never looks like that. The transform gathers letters that occur in similar company into runs. Runs are easy to squeeze. A later step does that by writing “t, twelve times” instead of twelve ts. That is how the bzip2 compressor uses the transform, and the compression chapter takes it from there.

Here, the transform has a different job. The next section turns the walk that gave the text back into an answer to Leo’s question.

3.7 By heart

FM-index and backward search

Picture the service from the start of the chapter, the one that answers “where is this line from?” for anyone who asks. It holds every book, script and lyric that people quote, Leo’s flood included. At five times the text or more, its index is the biggest thing it owns. Now suppose it kept only the transformed column, the same size as the text, and threw the text itself away. Could it still find “universally acknowledged”?

NoteTry first (no AI)

You have only the last column of banana$, annb$aa, the table C (0 for $, 1 for a, 4 for b, 5 for n), and the fact from the last section that, with the copies of each letter numbered from 0, c_k in L is c_k in F. No text, no matrix. Decide whether ana occurs in banana$, and how many times.

Start by asking which rows of the sorted matrix begin with the last letter of the pattern.

Fifteen minutes. You’re done when you know which rows begin with a, and then which rows begin with na.

Look at your rows for na. Did you find them from L and C alone, without the text? Here is the design that your answer should match.

The design 3.6

Goal: search the rearranged text directly, without rebuilding the text.

Promise: how many times a fragment occurs.

Idea: find the pattern from its end: first the suffixes that start with its last letter, then those that start with its last two letters, and so on, until the whole pattern.

Invariants:

  1. The rows kept so far are exactly the suffixes that start with the part of the pattern read so far, and they are found from the rearranged letters alone.

Cost: two counts per letter of the fragment, whatever the length of the text.

Assumes: the fragment has no $. One that does gets zero matches, since $ only marks the end of the text.

3.7.1 Searching backwards

Rows that begin with a are easy. They are a’s block in F, rows 1, 2 and 3. Write that as the stretch [1, 4), from row 1 up to, but not including, row 4. Every step from here keeps the design’s invariant, that the stretch is exactly the rows that begin with the part of the pattern read so far.

Now the pattern grows one letter to the left, to na. Which rows begin with na? Drop the n from such a row, and what is left begins with a, so it is one of rows 1 to 3. The question becomes which of rows 1 to 3 has an n just before it in the text. The letter just before a row’s first letter is its last letter, in L. That is why the pattern is read from its end. Row 1, a$banan, ends in n. Row 2, ana$ban, ends in n. Row 3, anana$b, ends in b. Rows 1 and 2 end in n0 and n1. One LF jump from each lands on the row that starts with that same n, na$bana and nana$ba.

Where do the new rows sit in n’s block? Each n in L carries a number, which is its place inside n’s block in F, counted from 0. Their numbering continues from the ns above the stretch. The first of them sits at the place given by the count of ns in L above row 1, where the stretch starts. The count above row 4, where the stretch ends, is the place just past the last of them. Both counts are offsets from the start of n’s block.

Table 3.4: How many copies of n lie in L above each row.
row L \text{occ}(\texttt{n}, \text{row}): how many copies of n lie in L above that row
1 n0 0
2 n1 1
3 b0 2
4, just past the stretch $0 2

So the new stretch needs only two numbers. L holds 0 ns above row 1 and 2 ns above row 4. The new rows are places 0 and 1 of n’s block, up to but not including place 2. Add each count to 5, where n’s block starts in F, and the stretch becomes [5, 7), rows 5 and 6, na$bana and nana$ba. One more letter to the left, a, works the same way from those two rows. L holds one a above row 5 and three as above row 7, and a’s block starts at row 1. The whole search, one letter per line:

Table 3.5: Backward search for ana in banana$, one letter per line.
letter read lo hi rows they begin with
a 1 4 1, 2, 3 a
n 5 + 0 = 5 5 + 2 = 7 5, 6 na
a 1 + 1 = 2 1 + 3 = 4 2, 3 ana

Each line adds two numbers: C[c], where the letter’s block starts in F, and how many of that letter lie in L above the old lo, or above the old hi. Written once, reading one more letter c to the left turns the stretch into

[\text{lo}, \text{hi}) \;\to\; [\,C[c] + \text{occ}(c, \text{lo}),\; C[c] + \text{occ}(c, \text{hi})\,). \tag{3.2}

It is equation (3.1), applied at both ends of the stretch.

The last line’s rows, 2 and 3, are ana$ban and anana$b. The answer to how many? is 4 - 2 = 2, and the text was never consulted.

Count the cost. Each letter of the pattern needs two counts, \text{occ}(c, \text{lo}) and \text{occ}(c, \text{hi}). That is two questions per letter, whatever the length of the text. If those two counts are fast, 48 questions tell how often a 24-letter fragment occurs, in an index of any size.

This is the FM-index, invented by Paolo Ferragina and Giovanni Manzini [22], and backward search is its central idea. The whole design now hangs on one operation, counting a letter above a row. The three jobs left are the text index’s three questions again. count needs that letter counted fast, without keeping much more than the column itself. locate needs where each match starts. extract needs the words around it.

3.7.2 Counting fast

Counting the cs above a row one by one would be a scan of L again. Instead, keep checkpoints. Every k rows, store how many of each letter came before that row. Then \text{occ}(c, i) is one lookup, at the last checkpoint at or before row i, plus a short count of the cs between it and row i.

\text{occ}(c, i) = \text{occ}(c, \text{checkpoint}) + c\text{s between}. \tag{3.3}

The cs between are counted from the checkpoint up to, but not including, row i.

Take annb$aa with a checkpoint every k = 4 rows. The checkpoint at row 0 stores 0 for every letter. Rows 0 to 3 hold annb, so the one at row 4 stores one a, one b and two ns. Then \text{occ}(\texttt{a}, 7) = 1 + 2 = 3, where the 2 counts the as in rows 4, 5 and 6, which hold $, a and a. Check it by hand. The as above row 7 are in rows 0, 5 and 6. That makes three, the same count that the search for ana used.

3.7.3 The index, with the book thrown away

Here is the index itself, the one that the library ships. Building it sorts the suffixes once, reads off the transform, and then keeps the transform in a compressed form that can answer occ directly. How it compresses is a black box here, and opening that box is a job for the compression chapter. Everything around it is this chapter.

The box answers two questions: how many cs are above row i? and what letter is in row i, and how many of that letter are above it? Backward search asks the first, and each LF step asks the second.

Inside the box, the last column is stored in less space than the column itself, in a kind of wavelet tree [23].

In the code, the wavelet tree is self._occ. self._occ.occ(c, i) answers the first question, and self._occ.access_occ(i) answers the second. Beside it, self._c holds C, filed by letter, and self.text_len() is n. The constructor that builds them is in the companion library, in fm_index.py.

Counting is now the walk you did by hand on banana$. _interval(p) finds the stretch of rows whose suffix begins with p, as the pair lo, hi. For a non-empty p with no $, count(p) is the stretch’s width, hi - lo, which is the number of positions where p occurs. The whole of count is in the same file.

Listing 3.9: FM-index backward search, Python.
def _interval(self, pattern): n = self.text_len() if (len(pattern) > n or SENTINEL in pattern[:-1]): return None lo, hi = 0, n for symbol in reversed(pattern): base = self._c.get(symbol) if base is None: return None lo = base + self._occ.occ(symbol, lo) hi = base + self._occ.occ(symbol, hi) if lo >= hi: return None return lo, hi
Refuse too long a pattern, or a $ before its end, which only wrapped rotations match.
Start with every row, then read the pattern right to left.
A letter that the text never uses means no match.
Two counts narrow the stretch. Empty: no match.backward search for ana: every row, then the a-rows, then na, then ana; the block only ever narrowsanaana

Built over banana$, with $ written as the zero byte, the index counts the two places where ana starts. The second argument is the sampling rate of the next section. For seven letters, 2 will do.

Listing 3.10: Counting with the FM-index, against the library, Python.
from algodesign.strings.fm_index import FMIndex

index = FMIndex(b"banana\x00", 2)
print(index.count(b"ana"))   # 2

Watch the stretch narrow below, letter by letter, then follow one match back to its place and to its quote.

Figure 3.19: Interactive FM-index backward search, one letter at a time.

3.8 Give me the whole line

Locate, extract and document listing

Two, says the index, for universally acknowledged. Leo has no use for a number. He wants the line, whole, while the moment is still there. The book is gone, so where the match sits and what words surround it must both come out of the same last column and a few numbers kept on the side.

3.8.1 Where the match sits

The rows in the stretch are rows of the suffix array, and the suffix array would say exactly where each one starts. But keeping it is 4n bytes again, which the FM-index set out to drop.

The design 3.7

Goal: say where each match starts, without keeping the suffix array.

Promise: every start position, each exactly once, in no particular order.

Idea: keep a few positions, and walk to the nearest one.

Invariants, added to the FM-index’s invariant 1:

  1. At fixed intervals along the text, a row keeps its own position, so every match is a short walk from one.

Cost: one kept position per interval; each match, fewer steps than the interval.

The walk comes from the last column, which gives a step back through the text. Each LF step, equation (3.1), lands on the row that starts one position earlier. In the suffix array’s terms,

\texttt{sa}[\text{LF}(i)] = \texttt{sa}[i] - 1. \tag{3.4}

Row 1 holds position 5, and LF takes it to row 5 (worked out in Reading it backwards), which holds position 4. The one exception is row 4, which holds position 0. Its step lands on row 0, which holds the $ at position 6, so the walk wraps around to the end.

Pick a rate, the interval between kept positions, for example every 32nd text position. Remember the row of each position that is a multiple of 32, and mark that row, the same move as the checkpoints for counting. To find the position of an unmarked row, walk LF from it, one step back in the text at a time, until you reach a marked row. Its stored position plus the number of steps you took is the answer. Every multiple of the rate is marked, position 0 included, so a walk always takes fewer steps than the rate (invariant 2) [24, Secs. 11.1.4, 11.2].

On banana$, with every second position sampled, positions 0, 2, 4 and 6 are kept. They sit in rows 4, 6, 5 and 0, the dotted rows of the banana$ table shown once more below.

The same table, at a rate of 2: only the dotted rows keep their start position. The gray positions are not stored; a walk recovers them.
Figure 3.20: The same table, at a rate of 2: only the dotted rows keep their start position. The gray positions are not stored; a walk recovers them.

The stretch for ana holds rows 2 and 3. Row 2 is not marked. It ends in n1, so one LF step takes it to row C[\texttt{n}] + 1 = 6, which is marked with position 2. So row 2 is position 2 + 1 = 3. Now do row 3 yourself.

Row 3 ends in b0, so one step takes it to row C[\texttt{b}] + 0 = 4, marked with position 0, so row 3 is position 0 + 1 = 1. Positions 3 and 1, as the suffix array said.

The index keeps these samples from the moment it is built. Its constructor reads them off the suffix array in one pass over the rows, before the suffix array is thrown away:3

Listing 3.11: FM-index construction, keeping position samples, Python.
def __init__(self, text, sample=SAMPLE): ... for row, position in enumerate(sa): if position % sample == 0: marks[row] = 1 self._sa_samples.append(position) k = position // sample self._isa_samples[k] = row
Get the suffix array and empty sample lists.
Keep every sample-th position and its row, and mark the row.only every sample-th text position is kept, with its row markedevery 4th position kept

Leave out the rate, and the constructor uses SAMPLE, which is 32 positions.

Then locate(p) turns every row of _interval(p) into a position with _position_of, which walks by LF one step at a time. The whole of locate is in fm_index.py.

Listing 3.12: FM-index LF step and position recovery, Python.
def _lf(self, row): symbol, occ = self._occ.access_occ(row) return symbol, self._c[symbol] + occ ​ def _position_of(self, row): steps = 0 while not self._marks.access(row): _, row = self._lf(row) steps += 1 k = self._marks.rank(row) return self._sa_samples[k] + steps
One LF step: the letter, and the row one position earlier.
Walk back to a marked row, counting the steps.walk back from the hit to the nearest kept position, then add the steps2 stepssample + 2
That row's sample plus the steps is where the hit starts.

The rate is the setting that trades space against time. Sample more often, and the samples cost more space. Sample less often, and every position costs a longer walk. Here is the library’s index on the ten books, at three rates:4

Table 3.6: Sample rate against index size and time per position found.
one sample every index size time per position found
16 positions 0.882 n 1.2 µs
32 positions 0.685 n 2.4 µs
64 positions 0.586 n 4.6 µs

Sample half as often and the time roughly doubles, because an average walk takes about half as many steps as there are positions between samples. The size drops each time by only half as much as before, because only the samples shrink and the compressed column underneath stays the same size.

3.8.2 Getting the words back

The text is gone. To show Leo his line, the index has to produce the letters, and it has nothing to produce them from but the walk. LF walks the text backwards, emitting the letter in L at every row. So to read a range, start at a known row after it and walk back.

Say the range starts at position s and is \ell characters long, so its last letter is at e = s + \ell - 1. The constructor’s loop also kept a second list of samples, _isa_samples, which holds the row of every kept position. Let t be the first kept position greater than e. Starting from t’s row, the walk takes t - s steps and gives the letters from position t - 1 down to s. Reverse them and keep the first \ell. The ones past the range are dropped.

Take banana$ at a rate of 2, where positions 0, 2, 4 and 6 are kept, in rows 4, 6, 5 and 0, and extract s = 1, \ell = 2:

  1. The range ends at e = 1 + 2 - 1 = 2, so t = 4, kept in row 5.
  2. The walk takes t - s = 3 steps, rows 5, 2 and 6, and emits a, n, a: positions 3, 2 and 1.
  3. Reversed, that is ana. Keep the first 2, an, which is positions 1 and 2 of banana$. The a at position 3 is past the range and dropped.

Extracting \ell characters takes about \ell steps, plus at most the sampling rate to get from the sample to the end of the range. The check to write for it says that, for every start s and length \ell, what comes out must equal the \ell letters of the text that start at s. The book can be read back out of its index, every line of it, from anywhere.

If the range runs so close to the end that no kept position comes after it, the walk starts from the row of position 0. That row’s rotation starts at 0, so its last letter is the final $. The walk gives the $ first, then the text from its end backwards. The code for extract, with its tests, is in the companion library, in fm_index.py.

3.8.3 From a hit to the whole quote

One last step remains, and it is the one about which Leo cares. A hit is only a position, and he wants the quote, the whole line, whichever piece of it he remembered.

Guess first. Say three quotes start at positions 0, 16 and 30 of one long text, and a hit for Leo’s fragment lands at 24. Which quote is it, and what single count would tell you?

Make every quote a record, here a paragraph of a book, and join them all into one text, with a separator between neighbors and $ at the very end. Then keep one more row of bits, B, as long as the text, with a 1 wherever a record starts [24, Ch. 11]. Now placing a hit in its quote needs only a count of the 1s in B.

Three quotes joined into one text, with B marking where each starts, and a hit for truth at position 24.
Figure 3.21: Three quotes joined into one text, with B marking where each starts, and a hit for truth at position 24.

From B alone, find which quote holds the hit, and where that quote starts and ends.

Count the quotes from 0, as positions are counted. The quote that starts at position 0 is quote 0, and each 1 in B takes the number of the quote it starts. In the figure, the hit for truth is at position 24. Count the 1s at or before position 24. There are two, so the hit is in quote 1.

That count is a rank, the question that occ already asked of L, now asked of a row of 0s and 1s. \text{rank}(i) counts the 1s before position i, so the count of 1s at or before position 24 is \text{rank}(25). Checkpoints make it fast as they did for L.

Because the first record starts at position 0, every hit has a 1 at or before it, so the count less one is the number of the quote in which the hit falls, here \text{rank}(25) - 1 = 1.

Quote 1 runs from its own 1, at 16. Finding where a given 1 sits is rank’s partner, select. It is the search chapter’s other question, which key is in position j, asked of bits. \text{select}(j) is the position of the 1 that starts quote j, the one with j 1s before it, so on B \text{select}(0) = 0 and \text{select}(1) = 16.

The quote and its separator run up to just before the next 1, and the next 1 is \text{select}(2) = 30. So the separator sits at 29, and the quote ends at 28. Extract positions 16 to 28, and that is the quote, it is a truth. The last quote has no next 1, so it runs up to just before the $ at the end.

For a hit at p, what you just did is:

  • quote = \text{rank}(p + 1) - 1,
  • start = \text{select}(\text{quote}),
  • separator = \text{select}(\text{quote} + 1) - 1.

The hit is used exactly once, for one rank, and then forgotten. Everything after it depends only on the quote in which it fell. So a fragment from the start of a quote, from the middle, or from the last three words costs the same. That is the property Leo needed, and it took nothing new, only rank and select, two questions you have already met, asked of one more row of bits.

Checkpoints work on B as they did on L. With a checkpoint every 16 positions, \text{rank}(25) = \text{rank}(16) + 1 = 2. The checkpoint at 16 holds the 1 at 0, and the bits from 16 to 24 hold one more, at 16.

Storing the answer for every position would cost an integer per bit, far more than the bits themselves, and counting from the start every time is a scan. The way out lies between the two extremes, with the checkpoints from above set in two layers.

A two-level directory for rank. Each big block stores how many 1s come before it, in absolute terms. Each small block stores how many come before it within its big block, which needs only a small number. A query adds the two, then counts the few bits left inside its small block.
Figure 3.22: A two-level directory for rank. Each big block stores how many 1s come before it, in absolute terms. Each small block stores how many come before it within its big block, which needs only a small number. A query adds the two, then counts the few bits left inside its small block.

Cut the bits into small blocks, and group the small blocks into big blocks. For every big block, store how many 1s come before it. That is a full-size number, but there are few big blocks. For every small block, store how many 1s come before it within its big block. There are many small blocks, but each number is small, because it can never exceed the size of a big block. Then \text{rank}(i) is the big block’s number, plus the small block’s number, plus a count of the few bits between the start of i’s small block and i. That is two lookups and a short count, however long the row of bits is [26]. With the sizes that real systems use, the two tables together add only a small fraction of the size of the bits themselves.

The separator can’t be another $, because the transform needs $ exactly once. So the separator is a second reserved byte. Both reserved bytes are kept out of the quotes. A record that holds either is refused with an error when the whole collection, the corpus, is built. A fragment that holds either finds nothing when it is asked.

Any quote finder must get these cases right. Each one catches a slip that is easy to make, by hand or with an AI:

  • A hit on the first byte of a quote returns that quote. The slip is counting only the 1s before the hit. The hit sits on its quote’s own 1, so that count comes out one short and names the previous quote.
  • A hit on the last byte of a quote returns that quote, without the separator after it. The slip is keeping the separator on the end of the quote.
  • A hit in the last quote returns that quote whole, up to just before the $. The slip is looking for a next 1 that is not there.
  • A fragment that runs from the end of one quote, across the separator, into the start of the next finds nothing. The slip is forgetting that rule, so a match runs from one quote into the next.

The library’s Corpus gets all four right. Here they are on the three quotes of Figure 3.21, one line each, in the order of the list:

Listing 3.13: The four cases on the three quotes of Figure 3.21, Python.
from algodesign.strings import Corpus, SEPARATOR

corpus = Corpus([b"call me ishmael", b"it is a truth", b"all happy families"])
def quotes(fragment):
    return [q.text for q in corpus.find(fragment)]

print(quotes(b"it is"))     # [b'it is a truth']
print(quotes(b"truth"))     # [b'it is a truth']
print(quotes(b"families"))  # [b'all happy families']
crossing = b"ishmael" + bytes([SEPARATOR]) + b"it"
print(quotes(crossing))     # []

Now run it on the ten books, cut into 22,703 paragraphs. Type drizzly November, and back comes a paragraph of Moby-Dick, whole, 1,115 bytes of it. It starts “Call me Ishmael. Some years ago…”, runs on through the drizzly November to the end of the paragraph, and keeps the line breaks of the printed edition. Type in my soul, and six paragraphs come back from four books: three from Moby-Dick and one each from Shelley’s Frankenstein, Great Expectations and Dracula. Type universally acknowledged, and both paragraphs from earlier come back, Austen’s opening and Dickens’s poet. Not one of those quotes was stored anywhere as text.

3.8.4 What it costs

The library ships an index built over the ten books with one sample every 32 positions (the middle row of Table 3.6). It takes 0.685 bytes for every byte of text: 4,656,156 bytes, against 6,793,687 bytes of text and $. It is smaller than the book, and the book is not kept. Table 3.7 shows the whole way down from the middle of the chapter. The suffix tree takes about 50 times the FM-index’s space, and the suffix array takes 7.3 times. The last step down, to the FM-index, composed the suffix array with three other ideas: the transform, checkpoints for counting, and samples for positions.

Table 3.7: Space for every byte of book: the FM-index measured on the ten books; the suffix tree and the suffix array from the costs per node and per entry above.
Index Bytes for every byte of book Book kept beside it?
Suffix tree about 34 + 1 = 35 yes
Suffix array 4 + 1 = 5 yes
FM-index 0.685 no

In that space it counts, finds and quotes. Counting an eight-letter fragment and finding each of its positions both take a few millionths of a second.5

How few bits the column needs depends on how predictable each letter is from the letters around it, which the compression chapter measures as the text’s entropy. The sorted order puts letters that keep the same company side by side, as it gathered the 12,455 ts before he into one stretch of Moby-Dick’s transform. The black box that holds the column is built to make use of that.

The 0.685 bytes for every byte of text are paid for in speed, since every count is decoded from the compressed column. For Leo’s flood, the space is the cost that decides. One index also has a size limit, so a large service cuts its corpus into pieces between quotes.

Compare the compressed index with a plain one. The plain one keeps the column as bytes with a running count every 512 rows and stores the samples and marks uncompressed, so it takes about two bytes for every byte of text. The compressed index keeps a running count only once per chunk of the column, about 67,000 rows on the ten books, and counts inside the chunk with its black box. Timed side by side in the same run as above, the compressed index is about 3 times slower to count and to read back, and about 6 times slower to locate. In return, it needs a third of the space.6

One index cannot grow forever, though. The library stores its positions as 4-byte numbers, which reach about 4.29 billion characters, and building an index holds several arrays of n numbers in memory at once. Leo’s flood is far bigger than that. So a service cuts the collection into pieces of a few gigabytes, always between two quotes. It builds an index for each piece, asks every piece the same question, and merges the answers. Because no cut falls inside a quote, every quote is found whole, in one piece.

The design holds up at sizes far past ten books. In 2025 a team built this same kind of index over 83 terabytes of web text, on raw bytes exactly as this chapter does, and the index came to 44% of the size of the text it replaced [27].

The library states the invariant of backward search in the proof assistant Lean, in lean/AlgoDesign/Strings/FMIndex/Spec.lean, and proves it in FMIndex/Search.lean. The invariant says a row lies in the stretch that backward search returns exactly when the suffix in that row begins with the pattern, for any text that ends in a single $ and any pattern without $ before its end. A second theorem says the count it gives is the number of positions where the pattern occurs. For the records, a third says that the hit lies between the bounds that two selects give for its record, the record whose number is its rank less one. Two more say that a search returns exactly the records containing the fragment, each once and in order, and that each comes back whole.

The proofs are about texts written as lists of numbers, with the last column counted plainly and rank and select read straight off the row of bits, not through the directory. The compressed column, the black box above, has no proof of its own. It is held to the plain version by tests. And no proof says anything about whether exact bytes was the right thing to search for, which is the question that the curly apostrophe asked earlier in the chapter.

3.8.5 What a frozen index can’t do

Every structure after the Patricia tree was built once and then only asked questions. The FM-index is the extreme case. It is a single sorted arrangement of the whole text, and adding one new quote anywhere changes rows all through it. To add a book, you build the index again. For a library of Gutenberg classics that is fine, since nobody is adding chapters to Moby-Dick. For a corpus that grows every day, the assumption that the text never changes breaks. The practice section returns to that problem.

3.9 ✎ When assumptions change practice

NoteNo-AI check

A service has 100 GB of text that never changes, and it must answer millions of “where does this fragment occur?” questions a day from a machine with 128 GB of memory. A colleague proposes a suffix array, “because it’s the standard”. Say what that proposal would need in memory, and which structure in this chapter fits instead. Then say which of the three questions, count, locate and extract, gets slower in exchange, and which setting decides by how much.

NoteNo-AI check

The same service now receives about a thousand new documents every day, and they must be searchable within the hour. Which assumption of the FM-index does this break? Then describe a design that keeps most of the index’s advantages anyway, without rebuilding the whole thing every hour. (A hint: the search chapter’s LSM-tree stopped repairing and started stacking.)

NoteNo-AI check

A hospital stores the genomes of ten thousand patients, each about three billion letters, and each differs from the others in only about one letter in a thousand. Someone builds this chapter’s FM-index over one genome, multiplies its size by ten thousand, and gets about the right size for an FM-index of the whole collection. Say why that is still far more than the collection really holds, which property of this collection the FM-index ignores, and what a better measure of its size would count. Think about the runs in the transform.

3.10 ◆ What these are actually made of big picture

This chapter built nine structures, from a plain scan to an index that replaces its book. Open them up, and they are made of a handful of small ideas, several of which you met in the search chapter, where they did completely different jobs.

Every structure in this chapter, written as what it is made of. Look for the chips that come back in more than one row.
Figure 3.23: Every structure in this chapter, written as what it is made of. Look for the chips that come back in more than one row.

Scan = look at every window. No preparation, no invariants, and every question re-reads everything. Every other structure here is an attempt not to look at every window.

Rabin–Karp = fingerprinting + randomization + check every match. Fingerprinting: compare two small numbers instead of two long strings, and accept that equal numbers only mean maybe. Randomization: pick the modulus at random, so nobody can write a text that fools it every time. Check every match: a maybe is confirmed against the real characters before it is reported, which is what makes the method exact. The Bloom filter in the search chapter made the opposite choice. It never checks, and accepts being wrong in one direction.

Trie = the word is the path. Nothing stores a word. The words are the routes down the tree, and shared beginnings are walked once.

Patricia tree = trie + canonical form. Every node below the root branches or ends a word. Every insert and removal restores that invariant before it finishes, so each set of words has one standard shape, its canonical form. That invariant is what keeps the tree to at most two nodes per word, whatever the shape of the words.

Suffix array = a position, not a copy + doubling + divide and conquer. Store where each suffix starts, never its letters. Sort by doubling, so two numbers from the last round stand in for twice as many letters. Then search by divide and conquer, halving the range, exactly as binary search did in the search chapter.

LCP array = suffix array + carry what you know. The count of matching letters is carried from one position to the next (carry what you know), because it drops by at most one (the appendix shows why), so no letter is compared from scratch twice.

Burrows–Wheeler transform = suffix array + equal letters keep their order. Read the letter before every sorted suffix, and the text becomes a permutation of itself that can be walked backwards. The transform is the one idea here that belongs to strings alone. The compression chapter uses it again for a different end.

FM-index = BWT + rank and select + work in blocks + sample, then walk. Backward search turns every question into counts of a letter above a row. Each of those counts is one rank. Checkpoints kept in blocks (work in blocks) make rank fast in little space, as fat nodes made the B-tree fast on disk. Sample, then walk keeps only every 32nd position and recovers the rest by walking. The sampling rate trades space against time.

Quote from a hit = FM-index + rank and select again + reserved separators. One rank finds the quote, and two selects bound it. The same two questions now apply to one more row of bits.

Some of these parts can be swapped for another part that does the same job. Figure 3.24 shows a few, each beside the choice that this chapter made. The first three rows keep the promise and change only the cost. The last row is the one part of Rabin–Karp that cannot go. Skip the check, and a window that only shares the pattern’s number is reported as a match.

Parts that can be swapped, each beside the choice that this chapter made. The struck-through one breaks the promise.
Figure 3.24: Parts that can be swapped, each beside the choice that this chapter made. The struck-through one breaks the promise.

3.10.1 Choosing one, under pressure

Every structure here makes a promise. Break what the promise needs and the answers are wrong. Break what makes the structure a good choice, and the answers are still right, but you are paying for the wrong thing. Each row of Table 3.8 is a short contract, in the contracts chapter’s sense. The last column is its failure mode, what you see when what the promise needs is broken. In every row, unless something guards against it, you see no error at all, just a wrong answer.

Table 3.8: Choosing a string structure: what the promise needs, when it fits, how it breaks.
structure the promise needs it is a good choice when if it breaks
Scan (Rabin–Karp) every fingerprint match is checked against the text the text is searched once, or changes all the time, because every question re-reads all of it a false alarm is reported as a match, at a position where the pattern is not
Trie, Patricia tree the stored keys, and nothing else, end at marked nodes the fragment and a key must agree from their first letter, as in autocomplete or a router’s table a removed word that keeps its mark is still found, and autocomplete goes on offering it
Suffix array the array is the sorted order of the suffixes of this text any fragment must be found, the text rarely changes, and it fits several times over in memory after the text changes, the search returns positions where the fragment no longer is, and misses where it now is
FM-index the text ends in one unique $, and the index was built from it the text is large, fixed and searched often, space matters more than a few microseconds, and a position is answer enough the rotations stop sorting like the suffixes, and a fragment is found running off the end of the text and around to its start; after the text changes, positions point at the wrong places
Quote from a hit no record holds a reserved byte, and no fragment does either answers must be whole records, whichever piece of one was remembered a match straddles two quotes, and back comes a quote that does not contain the fragment

3.10.2 What each one costs

For a text of n characters, a fragment of m characters, and z occurrences of it. Sizes include everything that must be kept to answer, the text too when it is needed.

Table 3.9: What each string structure costs.
structure prepare count locate size
Scan (Rabin–Karp) nothing about n + m steps, expected, plus m per occurrence the same the text, n
Patricia tree, of k keys about the total length of the keys m steps, plus a step per answer the same at most 2k nodes, plus the keys
Suffix array about n \log_2 n steps by doubling about 2m \log_2 n comparisons plus z 5n bytes, text included
FM-index the suffix array, once 2m counts plus at most the sampling rate in steps per occurrence 0.685 n on the ten books, with one sample every 32 positions, text not needed

Three things the table says that its cells don’t say.

Only one row doesn’t need the text. Every other structure keeps the book and adds to it. The FM-index is the book, in a form that also answers questions.

The FM-index’s count takes the same number of steps for any n. Each letter of the fragment costs two counts, whether the text is banana$ or a library. What grows with the text is the number of occurrences to find. Each costs at most the sampling rate in steps, which you can trade for space with one setting.

The scan is still the right answer sometimes. For a text searched once, any preparation is wasted. For a text that changes every second, every index is out of date before it is built. A row nobody would choose for Leo is the right row for a log file being written as you watch it.

3.10.3 Where they run

Each of these runs inside programs in daily use.

Table 3.10: Where each structure runs.
structure where it runs
Rolling fingerprint the substring search of Go’s standard library, as a fallback when plain comparison keeps failing, with a fixed base and every match checked, so it gives up the random prime that the design assumes; file synchronization that sends only the parts of a file that changed, as rsync does; backup tools that cut files into pieces wherever the fingerprint of the last few bytes hits a chosen value
Trie and Patricia tree routers choosing where to send a packet (the router appendix); web servers matching a request’s path to the code that answers it; the indexes of some databases
Suffix array finding text that repeats across a huge collection, such as the training text of a language model; building the transform
Burrows–Wheeler transform compressors, bzip2 among them
FM-index read aligners such as BWA [28] and Bowtie [29], which place short pieces of DNA on a reference genome

One kind of program is missing from the table. A web search engine, or the search box of a mail program, keeps an inverted index, the machine-built index of words from the start of the chapter. Text in those programs splits into words, and an index of words is smaller and simpler. The structures here take over where text has no words to cut it into: a genome, a model’s training text, a file being synchronized, an address. Where any piece can be the question, an index of short pieces of text, the kind that GitHub built for its code search, still serves. Such an n-gram index works as the fingerprint did in the first section, with a quick maybe first and a check of the real letters after.

3.10.4 The same ideas, over and over

Table 3.11: This chapter’s primitives and where else they turn up.
primitive where else it turns up
fingerprinting checking that two files match, the Bloom filter
randomization quicksort’s pivot, hash tables, the treap
canonical form sorting a list before removing duplicates, fractions in lowest terms
doubling a growable array, galloping search, jumping up a tree by powers of two
divide and conquer binary search, mergesort
carry what you know a running total, sliding-window maximums
work in blocks B-tree nodes, disk pages, cache lines
sample, then walk checkpoints in a video file, the index of a long log

Rank and select, the two questions under the FM-index, turn up as widely: in the search chapter’s ordered dictionaries, in compressed graphs, and in tree layouts stored as bits.

Most of these ideas came into this chapter from somewhere else, and every one of them leaves it for somewhere else again. When a problem arrives that no structure here fits, the useful question is which of these ideas it needs: what must be checked, what can be carried, what can be counted in blocks, and what you can afford to forget and recover by walking.

3.11 ◆ Where that leaves the quote big picture

Back at the dinner table. Somebody is talking about a long winter, and Leo has a fragment, “in my soul”. In the time it takes to put down his glass, an index smaller than the books it came from has found six paragraphs in four of them, and handed back, whole, the one he wanted. He says it, the table goes quiet for a second in the good way, and the conversation moves on carrying one more shared thing.

None of that needed a new idea at the moment it happened. Every piece of it was decided long before, by asking the same few questions of each structure in turn. What does the person actually remember: a start, a middle, any piece? What happens at question time, and what can be done once in advance? What has to be kept, and what can be thrown away and rebuilt by walking? And what does exact mean? As the curly apostrophe showed, that was a decision before it was ever an algorithm. The structures in this chapter are answers to those questions under one set of conditions. Change the conditions, and the same questions pick a different structure.

Almost every name that this chapter used is the one that the rest of the world uses too: pattern, window, fingerprint, trie, Patricia tree, suffix, suffix array, LCP array, Burrows–Wheeler transform, LF mapping, rank, select, FM-index, sampling. The table of longest borders, the prefix function, is also called the failure function. A stretch of rows is a suffix-array interval, a record is a document, and finding the records that hold a fragment is document listing. Open any implementation, read any paper, ask any model, and those words will be waiting.

A few were this chapter’s own. A false alarm is what the literature calls a spurious hit. To squeeze the chains is path compression in tries. And Leo’s flood was only ever a name for a large corpus. Those names were scaffolding, and the ideas underneath keep their standard names.

The quotes were never really the point. Knowing what it costs to find any piece of a text, and what you can afford to keep, was the point.

3.12 ✎ Hands-on projects practice

Projects come first. In each one you build something, measure something, or explain something to another person. They have no single right answer, so judge them against the checks that each one asks you to build. After them come the self-check problems, numbered exercises that each have an answer you can check. Do some of each. The exercises show what you know, and the projects show what you can do. Each problem that uses the appendix Why the fast versions are right says so. Where a project needs code, let an AI write it. The times given assume that the AI writes the code. Your job, even when the AI helps, is saying what the code must do, building the check that shows that the code does it, and judging what comes back.

Project 1 · the FM-index · hard · ~2 hours

Build Leo’s quote finder. Download a handful of books from Project Gutenberg, from at least three continents and in at least two languages, one of them your own. Cut them into paragraphs, and have an AI build a quote finder over them that returns whole paragraphs for any fragment. Before you ask, write down your checks:

  • for a thousand fragments cut at random out of the books, the finder returns every paragraph that a plain scan finds, and no other;
  • a fragment that appears in no book returns nothing;
  • the empty fragment returns every paragraph;
  • a fragment that crosses the end of one paragraph into the start of the next is never reported as found inside either.

Build the checks yourself, and run them before you believe a single answer. Then count how many different bytes your books use, compare that count with the ten books’ 125 different bytes, and explain the difference.

Project 2 · tries · ~45 min

Count the chains. Collect the opening sentences of a hundred novels you can find online. Have an AI store them in a trie and in a Patricia tree and report the node count of each. Before you see the counts, predict their ratio, and say why. Then store the last sentences of the same hundred novels and compare. Explain the difference in words that a friend who has not read this chapter would follow.

Project 3 · what is a character · ~1 hour

Decide what “exact” means. Take the corpus from Project 1 and add a step before indexing that rewrites every curly apostrophe and quotation mark as a straight one and every run of spaces and line breaks as a single space. Keep in mind that a letter like č, stored as one character, is two bytes, so a search for c does not find it. Write down first, as a specification, exactly which differences your finder now ignores and which it still respects. Then find a fragment that the normalized finder matches and the raw one doesn’t match, and one where normalizing makes the answer wrong by your own specification. If you can’t find the second, say why your specification rules it out.

Project 4 · the suffix array · hard · ~1.5 hours

Skip the letters you already know. The suffix-array search compares the pattern from its first letter on every look. Since the rows are sorted, a look between two rows that both share the first k letters with the pattern can start comparing at letter k. To never compare a letter twice, the search also needs a table, worked out once from the LCP array. For every pair of rows between which the search can land, the table says how many letters their suffixes share. Have an AI write that faster search, with its table. Specify the check first. It must return exactly what the plain search returns, on every fragment you try, including the empty one and one that occurs nowhere. Then measure both on a whole book, with fragments of length 5, 20 and 100, and say whether the saving pays for the extra table.

Project 5 · the LCP array · ~45 min

Find what a book repeats. Pick a book, have an AI compute its suffix array and LCP array, and list the ten longest passages that occur at least twice. Before you look, guess what they will be. Then explain each one: a refrain, a chapter heading, a phrase that a person in the book keeps saying, a printing convention. Which of them would a reader call a repetition, and which would only a machine call one?

Project 6 · the FM-index · ~1 hour

Choose the rate. Build the quote finder from Project 1 with one sample every 4, 16, 64 and 256 positions. For each, measure the size of the index and the time to locate every occurrence of a common word. Plot both against the rate, and say which rate you would ship for a phone, for a laptop, and for a server that answers a million questions a day, and why the three answers differ.

Project 7 · the quote finder · hard · ~2 hours

Visit each quote once. The quote finder locates every hit and then keeps each quote once, so a common word that occurs ten thousand times inside forty quotes costs ten thousand walks to return forty answers. Have an AI build a finder whose cost grows with the number of quotes it returns, not with the number of hits, and have it explain the extra structure that the finder needs and what that structure costs in space. Specify the check first. On every fragment you try, it must return exactly the quotes that the plain finder returns. Then measure both on fragments that occur ten, a thousand and a hundred thousand times, and say where the extra structure pays for itself.

Project 8 · design · hard · ~2 hours

Keep a changing library searchable. New books arrive every day, and a book already stored can be corrected or taken down. Every search must return each paragraph that holds the fragment now, exactly once: never a paragraph from a book that was taken down, never the old wording of a corrected one, never the same paragraph twice. No structure in this chapter does that alone. Design an arrangement that does, and write it as a design box of your own: a goal, an idea, and the invariants it keeps. Say how its pieces work together on one search. Then build the smallest example that catches a design breaking one of your invariants: a few books, one correction, one removal, one fragment. Have an AI build the arrangement, and run your example before you believe it.

Project 9 · the suffix tree · ~1 hour

Measure why the tree doesn’t fit. By hand, put every suffix of tomato$ into a trie, then squeeze its chains as the Patricia tree does. Count the nodes of each, and find to in both. Then have an AI insert every suffix of the first 1,000, 2,000 and 4,000 characters of a book into a trie and into a Patricia tree, and report the node counts. Check your counts against the growth that the chapter states. Then estimate the bytes per character of text for each, if every node takes about 24 bytes.

NoteNo-AI check: find the bug that shipped

A quote finder joins its paragraphs into one text before indexing them. To keep things simple, the person who wrote it joined them with a single space instead of a reserved byte, and every test they wrote passed. Here is the part that joins:

Listing 3.14: Joining the paragraphs, Python.
text = b" ".join(paragraphs) + END

END is the end marker, the chapter’s $.

  1. Before running anything, say what kind of fragment this version gets wrong, and what wrong answer it gives. The section From a hit to the whole quote has the reason.
  2. Write the smallest input that shows it, two paragraphs and one fragment. Smallest means fewest characters. If yours has more than twenty, keep cutting.
  3. Now take the first two paragraphs of Pride and Prejudice, which end and begin “…in want of a wife.” and “However little known…”, and say what this finder returns for the fragment wife. However. Then say what it should return.

Only after you have your own answer, hand the line to an AI and ask what is wrong with it. Does its answer find the problem? A space looks like a perfectly good separator in one line of code. Whether it is a good separator depends on a rule that lives in another part of the program, which the AI was not shown.

3.13 ✎ Self-check problems practice

Transfer 1 · middling · ~30 min

The longest piece two strands share. Two short strands of DNA read ggacgatt and gctacgag. What is the longest run of letters that appears in both? Read each letter as a digit, a as 1, c as 2, g as 3 and t as 4. A window of letters is then a number in base 10, as in A number for each window. Use the modulus 13.

  1. Do the two strands share a piece of five letters? Roll a fingerprint across each strand and compare. Which pair of windows agrees by accident, and what settles it?
  2. A binary search can find the longest shared length without trying every length. Which sentence does it keep true, and why does a yes at one length mean yes at every shorter length? Run it, starting from “at least 0 and less than 9”, and test the middle length, rounded down, each time. Which lengths do you test, and what is the answer?
  3. Suppose you trusted equal fingerprints without reading the letters. What would the search report, and which sentence would stop being true? The chapter found the longest repeat inside one text from the LCP array. Join the strands as ggacgatt#gctacgag$, with a # that is in neither. Why is the largest LCP entry of the joined text not always the answer, and which entries are the answer?
  1. No. A leading digit weighs 10^4 \bmod 13 = 3. The five-letter windows of ggacgatt are 33123, 31231, 12314 and 23144, with fingerprints 12, 5, 3 and 4. Those of gctacgag are 32412, 24123, 41231 and 12313, with fingerprints 3, 8, 8 and 2. One pair agrees, acgat and gctac, both 3. Reading the letters shows they differ, so it is a false alarm, and no five-letter piece is shared.
  2. The sentence is “the longest shared length is at least lo and less than hi”. A shared piece of length L begins with a shared piece of every shorter length, so a yes at L is a yes below it, and a no at L is a no above it. The tests go 4 yes, 6 no, 5 no. At 4, acga has fingerprint 9 in both strands and the letters agree. At 6 the fingerprints are 4, 2, 8 against 7, 3, 5, and none agree. Length 5 was settled in part 1. The answer is 4, the piece acga, after three tests.
  3. At length 5 the false alarm would count as a yes. lo would move to 5, and the search would report a piece of five letters that does not exist. The sentence “at least lo” stopped being true the moment an unchecked match moved lo. In the joined text, two neighboring rows can both start in the same strand. Their shared opening is then a repeat inside one strand, and says nothing about the other. Only neighbors whose suffixes start in different strands count, and the largest of their entries is the answer. Here that is the 4 between acgag (from the second strand) and acgatt#... (from the first). The # stops a shared opening from running across the join.

Transfer 2 · middling · ~30 min

Did the AI sort the suffixes? You ask an AI for the suffix array of panama$, and it hands back 6 5 1 3 4 2 0. You could sort the suffixes yourself and compare, but sorting is the expensive part. Here is a check that reads each pair of neighboring rows once, with $ before every letter. When row r holds position i and row r + 1 holds position j, the letter at i must not come after the letter at j. When the two letters are the same, the suffix that starts at i + 1 must sit in an earlier row than the suffix that starts at j + 1.

  1. Run the check on the AI’s array. Which pair of rows fails, and what is wrong with them?
  2. Why is the check enough? If every neighboring pair passes, why is every suffix in its right row? Think of the pair of numbers a doubling round gives each position.
  3. What does the check cost, against building the array by doubling? The check asks in which row a suffix sits. What must you also check before that question makes sense, and which half of the contracts chapter’s check of a sort is it?
  1. Rows 2 and 3, which hold anama$ and then ama$. Both start with a, so the check looks at the suffixes one letter on, nama$ (position 2) and ma$ (position 4). In the AI’s array they sit in rows 5 and 4. So nama$ comes after ma$, and anama$ belongs after ama$. The two rows are swapped. The right array is 6 5 3 1 4 2 0. Every other pair passes.
  2. A suffix is its first letter followed by the suffix one place on. That is the pair that a doubling round uses, with one letter for the first tag and a row for the second. Work up from the shortest suffix to the longest. $ is shortest and comes first by its letter. Along the rows the first letters never go down, so any two suffixes that start with different letters are in the right order. Two suffixes with the same first letter have that letter in every row between them, so the passing neighbors put the suffixes one letter on in rising rows. Those are shorter, and the shorter suffixes are already known to be in the right order among themselves, so the pair is in the right order too. Of all 5,040 orders of the seven positions, only 6 5 3 1 4 2 0 passes.
  3. Six neighbor checks for seven rows, n - 1 in all, plus one pass to write down the row of each position. That cost grows like n, against up to about n \log_2 n steps for doubling. The row of a suffix makes sense only if every position from 0 to 6 appears exactly once, which takes one more pass with a tally. That is the half that checks the output is a rearrangement of the input. The neighbor rule is the half that checks it is in order. And the check comes from somewhere other than the AI that built the array.

Transfer 3 · middling · ~20 min

Which part keeps it right? Rabin–Karp is fingerprinting, plus a random prime, plus a check of every candidate. Change one part at a time.

  1. Keep the check, but use one fixed prime that anyone can look up.
  2. Keep the random prime, but report every window whose number equals the pattern’s number, without checking its letters.

For each, say whether the promise, every occurrence and nothing else, still holds, and what happens to the time. Then say which part each half of the promise comes from, and which part only buys speed.

  1. The promise holds, because every candidate is still checked letter by letter (invariant 3). But someone who knows the prime can write a text in which many windows get the pattern’s number. Each one costs a full check, and the search slows to about n \times m steps. It is slower, never wrong.
  2. The search stays fast, about n + m steps. Every occurrence is still found, because equal windows get equal numbers (invariant 1). But a window that only shares the number is reported too, so “nothing else” breaks. With a random prime that happens rarely, but it can happen.

“Every occurrence” comes from the fingerprints: equal windows get equal numbers, and the number kept is always the current window’s number (invariants 1 and 2). “Nothing else” comes from the check. The random prime only buys speed: it keeps false candidates few, so the check is rarely wasted.

Here are forty exercises. Each shows roughly how long it takes, and everything you need for them is in the chapter so far or in its appendix Why the fast versions are right. You can mark much of it by running the library on the same input: an array, a column, a count, the positions found or the quote returned. The steps on the way, such as each window’s fingerprint or a count of comparisons, you check by hand against the chapter. The answers are on a page of their own.

If you only do four, do Exercises 4, 10, 19 and 24.

They are grouped by kind of task, not by structure. To practice one structure, here are the exercises for each section:

  • Reading the whole book, every time: 1, 2, 20, 21, 22, 26, 27
  • I remember how it starts: 3, 4, 19, 23, 28, 37, 38, 40
  • It was somewhere in the middle: 5, 6, 7, 15, 16, 18, 24, 29, 30, 31
  • Useful mess?: 8, 9, 17
  • By heart: 10, 32, 33
  • Give me the whole line: 11, 12, 13, 14, 25, 34, 35, 36, 39

One uses the chapter’s appendix: Exercise 6 needs its part on Kasai’s method.

3.13.1 Run it and report the state

Exercise 1 · gentle · ~5 min

Slide the pattern aab along the text aabaacaabaab by hand, comparing character by character and moving on at the first mismatch. Where does it occur, and how many character comparisons did the whole scan make?

Exercise 2 · middling · ~15 min

The text is the digits 6404137153929 and the pattern is 153, base 10, modulus 13. Write down the fingerprint of every window of three digits, rolling each from the one before. At which positions do the fingerprints agree with the pattern’s fingerprint, and which of those are false alarms?

Exercise 3 · gentle · ~10 min

Insert tea, ten, to, inn, in, tent into an empty trie, in that order. How many nodes does it have, root included? How many does it have after squeezing it into a Patricia tree? What does keys_with_prefix("te") return, in order?

Exercise 4 · middling · ~15 min

Insert romane, romanus, romulus, rubens, ruber into an empty Patricia tree and draw it, every branch labelled. Then insert rubicon. Which branch is cut, and where? How many nodes does the tree have before and after?

Exercise 5 · gentle · ~15 min

Write the suffix array of abracadabra$, with $ sorting before every letter. Which rows hold the suffixes that begin with abra, and which text positions are they?

Exercise 6 · middling · ~20 min

From the suffix array of abracadabra$ (the previous exercise), write its LCP array. What is the longest passage that occurs twice, and which entry tells you? Then fill it in Kasai’s way: visit the positions in text order, 0 to 11, carrying h. For each position, what does h start at, and what does it record?

Exercise 7 · middling · ~20 min

Sort the suffixes of aababa$ by prefix doubling. Give the tag of every position after each round, with tags starting at 1 and $ tagged lowest, until every tag is different. How many doubling rounds did it take, not counting round 0, the tagging by single letters?

Exercise 8 · gentle · ~15 min

Write the Burrows–Wheeler transform of abracadabra$: sort its rotations and read the last column. Where are the runs of equal letters?

Exercise 9 · middling · ~15 min

A last column reads omotta$. Recover the text with the LF walk: sort the column to get F, number equal letters, start from the row whose last letter is $, and follow LF. Give the LF value of every row, and the text.

Exercise 10 · middling · ~15 min

Using only the last column of abracadabra$ (Exercise 8) and its table C, run backward search for bra. Give the interval of rows after each letter, and the count.

Exercise 11 · gentle · ~10 min

For the bits 0110100111000101 (position 0 first), what are rank(5), rank(11) and rank(16), the number of 1s before each position, and select(0), select(4) and select(7), counting the 1s from zero?

Exercise 12 · middling · ~20 min

The FM-index of abracadabra$ keeps a sample at every 4th text position (0, 4 and 8). Find every row whose suffix begins with a, and turn each into its text position by walking LF to a sampled row. How many steps does the longest walk take?

Exercise 13 · middling · ~15 min

The FM-index of abracadabra$ keeps the row of every 4th text position (0, 4 and 8). Extract the 3 letters starting at position 5, then the 2 letters starting at position 9. For each: which row do you start from, how many LF steps do you walk, and what comes out?

Exercise 14 · gentle · ~10 min

Three quotes are joined into one text with a separator between them: frankly my dear, here is looking at you, may the force be with you. The fragment looking is found at one position. Which position, which quote does it fall in, numbered from 0, and which bounds do the two selects give? Then: which quotes does a search for you return?

3.13.2 Which promise broke

Each item hands you something that a program produced and claims is correct. Say whether it is, and if it is not, name the invariant it breaks and the smallest change that would mend it. One of them is correct, and saying so is the answer.

Exercise 15 · middling · ~10 min

The suffix array of cocoa$ is 5 4 0 2 3 1.

Exercise 16 · middling · ~10 min

The suffix array of pepper$ is 6 1 4 0 3 2 5.

Exercise 17 · middling · ~10 min

A last column reads ap$p$le, and is said to be the transform of some text.

Exercise 18 · middling · ~10 min

The LCP array of cocoa$ is 0 0 0 3 0 1.

Exercise 19 · middling · ~10 min

A Patricia tree holds cart and card. Below the root it has a branch labelled ca to a node that holds no word, from there a branch r to a node that holds no word, and from there two branches, t and d, each ending a word.

Exercise 20 · middling · ~10 min

A fingerprint search for 15 in the digits 31415926, base 10, modulus 7, reports the positions [3, 5].

3.13.3 You supply the input

Exercise 21 · middling · ~15 min

Find a text of 10 letters and a pattern of 4 letters, both over the letters a and b, that make the plain scan do as many character comparisons as it possibly can. How many is that?

Then: Say what every text and pattern that reach the maximum have in common.

Exercise 22 · gentle · ~10 min

With base 10 and modulus 13, find two different three-digit windows that have the same fingerprint.

Then: Say the rule that decides, for any two numbers, whether they get the same fingerprint.

Exercise 23 · gentle · ~10 min

Choose five words of four letters each so that the trie holding them has as many nodes as possible. How many is that, and how many nodes does the Patricia tree of the same words have?

Then: What does that say about when squeezing pays most?

Exercise 24 · middling · ~15 min

Choose a text of 8 letters over a and b, with $ added at the end, that makes prefix doubling run as many rounds as possible. How many doubling rounds does it take, not counting round 0, the tagging by single letters?

Then: Say which property of the text decides the number of rounds.

Exercise 25 · middling · ~10 min

A quote finder joins its quotes with a reserved separator, written | here, and refuses any quote that holds it. It does not check the fragment for which it is asked. With the quotes you had me at hello and show me the money, write a fragment that this finder reports as found, though neither quote contains it.

Then: Say why keeping the separator out of the quotes is not enough on its own.

3.13.4 Which idea do you reach for

Each of these nine exercises describes a situation, most of them far from quotes, and asks which of the ideas above, the eight primitives or rank and select, you would use. Each has four options: pick the one for which you would reach first.

Exercise 26 · gentle · ~5 min

A multiplayer game must check, sixty times a second, that every player’s copy of the game world is still the same as the server’s copy. Sending the whole world each time is far too slow, and a very small chance of missing a difference is acceptable.

  1. fingerprinting
  2. divide and conquer
  3. sample, then walk
  4. work in blocks

Exercise 27 · middling · ~5 min

A public web service checks whether a pasted paragraph appears in its archive using a rolling fingerprint with a fixed, published modulus. An attacker sends texts that make every window match, and the service slows to a crawl.

  1. carry what you know
  2. randomization
  3. rank and select
  4. canonical form

Exercise 28 · middling · ~10 min

A phone keyboard suggests words while you type. The team wants the stored dictionary compact, and still to be correct after words are added and removed every day.

  1. doubling
  2. canonical form
  3. fingerprinting
  4. sample, then walk

Exercise 29 · middling · ~10 min

You must sort the positions of every line break in a ten-gigabyte log by what follows them, and many lines repeat long stretches word for word, so comparing strings directly keeps re-reading the same letters.

  1. doubling
  2. randomization
  3. work in blocks
  4. rank and select

Exercise 30 · gentle · ~5 min

A sorted list of every street name in a country is printed in a thick book, with no index. You need the page where names starting with Mill begin.

  1. carry what you know
  2. sample, then walk
  3. divide and conquer
  4. fingerprinting

Exercise 31 · hard · ~15 min

The suffixes of a long text are sorted, one to a row. For every row you need how many opening letters its suffix shares with the suffix in the row above, and computing each one from scratch is far too slow.

  1. carry what you know
  2. work in blocks
  3. randomization
  4. canonical form

Exercise 32 · middling · ~10 min

A map app stores, for a billion road segments, one bit saying whether each is a toll road. It must answer how many toll segments come before segment i instantly, and may use only a little more memory than the bits.

  1. fingerprinting
  2. rank and select
  3. divide and conquer
  4. doubling

Exercise 33 · middling · ~10 min

Storing a running count after every bit of that billion would cost far more than the bits; counting from the start on every question is far too slow. Each question may read only two stored counts and one machine word of bits.

  1. sample, then walk
  2. work in blocks
  3. randomization
  4. carry what you know

Exercise 34 · middling · ~10 min

A bank numbers every transaction on an account since it was opened, ten years of them, and must quickly show the balance after any numbered transaction, without storing a balance after every transaction.

  1. divide and conquer
  2. canonical form
  3. sample, then walk
  4. rank and select

3.13.5 The tests pass. What did they miss?

Code that fails its tests is easy to catch. The costly kind passes every test, because nobody wrote a test for the requirement it breaks.

Exercise 35 · middling · ~15 min

A team ships a quote finder built on an FM-index. Its tests pass: for a thousand random fragments, count agrees with a plain scan of the books, and locate returns exactly the positions that the scan finds. In production, people type quotes with straight apostrophes copied from a chat, and the finder says they appear nowhere. What requirement did the tests miss?

Then: Write the requirement as a sentence that a test could check.

Exercise 36 · hard · ~20 min

An index over song lyrics returns whole songs for a fragment, joining the songs with a reserved separator and finding where each song starts by looking for that byte. Its tests pass: every fragment cut from inside one song returns that song and every other song containing it, and a fragment that occurs nowhere returns nothing. After launch, a lyric site adds one song containing the separator byte inside a line, and from then on some searches return songs that do not contain the fragment. What requirement did the tests miss?

Then: Say where the checks belong, and what each must do.

3.13.6 Fix the code, the box, or the design?

Each item starts from code that an AI wrote from one of the chapter’s design boxes, and something it did that looks wrong. Decide which of three things happened. The code breaks a promise in the box: fix the code. The code keeps the box but misses what you wanted: fix the box. The design keeps its promise, but its assumptions or its cost no longer fit the job: change the design. Say why.

Exercise 37 · middling · ~10 min

You give an AI the trie’s design box and ask for the code. Its remove walks to the word and clears the mark that says a word ends there, and does nothing else. Insert tea and ten into an empty trie, then remove both. get finds neither word, keys() returns nothing, and the count of words is 0. The trie still has 5 nodes. Which of the three is it, and why?

Then: Suppose the box had stopped at invariant 2 and said nothing about memory. Which would it be then? Write the line you would add to the box, and a test you would keep from the AI that checks it.

Exercise 38 · middling · ~10 min

The same AI’s trie, its remove now mended, holds 2,000 web addresses of a shop, such as https://shop.example.com/products/aaliwuqonsmb/reviews, about 54 letters each. Nothing has been removed, every check of the box’s invariants passes, and every lookup is right. Yet the trie has 36,601 nodes, about 18 per address, and a colleague says the leak is back. Which of the three is it, and why?

Then: Name the design you would switch to, and say what you would measure to check it.

Exercise 39 · middling · ~10 min

An AI builds the FM-index from its design boxes for a reading app. Asked where i occurs in mississippi$, locate returns [10, 7, 4, 1]; asked for ssi, it returns [5, 2]. The app jumps to the first position in the list, so a search for i takes the reader to position 10, the last i in the text. Which of the three is it, and why?

Then: Rewrite the line of the box that has to change, say what the change costs, and name a test you would keep from the AI.

3.13.7 Taking a word out of a squeezed tree

Exercise 40 · hardest in the chapter · ~90 min

You already have:

  • the Patricia tree’s insert, printed in the chapter
  • its invariant: every node below the root branches or ends a word
  • the chapter’s one-paragraph description of removal

Write remove(key) for the Patricia tree, as code or as precise steps, so that the invariant holds again after every removal. Your answer must say what happens to a node left with no word and no children, to one left with a single child and no word, and why the root is treated differently from every other node.

Three checks tell you whether you got it right, on the words romane, romanus, romulus, rubens, ruber, rubicon, rubicundus, removing romulus, then rubicon, then rubicundus:

  • After every removal, no node below the root has exactly one child and no word.
  • The tree after removing a word has exactly as many nodes as a tree built from scratch from the words that remain.
  • Removing a word that is not stored changes nothing.

Stretch: The second check says a squeezed tree depends only on its set of words, not on the order in which they arrived or were removed. Prove it.

NoteCome back in a week

Put this somewhere you’ll see it in about a week, and when you do, answer from memory first, with no scrolling back and no AI. Getting it wrong and then looking is the point.

  1. Name the structures in this chapter in order, and for each, name the thing about Leo’s question it could not handle, which forced the next one.

  2. Why does a fingerprint match have to be checked against the actual characters, and what does the check cost when the fingerprints almost never agree by accident?

  3. What invariant does a Patricia tree keep about every node below its root, and why does it keep the tree small?

  4. Write the suffix array of abab$ by hand, and find ab in it.

  5. The transform of a text is exactly as long as the text. So where does the FM-index’s saving come from?

  6. A colleague’s FM-index answers every count correctly, but locate takes a full second per occurrence on a large corpus. What did they most likely set, and what does changing it cost?

  7. Pick one of the chapter’s design boxes and write it from memory. Say what it promises, its idea and invariants, and on what its cost depends. If it assumes anything, say what you would see if that assumption broke. Then open the box and compare.

Whichever of those you couldn’t reconstruct is the one to reread, and only that one. If you got all seven, come back again in a month instead.

3.14 ★ Frontier map advanced

What follows is an optional short tour of ideas just past the edge of this chapter. Skip it now if you’d rather move on, and come back later.

One thread runs through all of it. This chapter took a text as a fixed row of bytes, asked for exact matches, and built an index once. Almost every piece of current research changes one of those choices: what the pieces of a text are, whether it is one line at all, what counts as a match, or whether the text stays still. The rest asks what impossible really means. Each entry below takes up one of these choices or limits. Most end with a question you can now ask of other systems.

3.14.1 Did the AI copy this?

Exact indexes over training data

Language models are trained on trillions of words of text. They sometimes give some of it back word for word. Finding out when that happens is exactly Leo’s problem, at a scale that no scan can touch. Given a paragraph that the model wrote, does it occur in the training text, and where?

The field reaches for the structures of this chapter. A 2022 study built a suffix array over a large training corpus and found that one 61-word sentence occurred more than 60,000 times in it. Removing such repeats before training cut how often the model reproduced its training text word for word to about a tenth [30]. A suffix array over five trillion tokens now counts any phrase in milliseconds [20]. In 2025 came an FM-index over 83 terabytes of web text, built on raw bytes and smaller than the text [27]. The FM-index’s builders use it to find benchmark questions that leaked into training text. A related tool traces a chatbot’s answer back to the exact training documents it echoes, in seconds [31]. That last one is this chapter’s from a hit to the whole quote, in a public tool, in 2025.

The FM-index among them makes the choice that this chapter made about the apostrophe. It indexes bytes, not the model’s own pieces of words, so the index still works when the model, or the way it cuts text into pieces, changes.

The question to ask: an AI says its answer is original. What would you index, at what unit, and what would your check still miss: a paraphrase, a translation, a quote with one word changed?

3.14.2 A thousand copies of almost the same book

Repetitive collections and dynamic indexes

Every version of Wikipedia. Every release of a code base. The genomes of ten thousand people, each differing from the others in about one letter in a thousand. These collections are enormous, and almost all repetition. An FM-index measures its size against the text’s length, and that is the wrong measure here. Ten thousand near-copies are not ten thousand times harder to index than one.

The transform already points to the fix. Near-copies make the last column fall into long runs of equal letters, and the number of runs measures what is really there. A 2020 result showed how closely that count of runs tracks other measures of repetition [32]. The r-index answers count and locate in space proportional to the number of runs [33]. Choosing which measure of repetition is the right one is a question of compression, and the compression chapter takes it up.

This chapter also assumed that the text never changes, and that assumption is falling too. Since 2022 a suffix array can be kept up to date through insertions and deletions, each in time that grows only like a power of \log n, without a rebuild [34]. In 2026 a compressed index for repetitive text beat earlier updatable ones by up to 77 times on updates and up to 11 times on locating, across eleven repetitive collections that include 37 GB of Wikipedia and 59 GB of human chromosomes [35]. Updatable indexes still trade something away. When changes arrive in large batches, rebuilding from time to time can still be the better engineering.

The question to ask: your corpus is every version of one document. What should size mean for its index, and what does an update cost?

3.14.3 Placing a million reads

Minimizers

A DNA sequencer produces hundreds of millions of short reads, and each one has to be placed on a genome. Many current read mappers, especially for long reads, start with fingerprints. In every short stretch of a read they keep only the window whose fingerprint is smallest, its minimizer [36]. Two sequences that share a long enough stretch are guaranteed to keep the same minimizer inside it, so a handful of kept windows is enough to propose where a read belongs. A careful alignment then checks the proposal [37]. This is the bargain from the start of this chapter again, a cheap fingerprint to guess and a real comparison to confirm.

The question to ask: which windows does your method keep, and what does it miss when two sequences share no kept window?

3.14.4 When there is no single text

Wheeler graphs

From about 2009, the FM-index’s best-known job was searching a human genome, a reference sequence of about three billion letters. A sequencer’s hundreds of millions of short reads are placed against it. Many of them start from exact matches that backward search finds and are then aligned in a way that allows differences. But no person’s genome is the reference. Everyone differs from it in millions of places, and a read from a part where you differ may align badly, or in the wrong place. So in 2023 a consortium published a first pangenome reference, built from the genomes of 47 people [38]. It is not one string. Where those people agree, it is a single path of letters. Where they differ, it splits into alternatives and joins again. It is a graph.

Look again at why backward search worked. Every row was a position in the text, and the rows were sorted so that two things held. Rows were grouped by the letter that leads into them, a grouping on which C relied. And among rows that end in the same letter, LF kept their order. If row u came before row u', then \text{LF}(u) came before \text{LF}(u'). It is the same rule, a_k in L is a_k in F. A text is a single path, and that path is what guaranteed such an order exists.

So ask for exactly that order on a graph. Take a graph whose edges carry letters, and put its nodes in one line so that:

  • nodes with no edge coming in come first, and the rest are grouped by the letter on the edges coming into them, in alphabetical order;
  • for two edges carrying the same letter, from u to v and from u' to v', if u comes before u', then v comes no later than v'.

A graph that has such an order is a Wheeler graph [39]. On a Wheeler graph, backward search runs much as it does on a text, with a stretch of nodes narrowed one letter at a time by counting.

Two small graphs of variants. On the left, a path that splits into cat and cut and joins again: the numbers give an order with both properties, so backward search works on it. On the right, two a-edges leave each of p and q and cross. p must come before q, so everything that p’s a-edges reach must come no later than everything that q’s a-edges reach, and each reaches both r1 and r2. No order can satisfy that.
Figure 3.25: Two small graphs of variants. On the left, a path that splits into cat and cut and joins again: the numbers give an order with both properties, so backward search works on it. On the right, two a-edges leave each of p and q and cross. p must come before q, so everything that p’s a-edges reach must come no later than everything that q’s a-edges reach, and each reaches both r1 and r2. No order can satisfy that.

Not every graph has such an order, and the right-hand graph above shows why. The trouble is equal letters that cross, two a-edges whose starting points come in one order and whose ending points are forced into the other.

And here the field meets a wall. Deciding whether a graph has a Wheeler order at all is NP-complete as soon as its edges carry two different letters. With one letter it is quick [40]. The exact method in the same paper takes time that grows exponentially with the number of edges. Worse, for general graphs a fast search may be out of reach. Exact pattern matching in a graph cannot be done much faster than the size of the graph times the length of the pattern, unless a widely believed conjecture about the limits of computation, the Orthogonal Vectors conjecture, is false [41]. That conjecture says that among n short lists of 0s and 1s, finding two lists that never have a 1 in the same position cannot be done much faster than checking every pair. A single line of text gets an index that answers in steps proportional to the pattern. A graph, in general, does not get one [42].

Genome researchers live with that now. They build graphs that are close enough to Wheeler graphs to search, and accept the cost where the graphs are not close enough. The single line of text was more of a gift than it looked.

The question to ask: a tool says it searches a graph as fast as a text. Does its graph have a Wheeler order, and what does the tool do where the graph does not have one?

3.14.5 How sure is “impossible”?

Lower bounds for string problems

This chapter has met impossible more than once, and it did not always mean the same thing.

The entry on Wheeler graphs above met a conditional wall. Exact matching in a general graph can’t be much faster than the graph’s size times the pattern’s length, unless the Orthogonal Vectors conjecture fails [41]. The same conjecture sets the wall for edit distance, the minimum number of single-letter insertions, deletions or substitutions needed to turn one string into another. Edit distance is the measure behind many spell checkers’ suggestions. No method computes it exactly in much less than the product of the two lengths unless that conjecture is false [43]. The door in that wall is approximation. Since 2020, edit distance can be estimated to within a constant factor in nearly linear time [44]. The standard algorithm for computing it exactly uses dynamic programming, like its cousins that line up DNA and protein sequences: Needleman–Wunsch for whole sequences [45] and Smith–Waterman for their best-matching pieces [46]. All of that lies beyond this chapter.

An unconditional wall needs no hypothesis at all, only a model of the machine. In 2026 two papers by Dominik Kempa and Tomasz Kociumaka settled how fast a compressed suffix array can answer which position is in row i? For indexes compressed as far as a text’s repetition allows, that question and the LCP question need time that grows like \log n / \log\log n, while the transform’s own questions need only \log\log n [47]. The second paper, still a preprint, answers a question open since 2000. For a text of 0s and 1s, no suffix array that fits in a number of bits proportional to the text’s length answers in constant time [48]. That is a precise version of something this chapter measured by hand. Locate is the expensive question, and no cleverness removes all of its cost.

The question to ask: someone says it can’t be done faster. In which model of the machine, under which hypothesis, and what would change if you changed either?

3.14.6 How a language model reads

Tokenization

A language model does not read letters or bytes. Before a sentence reaches the model, a tokenizer cuts it into pieces from a fixed vocabulary of tens or hundreds of thousands of fragments, and the model only ever sees the pieces. Where the cuts fall matters. This is why models have stumbled at counting the letters in a word, and why the same sentence costs different amounts in different languages.

Choosing the pieces is a hard problem in its own right. Finding the vocabulary of a given size that cuts a text into the fewest pieces is NP-complete [49]. The standard greedy method, which the compression chapter builds, merges the commonest pair of neighboring pieces again and again. With the same number of merges, it provably saves at least a constant fraction of what the best possible merges save [50]. Since 2024, some models drop the fixed vocabulary altogether, reading raw bytes and grouping them into pieces as they go. One cuts where the next byte is hard to predict [51], and another learns where to cut as part of training [52]. The frontier still reads in pieces, and is learning where the pieces should go.

The question to ask: who decided where a word ends in this system, and what does it fail at because of that decision?

3.14.7 The search that takes a site down

Regular expressions: speed and proof

This chapter searched for fixed fragments. Code editors and programming tools accept patterns, regular expressions such as colou?r or [0-9]+. Most programming languages match them by trying one way, backing up when it fails, and trying another. On an unlucky pattern and text, that backing up explodes. In July 2019 one such pattern exhausted the processors of Cloudflare’s network for about half an hour [53].

The fix, known for decades, is to match with an automaton that never backs up, in time proportional to the text [54]. Since 2021 it has been moving into the mainstream engines that used to back up. In 2024 researchers showed that nearly all of JavaScript’s regular expressions, including features that look ahead and behind, can be matched in linear time [55]. In exchange, some features, such as matching a group that was captured earlier, can’t keep that guarantee and have to be given up. Speed is the first change, and proof is the second. There are now matchers whose correctness against a formal definition of the language is checked by a proof assistant [56]. The limit is the same as in the search chapter’s proofs. The proof holds relative to the formal definition, not to what the person writing the pattern meant.

The question to ask: which features would you give up for a guarantee on time, and what does a proof of correctness still not promise?

3.14.8 Text that hides text

Invisible characters as an attack

What is a character, actually? mattered for apostrophes. It matters much more when someone chooses the characters on purpose. Unicode includes invisible characters, and characters that reverse the direction in which text is displayed. In 2021, researchers showed that these let source code look one way to the person reviewing it and compile another way, an attack they called Trojan Source [57]. The same tricks fool language-processing systems that read the bytes rather than the screen [58]. A reviewer reads the display. The compiler, the search index and the model read the bytes. Every check in this chapter compared bytes, so every one of them would find the hidden text, if only someone thought to search for it. Even counting letters depends on who counts. A flag or a family emoji is a short run of characters that the screen draws as one symbol.

Text can also carry a signal hidden in which words were chosen, a watermark or a secret message, which no byte search can see at all. Detecting it is a matter of statistics and hashing, and lies beyond this chapter.

The question to ask: a text passes every check you can run. What could it still be carrying, and which layer, display or bytes, is your check actually reading?

3.14.9 The model that searches its own past

Suffix structures in language model decoding

A language model writes one piece of text at a time. Each piece costs a full pass through a very large network. But in many tasks the model repeats itself, as when an agent calls the same tools or a program is edited line by line. SuffixDecoding keeps a suffix tree over what the model has written before. When the last few pieces match something seen earlier, it guesses the continuation from the tree. The model then checks the whole guess in one pass, keeping what agrees and discarding the rest. On agent workloads it made generation up to 5.3 times faster [59].

It is the Rabin–Karp bargain from the start of the chapter in another form: a cheap guess, an expensive check, and a guarantee that the check makes the answer exact.

The question to ask: when is a cheap guess plus an expensive check faster than the expensive thing alone?

3.14.10 Finding what it means, not what it says

Semantic search, in one paragraph

Leo wanted the exact words. Much of today’s search wants the meaning, the passage about loneliness at sea, whatever words it uses. That is done by turning passages into lists of numbers and finding the nearest lists, which is a geometry question. The chapter on geometry and the search chapter’s frontier take it up. The two kinds of search answer different questions. For a quotation, a citation or a check that a model copied its training text, only an exact match is evidence. A passage that means the same is not a quote.

3.14.11 Could the machine choose the pieces?

Where this may be going

Models are learning where text should be cut. Exact indexes sit beside models to check from where their words came. One model in 2026 builds a lookup table of word sequences into the model itself [60]. Repetition is becoming the measure of a collection’s size, and indexes are learning to change without being rebuilt. In each case, a choice that this chapter made by hand is being handed to something else, sometimes to a learned model: what a piece is, what a match is, what stays fixed.

The question that lasts is the one to put to whatever makes that choice for you, what would it have to show you before you believed it? The assumption it made about your text, what would break that assumption, and what happens to the answers when it breaks. A chooser that tells you those three things is one you can check. One that hands you an index and a confidence score has told you nothing you can check, however good the index is.

3.15 ★ Appendix: why the fast versions are right advanced

This appendix is part of the chapter, and some exercises use it. It proves the two facts that make the fast constructions right, and shows how a doubling round sorts its pairs. The code for each of them, with its tests, is in the companion library, in its strings folder.

3.15.1 Why two old tags are enough

Prefix doubling, from Sorting by doubling, works in rounds. In the round where the tags cover w letters, each position i gets the pair (tag of i, tag of i + w), with 0 in place of the second tag when i + w is past the end. The pairs are sorted, and the new tags step up only where the pair changes.

Each round needs the pairs in order of their second tag first, and that order costs no sort. The order from the round before already lists the suffixes by tag. Step back w from each one, and the suffixes come out in order of their second tag. In front of them go the few whose second half runs past the end, with tag 0. Then one pass of counting sort orders the pairs by their first tag. Counting sort keeps equal keys in the order they arrived, so the pairs come out sorted by first tag, then second.

The invariant to keep true is that whenever the tags cover w letters, they order the suffixes by their first w letters. Two positions get equal tags exactly when their first w letters agree, and one gets the lower tag exactly when its first w letters sort first.

It is true for w = 1, because the first tags are given by the letters themselves.

Suppose it is true for w. Compare two suffixes by their first 2w letters. Sorted order compares the first w letters first, and only if those tie, it compares the next w. The first w letters of the suffix at i are ordered by the tag of i. The next w are the first w letters of the suffix at i + w, ordered by the tag of i + w, or by 0 if that suffix is empty. That 0 is right, because a suffix that has ended sorts first. So sorting by the pair, first number first, is exactly sorting by the first 2w letters, and handing out tags that step up only where the pair changes keeps equal prefixes equal. The invariant holds for 2w.

The doubling can stop when every tag is different. From then on the order can’t change, because the pairs only ever break ties. Or it can stop when w reaches the text’s length, since no suffix has more letters than that to compare.

3.15.2 Why the count drops by at most one

Kasai’s method, from Neighbors that agree, visits the suffixes in text order, position 0 first, and carries a count h that starts at 0. At each position it compares the suffix with the one in the row above it in sorted order. It skips the first h letters, extends the match while the letters agree, and writes the new h into that row of the LCP array. The top row has no row above it, so there the method compares nothing and writes nothing. Either way, h then drops by one, never below 0, and the method moves on to the next position.

Why may it skip those h letters? If the suffix at position p shares h letters with its neighbor above, chop the first letter off both. What is left is the suffix at p + 1 and a suffix sorted above it, still sharing h - 1 letters. The neighbor directly above p + 1 sits between that suffix and p + 1 in sorted order. A row sorted between two suffixes shares at least what they share, so this neighbor shares at least h - 1 letters too. So the comparison for p + 1 can skip its first h - 1 letters, because they are known to agree.

That is also why the pass is fast. h never exceeds n and drops by at most one per position, so it can rise at most 2n times in all, and the pass takes time proportional to n.

3.16 ★ Appendix: the router’s question advanced

Longest-prefix match

The trie answered which stored words start like this? Turn the question around, and the trie answers another one, asked billions of times a second across the internet, which stored prefix is the longest one that this starts with?

Every packet carries a destination address, 32 bits for the older version of the internet protocol. A router does not know every address. It holds a table of prefixes, address beginnings, each with a direction to send packets whose addresses start that way. A prefix written 192.168.0.0/16 means the first 16 bits of 192.168.0.0, and it covers 65,536 addresses. Tables hold around a million such prefixes, a number that keeps growing. The prefixes overlap, with one route for a large block and a different route for a smaller block inside it. The rule is that the most specific match wins, the longest prefix with which the address starts.

That is a trie question. Store each prefix as a string of bits, one bit per branch, and walk down the address’s bits from the root, remembering the last marked node you passed. When the walk can go no further, the last mark is the answer. A Patricia tree does the same walk a whole branch label at a time:

Listing 3.15: Longest prefix match in a Patricia tree, Python.
def longest_prefix(self, key): node = self.root best = 0 if node.has_value else None consumed = 0 rest = key while rest: child = node.children.get(rest[0]) if (child is None or not rest.startswith(child.label)): break consumed += len(child.label) rest = rest[len(child.label):] node = child if node.has_value: best = consumed if best is None: return None return key[:best]
Start at the root, which may itself end a prefix.
Stop when no branch matches the rest of the address.
Step down, noting each stored prefix.walk down whole labels; the deepest marked node on the way is the longest stored prefixlast mark
The longest stored prefix, or none.

Take three prefixes, written as bits: 1100 for a large block, 110010 inside it, and 1110 elsewhere. In the Patricia tree they share the branch 11, so an address beginning 11001011 walks 11, then 00 (a mark: remember 1100), then 10 (a mark: remember 110010 instead), and then no branch starts with the next bit. The answer is 110010, the more specific of the two. An address beginning 11000111 walks 11, then 00, finds no branch for the 0 that comes next, and gets the large block. An address beginning 0 gets nothing at all, and a real router would send it along its default route.

Many real routers use the same idea with refinements: branches several bits wide at once, to take fewer steps, and tables laid out to fit in the fastest memory that a router has. The question underneath is the one from which this appendix started, and the structure answering it is the trie.

[1]
R. M. Karp and M. O. Rabin, “Efficient randomized pattern-matching algorithms,” IBM Journal of Research and Development, vol. 31, no. 2, pp. 249–260, 1987.
[2]
R. Motwani and P. Raghavan, Randomized algorithms. Cambridge University Press, 1995.
[3]
D. E. Knuth, J. H. Morris Jr., and V. R. Pratt, “Fast pattern matching in strings,” SIAM Journal on Computing, vol. 6, no. 2, pp. 323–350, 1977, doi: 10.1137/0206024.
[4]
A. V. Aho and M. J. Corasick, “Efficient string matching: An aid to bibliographic search,” Communications of the ACM, vol. 18, no. 6, pp. 333–340, 1975, doi: 10.1145/360825.360855.
[5]
M. Crochemore and D. Perrin, “Two-way string-matching,” Journal of the ACM, vol. 38, no. 3, pp. 650–674, 1991, doi: 10.1145/116825.116845.
[6]
R. S. Boyer and J. S. Moore, “A fast string searching algorithm,” Communications of the ACM, vol. 20, no. 10, pp. 762–772, 1977, doi: 10.1145/359842.359859.
[7]
R. N. Horspool, “Practical fast searching in strings,” Software: Practice and Experience, vol. 10, no. 6, pp. 501–506, 1980, doi: 10.1002/spe.4380100608.
[8]
T. Clem, “The technology behind GitHub’s new code search.” 2023.
[9]
E. Fredkin, “Trie memory,” Communications of the ACM, vol. 3, no. 9, pp. 490–499, 1960, doi: 10.1145/367390.367400.
[10]
D. R. Morrison, “PATRICIA—practical algorithm to retrieve information coded in alphanumeric,” Journal of the ACM (JACM), vol. 15, no. 4, pp. 514–534, 1968.
[11]
P. Weiner, “Linear pattern matching algorithms,” in 14th annual symposium on switching and automata theory (swat 1973), IEEE, 1973, pp. 1–11.
[12]
E. M. McCreight, “A space-economical suffix tree construction algorithm,” Journal of the ACM (JACM), vol. 23, no. 2, pp. 262–272, 1976.
[13]
E. Ukkonen, “On-line construction of suffix trees,” Algorithmica, vol. 14, no. 3, pp. 249–260, 1995.
[14]
U. Manber and G. Myers, “Suffix arrays: A new method for on-line string searches,” SIAM Journal on Computing, vol. 22, no. 5, pp. 935–948, 1993.
[15]
T. H. Cormen, C. E. Leiserson, R. L. Rivest, and C. Stein, Introduction to algorithms, 4th ed. Cambridge, MA: MIT Press, 2022.
[16]
J. Kärkkäinen and P. Sanders, “Simple linear work suffix array construction,” in International colloquium on automata, languages, and programming, Springer, 2003, pp. 943–955.
[17]
G. Nong, S. Zhang, and W. H. Chan, “Linear suffix array construction by almost pure induced-sorting,” in Data compression conference (DCC), IEEE, 2009, pp. 193–202.
[18]
T. Kasai, G. Lee, H. Arimura, S. Arikawa, and K. Park, “Linear-time longest-common-prefix computation in suffix arrays and its applications,” in Annual symposium on combinatorial pattern matching, Springer, 2001, pp. 181–192.
[19]
M. I. Abouelhoda, S. Kurtz, and E. Ohlebusch, “Replacing suffix trees with enhanced suffix arrays,” Journal of Discrete Algorithms, vol. 2, no. 1, pp. 53–86, 2004, doi: 10.1016/S1570-8667(03)00065-0.
[20]
J. Liu, S. Min, L. Zettlemoyer, Y. Choi, and H. Hajishirzi, “Infini-gram: Scaling unbounded n-gram language models to a trillion tokens,” in Conference on language modeling (COLM), 2024.
[21]
M. Burrows and D. J. Wheeler, “A block-sorting lossless data compression algorithm,” Digital Equipment Corporation, Systems Research Center, 124, 1994.
[22]
P. Ferragina and G. Manzini, “Opportunistic data structures with applications,” in Proceedings 41st annual symposium on foundations of computer science (FOCS), IEEE, 2000, pp. 390–398.
[23]
R. Grossi, A. Gupta, and J. S. Vitter, “High-order entropy-compressed text indexes,” in Proceedings of the fourteenth annual ACM-SIAM symposium on discrete algorithms (SODA), 2003, pp. 841–850.
[24]
G. Navarro, Compact data structures: A practical approach. Cambridge University Press, 2016. doi: 10.1017/CBO9781316588284.
[25]
R. Raman, V. Raman, and S. S. Rao, “Succinct indexable dictionaries with applications to encoding k-ary trees and multisets,” in Proceedings of the thirteenth annual ACM-SIAM symposium on discrete algorithms (SODA), 2002, pp. 233–242.
[26]
G. Jacobson, “Space-efficient static trees and graphs,” in 30th annual symposium on foundations of computer science (FOCS), IEEE, 1989, pp. 549–554.
[27]
H. Xu, J. Liu, H. Hajishirzi, N. A. Smith, Y. Choi, et al., “Infini-gram mini: Exact n-gram search at the internet scale with FM-index,” in Proceedings of the 2025 conference on empirical methods in natural language processing (EMNLP), 2025.
[28]
H. Li and R. Durbin, “Fast and accurate short read alignment with Burrows–Wheeler transform,” Bioinformatics, vol. 25, no. 14, pp. 1754–1760, 2009.
[29]
B. Langmead, C. Trapnell, M. Pop, and S. L. Salzberg, “Ultrafast and memory-efficient alignment of short DNA sequences to the human genome,” Genome Biology, vol. 10, no. 3, p. R25, 2009.
[30]
K. Lee et al., “Deduplicating training data makes language models better,” in Proceedings of the 60th annual meeting of the association for computational linguistics (ACL), 2022. doi: 10.18653/v1/2022.acl-long.577.
[31]
J. Liu, T. Blanton, Y. Elazar, S. Min, et al., “OLMoTrace: Tracing language model outputs back to trillions of training tokens,” in Proceedings of the 63rd annual meeting of the association for computational linguistics: System demonstrations (ACL), 2025.
[32]
D. Kempa and T. Kociumaka, “Resolution of the Burrows-Wheeler transform conjecture,” in 61st annual IEEE symposium on foundations of computer science (FOCS), 2020.
[33]
T. Gagie, G. Navarro, and N. Prezza, “Fully functional suffix trees and optimal text searching in BWT-runs bounded space,” Journal of the ACM, vol. 67, no. 1, 2020.
[34]
D. Kempa and T. Kociumaka, “Dynamic suffix array with polylogarithmic queries and updates,” in Proceedings of the 54th annual ACM symposium on theory of computing (STOC), 2022. doi: 10.1145/3519935.3520061.
[35]
T. Nishimoto and Y. Tabei, “Dynamic grammar-compressed self-index in delta-optimal space,” in 34th annual european symposium on algorithms (ESA), in LIPIcs. 2026. doi: 10.4230/LIPIcs.ESA.2026.6.
[36]
M. Roberts, W. Hayes, B. R. Hunt, S. M. Mount, and J. A. Yorke, “Reducing storage requirements for biological sequence comparison,” Bioinformatics, vol. 20, no. 18, pp. 3363–3369, 2004.
[37]
H. Li, “Minimap2: Pairwise alignment for nucleotide sequences,” Bioinformatics, vol. 34, no. 18, pp. 3094–3100, 2018.
[38]
W.-W. Liao, M. Asri, J. Ebler, et al., “A draft human pangenome reference,” Nature, vol. 617, pp. 312–324, 2023.
[39]
T. Gagie, G. Manzini, and J. Sirén, “Wheeler graphs: A framework for BWT-based data structures,” Theoretical Computer Science, vol. 698, pp. 67–78, 2017, doi: 10.1016/j.tcs.2017.06.016.
[40]
D. Gibney and S. V. Thankachan, “On the hardness and inapproximability of recognizing Wheeler graphs,” in 27th annual european symposium on algorithms (ESA), in LIPIcs. Schloss Dagstuhl, 2019.
[41]
M. Equi, V. Mäkinen, A. I. Tomescu, and R. Grossi, “On the complexity of string matching for graphs,” ACM Transactions on Algorithms, vol. 19, no. 3, pp. 1–25, 2023, doi: 10.1145/3588334.
[42]
M. Equi, V. Mäkinen, and A. I. Tomescu, “Graphs cannot be indexed in polynomial time for sub-quadratic time string matching, unless SETH fails,” Theoretical Computer Science, vol. 975, p. 114128, 2023, doi: 10.1016/j.tcs.2023.114128.
[43]
A. Backurs and P. Indyk, “Edit distance cannot be computed in strongly subquadratic time (unless SETH is false),” in Proceedings of the 47th annual ACM symposium on theory of computing (STOC), 2015, pp. 51–58.
[44]
A. Andoni and N. S. Nosatzki, “Edit distance in near-linear time: It’s a constant factor,” in IEEE 61st annual symposium on foundations of computer science (FOCS), IEEE, 2020.
[45]
S. B. Needleman and C. D. Wunsch, “A general method applicable to the search for similarities in the amino acid sequence of two proteins,” Journal of Molecular Biology, vol. 48, no. 3, pp. 443–453, 1970, doi: 10.1016/0022-2836(70)90057-4.
[46]
T. F. Smith and M. S. Waterman, “Identification of common molecular subsequences,” Journal of Molecular Biology, vol. 147, no. 1, pp. 195–197, 1981, doi: 10.1016/0022-2836(81)90087-5.
[47]
D. Kempa and T. Kociumaka, “Tight lower bounds for central string queries in compressed space,” in Proceedings of the 2026 annual ACM-SIAM symposium on discrete algorithms (SODA), 2026.
[48]
D. Kempa and T. Kociumaka, “Cell-probe lower bounds and complexity-preserving reductions for suffix array queries.” 2026.
[49]
P. Whittington, G. Bachmann, and T. Pimentel, “Tokenisation is NP-complete,” in Proceedings of the 63rd annual meeting of the association for computational linguistics (ACL), 2025.
[50]
L. Kozma and J. Voderholzer, “Theoretical analysis of byte-pair encoding,” in 34th annual european symposium on algorithms (ESA), in LIPIcs. 2026. doi: 10.4230/LIPIcs.ESA.2026.80.
[51]
A. Pagnoni et al., “Byte latent transformer: Patches scale better than tokens,” in Proceedings of the 63rd annual meeting of the association for computational linguistics (ACL), 2025.
[52]
S. Hwang, B. Wang, and A. Gu, “Dynamic chunking for end-to-end hierarchical sequence modeling,” in International conference on learning representations (ICLR), 2026.
[53]
J. Graham-Cumming, “Details of the Cloudflare outage on July 2, 2019.” 2019.
[54]
R. Cox, “Regular expression matching can be simple and fast.” 2007.
[55]
A. Barrière and C. Pit-Claudel, “Linear matching of JavaScript regular expressions,” in Proceedings of the ACM on programming languages (PLDI), 2024.
[56]
A. Chattopadhyay, A. W. Li, and K. Mamouras, “Verified and efficient matching of regular expressions with lookaround,” in Proceedings of the 14th ACM SIGPLAN international conference on certified programs and proofs (CPP), 2025.
[57]
N. Boucher and R. Anderson, “Trojan source: Invisible vulnerabilities,” in 32nd USENIX security symposium, 2023.
[58]
N. Boucher, I. Shumailov, R. Anderson, and N. Papernot, “Bad characters: Imperceptible NLP attacks,” in IEEE symposium on security and privacy (s&p), 2022.
[59]
G. Oliaro, Z. Jia, D. Campos, and A. Qiao, “SuffixDecoding: Extreme speculative decoding for emerging AI applications,” in Advances in neural information processing systems (NeurIPS), 2025.
[60]
X. Cheng et al., “Conditional memory via scalable lookup: A new axis of sparsity for large language models,” in Proceedings of the 64th annual meeting of the association for computational linguistics (volume 1: Long papers), 2026, pp. 4968–4990. doi: 10.18653/v1/2026.acl-long.226.

  1. All ten are from Project Gutenberg: Pride and Prejudice, Moby-Dick, Great Expectations, A Tale of Two Cities, Frankenstein, Dracula, The Adventures of Sherlock Holmes, The Picture of Dorian Gray, Adventures of Huckleberry Finn and Alice’s Adventures in Wonderland, 6,793,686 bytes in all.↩︎

  2. Both from the library’s scan benchmark, median nanoseconds per byte on one core: 3.07 for Rabin–Karp against 1.94 for the scan.↩︎

  3. RRR, the compressed row of bits that holds the marks: [25].↩︎

  4. Measured on one core kept for the run: the time to find each position of a four-letter fragment, median of five runs.↩︎

  5. Counting took about 1 microsecond, and each position found took about 2.4 more. Measured over the ten books with 2,000 eight-byte fragments, finding the 9,193 positions of 100 of them, and reading back 200 ranges of 100 bytes. The compressed index and the plain one below were timed in turn in the same process, 40 rounds in each of 6 processes; every figure is a median over the repeats.↩︎

  6. A count took about 1 microsecond on the compressed index against 0.3 on the plain one, each position found took 2.4 microseconds against 0.4, and reading back 100 bytes took 10.4 microseconds against 3.2.↩︎