CComputer Science, Built

Act IV · Algorithms

Part 21 of 61

Strings

Degreestarts at this level51 min of film18 chaptersprerequisites: Part 12, Part 17, Part 19, Part 20

How do you find, compress and compare text without reading all of it again each time?

The part opens with Queequeg found four ways in the 25 megabytes of thirty novels: by a naive scan, by Knuth, Morris and Pratt, by Boyer and Moore, and by sixteen rank requests on an index. The naive scan costs about one comparison per character on English and (n - m + 1) m on a run of one letter; rolling hashes, the border table of KMP and the skips of Boyer and Moore each remove part of that cost, and Aho and Corasick search for many patterns in one pass. The part then indexes the text itself: a suffix tree, the suffix array of the whole corpus, and the Burrows-Wheeler transform, whose last-to-first mapping both inverts it and searches it backwards as the FM-index. Compression follows from the same structure: Lempel and Ziv's back-references, Huffman and ANS coding, and the rule that a better model of context costs fewer bits. Alignment, Myers' diff on the history of the course's own syllabus, rsync and content-defined chunks compare and synchronize texts. The part ends with periods, palindromes and Lyndon words, and with indexes whose size follows the number of runs of the transform.

What you need. Logarithms and the idea of entropy as bits per symbol; modular arithmetic for the rolling hash.

Mathematics, ideas and history
Rabin–Karp, KMP, Boyer–Moore, Aho–Corasick, suffix trees and arrays, the BWT and FM-index, LZ compression, Myers' diff
What we build or compute
a BWT compressor and FM-index on the novels

What you will be able to do

Degree

  • Compute the border table of a pattern and trace Knuth-Morris-Pratt on a text without moving backwards in it.
  • Build the suffix array and the Burrows-Wheeler transform of a short string by hand, and invert the transform with the last-to-first mapping.
  • Parse a text into Lempel-Ziv back-references, and read an edit script off Myers' edit graph.

Graduate

  • Prove the 2n comparison bound of KMP by the amortized argument, and the (m - 1)/p collision bound of a rolling hash with a random base.
  • Run backward search on an FM-index, counting the rank requests, and explain what locating adds to counting.
  • Derive the O(N(D + 1)) bound of Myers' algorithm from furthest-reaching paths on diagonals.

Research

  • State what an index of size proportional to the number of runs r of the transform supports, and how r relates to the Lempel-Ziv phrase count z.
  • State exactly what the SETH lower bound for edit distance covers, and which variants (approximation, banded, compressed inputs) escape it.

Industry

  • Choose between fixed blocks, a rolling checksum and content-defined chunks for synchronizing or deduplicating files, and predict what an insertion does to each.
  • Report a compressor or an index honestly: emitted bytes against a cost model, and count queries against locate queries.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Degree 17 min · Graduate 48 min · Research 51 min · Industry 20 min.

  1. 0Queequeg, four waysDegree2 min
  2. 1Matching, the obvious wayDegree2 min
  3. 2Rolling hashesDegree2 min
  4. 3Knuth, Morris and Pratt: never look backDegree3 min
  5. 4Boyer and Moore: skip aheadGraduate3 min
  6. 5Many patterns at onceGraduate3 min
  7. 6Suffix treesGraduate3 min
  8. 7Suffix arraysGraduate4 min
  9. 8The Burrows-Wheeler transformGraduate3 min
  10. 9Searching compressed text: the FM-indexGraduate3 min
  11. 10Compression, I: Lempel and ZivDegree4 min
  12. 11Compression, II: coding the symbolsGraduate3 min
  13. 12AlignmentGraduate3 min
  14. 13Myers' diffDegree3 min
  15. 14Rolling hashes at scale: rsync and chunkingIndustry3 min
  16. 15Periods, palindromes and Lyndon wordsGraduate3 min
  17. 16Frontier: indexes as small as the informationResearch3 min
  18. Recap, problems, and where this comes backAll tracks2 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.

Queequeg, four waysDegree2 min

Queequeg, the harpooner of Moby-Dick. Where does his name appear in the thirty novels, twenty-five megabytes of text? The obvious method compares the name against the text at every position: about twenty-five million character comparisons, roughly one per character. Knuth, Morris and Pratt's algorithm guarantees it never needs more than two per character, and never looks back. Boyer and Moore's algorithm looks at the end of the name first and skips ahead: three and a half million comparisons, seven times fewer. And an index built from a strange permutation of the text, the Burrows–Wheeler transform, counts with sixteen rank requests. A rank request can do more work than one character comparison; the index build and locating all positions are separate costs. All four agree on the count: 253 occurrences.

Text is the oldest kind of data, and this part is about four things we do to it. We search it, with automata built from patterns and with indexes of every suffix. We compress it. zlib squeezes the novels to about a third, and sorting followed by coding can compress it further. We compare it: an exact shortest diff is a shortest path on a grid, and we will run one on the history of this course's own syllabus. And we synchronize it, sending only what changed, found with the rolling hashes of Part 20.

1Matching, the obvious wayDegree2 min

Put the pattern under the text at the first position and compare left to right until a character differs. Then slide one place and start again. At most positions the first character already fails, so the work is close to one comparison per character of text. When the pattern does match, as at positions zero and seven here, we pay its whole length.

On the whole corpus, 24,971,555 characters, the naive method costs very little more than one comparison per character for every pattern we tried. English text is kind to it: most positions fail at once, and even common words like the cost under one point one.

Why is English kind to this search? A second comparison happens only after the first character matches; a third needs the first two. Count those matching prefixes at complete alignments only, including overlaps. The empty prefix contributes A, where A is n minus m plus one, or zero if the pattern is longer. This is an exact finite count, not an independence assumption. Dividing by the text length gives the table, and the reference and instrument agree exactly before rounding. For aaaa and aa there are three alignments and two comparisons each: six. Counting prefixes beyond the final complete alignment would overcount.

The worst case is easy to build. Search for a run of a's ending in b inside a text of nothing but a's. Every alignment matches m minus one characters before it fails. The count is exactly n minus m plus one, times m: a hundred thousand characters and a thousand-letter pattern take ninety-nine million comparisons. DNA, with its four letters, binary files, and anyone who wants to slow a server down all find this case. KMP removes this worst case; the other matchers need their own assumptions and refinements.

2Rolling hashesDegree2 min

Richard Karp and Michael Rabin, in 1987, used Part 20's fingerprints. Read each window of m characters as a number in base b, modulo a prime p, and compare it with the pattern's number. Sliding the window by one place doesn't need a fresh sum: subtract the character that leaves, multiply by the base, and add the one that arrives. That is a constant amount of work per position, and characters are compared only when the two numbers agree. For two fixed unequal byte windows, choose a prime larger than 255 and a base uniformly in its field. They give the same number only if a nonzero polynomial of degree m minus one vanishes at that base, which Schwartz–Zippel says happens with probability at most m minus one over p.

Here is Queequeg in Moby-Dick, 1,217,697 bytes. This experiment fixes the base at 256. The windows-over-modulus column is a heuristic reference, not a randomized expectation for this fixed text and base. The small modulus produces many false alarms; every one is rejected by exact byte comparisons. Larger moduli have fewer false alarms in these observations. Randomizing the base would give the polynomial bound from the previous screen, with a prime larger than the byte alphabet. Fingerprints can also screen many equal-length patterns at once, before exact verification, and extend to two-dimensional matching. Rolling updates return in rsync and deduplicating backups.

3Knuth, Morris and Pratt: never look backDegree3 min

Suppose j characters of the pattern have matched, and the next one fails. The naive method slides one place and re-reads text it has already seen. But those j characters of text are exactly the first j characters of the pattern, so we know them without looking. The only useful question is how far the pattern can shift so that what we have seen still matches. The answer is the longest proper prefix of those j characters that is also a suffix of them, called a border. Shift the pattern so the border lines up, and carry on comparing from the same text position. The text is read once, left to right, and never backed up. For the pattern a b a b a c a, after a b a b a the border is a b a, so we continue as if three characters had matched. The table is computed from the pattern alone, in linear time, by running the same idea on the pattern against itself.

The failure table is really a finite automaton, the kind Part 12 built from regular expressions. State q means: the last q characters read match the first q of the pattern. Each matching character moves one state right. A mismatch follows the border back: from state five, a b means the last characters read are a b a b, state four. Every other transition returns to the start. Now feed it text, one character at a time, with no backtracking at all. When it reaches state seven, the pattern has just ended.

How much work is that? Every comparison either matches, and the text position moves right, or fails, and the pattern's starting position moves right. Each of those can move right at most n times, so there are at most two n comparisons in all, plus linear work to build the table. This is an amortized argument, like Part 16's doubling arrays: a single character can cost several comparisons, but never many on average. Chapter one's worst case, which cost the naive method ten million comparisons, costs 199,901. On the novels, Knuth–Morris–Pratt is no faster than naive search; it is never slower, whatever the text.

4Boyer and Moore: skip aheadGraduate3 min

In 1977 Robert Boyer and J Strother Moore turned the comparison around. Put the pattern under the text and compare its last character first. Here the text has a space where the pattern has g, and a space appears nowhere in Queequeg. So no alignment that covers that space can match, and the pattern can jump its whole length. When the character does occur in the pattern, use its rightmost copy before the pattern's final position, as in the Horspool shifts animated here. Watch how few characters of the text are ever looked at.

The full algorithm takes the larger of two safe shifts. The bad-character rule uses the mismatched text character. The good-suffix rule uses the suffix already matched, or a compatible border. Galil's refinement can guarantee a linear worst case. Our measured implementation omits that refinement, so it can still take n times m comparisons; favorable skipping on English is an observation, not a universal n-over-m theorem. Horspool uses only the window's last character for its shift. Mike Haertel explained how skipping helps GNU grep. Real search tools choose among several engines according to the pattern, options and platform.

The good-suffix rule deserves an example. Here the pattern ANPANMAN is lined up under the text, and comparing from the right, M A N matched before a mismatch. Whatever the next possible alignment is, the text there still ends in M A N, so the pattern must have a matching piece under it. ANPANMAN has no other M A N, but its prefix A N is a suffix of M A N, a border again, so the pattern can slide until that A N lines up. That is a shift of six instead of one, and here it lands on a match; and the whole table is computed from the pattern before the search starts. On English the bad-character rule does most of the work, because the alphabet is large; on DNA, with four letters, the good-suffix rule earns its keep.

We measured three random patterns of each length in Moby-Dick. Knuth–Morris–Pratt does about one comparison per character, whatever the length. Boyer–Moore does about half a comparison per character for two-letter patterns, a sixth for eight letters, and a twentieth for sixty-four: the longer the pattern, the less of the text it reads. Horspool's simplification lies almost exactly on top of it. On English, the good-suffix rule rarely matters. For Queequeg in the whole corpus, Boyer–Moore made three and a half million comparisons, seven times fewer than the naive method, and the table gives current host observations for grep and native byte counting, with every result checked. These timings are not controlled speedup estimates.

5Many patterns at onceGraduate3 min

Often we want many patterns at once: every virus signature, every banned word, every name in a list. Running one search per pattern reads the text again and again. In 1975 Alfred Aho and Margaret Corasick put all the patterns into one trie, a tree of their prefixes. Reading the text, we walk down the trie while characters match. On a mismatch, we follow a failure link to the longest proper suffix of what we've read that is still in the trie: from s h, the link goes to h. And each state lists every pattern that ends there: reaching s h e reports she, and also he. This is Knuth, Morris and Pratt's failure function, generalized from a line to a tree, and it reads the text exactly once.

How are the failure links found? Breadth-first, level by level from the root. A failure link always points to a shallower state, so by the time we reach a state, every state its link could need has been done. For a child t of state s, reached by character c, start from s's own failure link and keep following links until reaching a state that has a c child; t's link is that child. For s h e: s h links to h, and h has an e child, so s h e links to h e. Each state also inherits the outputs of the state it links to, which is how she reports he. Linear construction bounds need a specified transition and output representation. Our sparse teaching implementation follows fallback links and copies inherited output lists, so those costs must be counted explicitly.

We built the automaton for 45 character names from the novels: Elizabeth, Ahab, Queequeg, Holmes, Raskolnikov and the rest. The trie has 231 states. The step count includes trie transitions and fallback traversals. Reporting all matched outputs adds work; the host time includes construction and search. Searching for each name separately would read the text forty-five times, more than a billion characters. These are substring counts, so Jo also counts John and Joe; a real tool would add word boundaries. The same automaton runs inside grep with many patterns, antivirus scanners and network intrusion detectors.

6Suffix treesGraduate3 min

Fix the text and search it repeatedly. Put every suffix of banana with a unique end marker into one compact tree. Each leaf gives its suffix's start. Branch only where suffixes differ, leaving at most n leaves and fewer than n branching nodes for the indexed text. The theoretical representation stores edge labels as intervals into the original text; our small drawing materializes labels for convenience. With constant-time child lookup, a pattern walk costs order m. Stored subtree sizes give its count; reporting all matching leaves adds work proportional to the output. Ana reaches the branch with starts one and three.

Our small drawing is constructed from a suffix array and LCP values. Ukkonen is the theoretical online alternative: naive suffix insertion can walk a quadratic number of characters. Esko Ukkonen's algorithm extends the tree one character at a time instead, turning the tree of the first i characters into the tree of the first i plus one. Two tricks make that cheap. Suffix links join the node for c followed by alpha to the node for alpha, so the algorithm can jump from one suffix to the next shorter one without walking down from the root: a related suffix-shortening idea, although these links have a different invariant from Aho–Corasick. And leaf edges are left open, ending at whatever the current end of the text is, so all the leaves grow by a character at once, for free. The full construction also maintains an active point and skips whole edges. With constant-time child lookup, its amortized work is linear. The same links and the same accounting as Knuth–Morris–Pratt and Aho–Corasick: string algorithms keep rediscovering one idea.

Many questions become walks in this tree. The longest repeated substring is the deepest branching node. In Moby-Dick, it is a chapter title of a hundred characters, which appears in the table of contents and again at the head of its chapter. Put two texts in one tree, and the deepest node with leaves from both gives their longest common substring in linear time, which dynamic programming needs quadratic time for. For n original bytes plus one unique appended end marker, the edge-length sum includes n plus one extra terminated substrings. Subtract them to count the original text: for Moby-Dick, seven hundred and forty-one billion. Peter Weiner first built the tree in linear time in 1973; Esko Ukkonen's 1995 algorithm builds it online, a character at a time. The catch is representation: nodes, child structures and suffix links can take substantial memory. We do not measure a full-corpus suffix tree's allocated size here. The next chapter uses a compact integer array.

7Suffix arraysGraduate4 min

Udi Manber and Gene Myers kept the suffix tree's power with far less memory. Take every suffix of the text and sort them, in dictionary order. Then throw the suffixes away and keep only where each one starts: an array of n integers, the suffix array. Every occurrence of a pattern is the beginning of some suffix, and suffixes beginning with the same pattern are next to each other in sorted order. Here, the four suffixes that start with t. So two binary searches find the block, with m times log n character comparisons at most, and the block's size is the number of occurrences.

How do you sort twenty-five million suffixes, each up to twenty-five million characters long? Rank them first by one character. Then notice that ranking by the first two k characters is the same as sorting pairs: the rank of the suffix's first k characters, and the rank of the k characters after them, which is the rank of another suffix. Double k until every suffix has its own rank: log n rounds of sorting. Linear-time algorithms exist too; SA-IS, from 2009, sorts a sample of the suffixes recursively and induces the rest, and it is what fast libraries use. Alongside, keep the longest common prefix of each pair of neighbours in sorted order, which Kasai and colleagues showed how to compute in linear time. The arrays, with suitable auxiliary structures, recover many suffix-tree queries. Their space depends on entry widths and on which query operations are supported.

We built the suffix array of all 24,971,556 characters of the novels, by prefix doubling with numpy's sorts, in with the observed build time shown here. The cached array takes about a hundred megabytes with four-byte entries; that excludes the text and larger construction temporaries. Now any pattern is a pair of binary searches: Queequeg's two hundred and fifty-three occurrences were found with a hundred and sixty-seven character comparisons, against twenty-five million for a scan. And Moby-Dick's LCP array says that neighbouring suffixes share eight characters on average, which is why the binary search rarely compares more than a few characters per step.

With the suffix array and its LCP array, the longest repeated substring is simply the largest common prefix of two neighbours. For the whole corpus we computed it by comparing neighbouring suffixes in numpy, extending every adjacent pair to its first mismatch, including the residual characters after any doubled block. The winner is 428 characters long, and it is not prose: it is a run of chapter headings, Chapter one, Chapter two, Chapter three, reappearing a few hundred characters later. In Moby-Dick alone, the longest repeat is a chapter title printed twice. This is a maximum for exact contiguous bytes, not a claim that prose cannot be reused or paraphrased.

Here is the exact witness. These two half-open intervals contain the same four hundred and twenty-eight bytes. The next byte is different, so this pair cannot extend. A witness alone does not prove a global maximum: we also checked every adjacent pair in the certified suffix order, and an independent native Kasai implementation agrees.

8The Burrows-Wheeler transformGraduate3 min

In 1994 Michael Burrows and David Wheeler published a transform that Wheeler had found years earlier. Write down every rotation of the text, here banana with an end marker. Sort the rotations. The first column is now just the letters of the text in order. The last column is the transform: a n n b, end marker, a a. Each character in the last column is the one that comes just before its row in the text. Rows that begin alike are sorted next to each other, so the characters before them cluster too. In Moby-Dick, nearly three in four of the rows beginning h e end in t, so the sorted text has long runs of the same letter.

Sorting threw away the order of the text, or seemed to. The key fact: the k-th a in the last column and the k-th a in the first column are the same character of the text. Rows that start with a are sorted by what follows the a, and so are the rows that end with a, because the text after that a is the rest of each rotation. So start at the row ending with the end marker, which is the text itself. Read its last character, then jump along the arrow to the row that begins with that same character, and repeat. The text comes out backwards, one character per jump. We inverted the transform of all of Moby-Dick this way and got the novel back exactly.

Here is the opening of Moby-Dick, and a stretch of its transform. The transform is full of runs. Across the novel there are just over half a million runs for 1.2 million characters. Move-to-front coding replaces each character by its position in a list of recently seen characters, so a run becomes a string of zeros: the entropy drops from four point four bits per character to two point seven. That is the recipe of bzip2, which Julian Seward released in 1996: transform, move to front, then Huffman. On the novel it beats zlib's Lempel–Ziv by a quarter.

Why does sorting help a later coder? Rows are sorted by what follows a position; the last column holds what precedes it. Characters before similar right contexts are grouped together: before he, before hi, and so on. Within those groups some characters dominate. Before he, t dominates here. The transform itself is a reversible permutation, so its zero-order histogram and entropy are unchanged. Compression comes from coding the resulting local structure. The lower-order conditional entropies shown below illustrate the value of context; they are not promised final file sizes. Manzini's 2001 analysis gives high-order entropy bounds for specified coding pipelines, with constants and overhead terms. Those terms matter for short texts and large context orders.

9Searching compressed text: the FM-indexGraduate3 min

Paolo Ferragina and Giovanni Manzini saw in 2000 that the transform is itself an index. The sorted rows are the sorted suffixes of chapter seven, so all occurrences of a pattern are a block of consecutive rows. Find the block by reading the pattern backwards. Start with the last character, a: rows one to three begin with a. Which rows begin with n a? They are where the LF mapping sends those a rows whose last character is n, and two counts of n in the last column, before row one and before row four, say where they land: rows five and six. Once more for a n a: rows two and three. Two rows, two occurrences. Each character of the pattern costs two rank queries, whatever the length of the text.

The distinction is visible in the work itself. Counting Queequeg returns one suffix interval with two hundred and fifty-three rows. Locating asks which text position belongs to each selected row, so it follows LF links to stored samples. Here we locate only the first five rows, not all occurrences. The two lanes count their rank requests separately. Building the index and storing its input are separate costs, and one rank request is not one character comparison.

Real FM-indexes answer rank queries without storing the transform as bytes. A wavelet tree splits the alphabet in two and writes one bit per character: zero for the first half, one for the second. Then it does the same, recursively, for the characters of each half: log sigma levels of bit vectors. To count the n's before position i, ask how many ones come before i at the top, follow that count into the right child, and ask again. Guy Jacobson showed in 1989 how to answer a binary rank in constant time with only a sliver of extra bits. Compress the bit vectors, or shape the tree like a Huffman code, and the whole index takes about the compressed size of the text.

Here is the teaching index on the whole corpus. Count timing is a single warm observation, with index construction excluded. Locating is separate: we check up to the first five matching rows and show mean time per returned location. A dash means no occurrence to locate. Samples are chosen by text offset divisible by thirty-two, so at most thirty-one LF steps reach one. The implementation stores plain BWT bytes, rank checkpoints and Python dictionaries. Its modeled storage excludes Python object overhead; it is larger than the text. Compressing the BWT is only one part of an index. The bzip2 size is a file-size reference, not the size of a fully functional FM-index: rank structures and locate samples still cost space. FM-indexes are used by DNA aligners such as BWA and Bowtie; production implementations add specialized layout and search strategies.

10Compression, I: Lempel and ZivDegree4 min

In 1977 Abraham Lempel and Jacob Ziv proposed the idea behind zip, gzip and PNG. Read the text left to right. Whenever the next stretch has appeared recently, don't write it again: write a pair, how long it is and how far back it was. Here is the opening of A Tale of Two Cities. It was the, of times, it was the: each repetition becomes an arc back to its first appearance. The search looks back over a window, thirty-two kilobytes in DEFLATE, and matches from three to two hundred and fifty-eight characters. Finding the longest match fast is a hashing problem: index every three-character prefix in the window, and follow the chain of earlier positions with the same prefix.

DEFLATE, the format inside zip and gzip, puts Lempel–Ziv and Huffman together. Literal bytes and match lengths share one alphabet of two hundred and eighty-six symbols, and distances have their own thirty. Big values are coded as a bucket plus a few extra raw bits, so that the Huffman alphabets stay small. Dynamic blocks carry a pair of compressed Huffman codebooks; fixed-code blocks and stored blocks are alternatives. The compressor's cleverest trick is lazy matching: before committing to a match, it checks whether starting one character later would give a longer one. Our instrument prices tokens only; it does not implement the full framing or block choices. The levels from one to nine trade how hard the compressor searches against speed, while decompression is always quick, little more than copying bytes. Phil Katz designed it in 1993 for PKZIP; it was standardized in 1996 and has been everywhere since.

A year later Ziv and Lempel gave a second scheme. Keep a dictionary of phrases. Read the longest phrase already in it, write down its number, and add that phrase plus the next character as a new entry. The phrases grow one character at a time, so common stretches of text soon have a number of their own. Terry Welch's variant, LZW, starts with every single byte in the dictionary. It ran Unix's compress command and GIF images. Ziv and Lempel proved something remarkable: for any stationary ergodic source, the number of bits per character tends to the source's entropy rate, the best possible. That asymptotic result concerns classic universal LZ schemes.

We parse three novels into literals and back-references, then estimate their payload bit costs. Every token stream is decoded and compared byte for byte with its input. The LZW codes also pass an independent decoder. These columns are models: they omit framing, transmitted codebooks and other metadata, and do not form a complete DEFLATE file. A close payload estimate is not an end-to-end compressor result. The zlib, bzip2 and xz columns are actual emitted files, each decoded and checked. Their relative sizes are observations on these novels, not a universal ranking. DEFLATE combines LZ back-references with Huffman coding; real formats also define how headers, codebooks, blocks and end markers are transmitted.

11Compression, II: coding the symbolsGraduate3 min

Lempel–Ziv finds the repetition; then the symbols must be written in bits. Shannon says a symbol of probability p is worth log of one over p bits, and the average is the entropy. Huffman's code from Part 19 gives each symbol a whole number of bits, which is within one bit of that. Usually that is fine. But take a source where one symbol has probability ninety-five percent: its entropy is under three tenths of a bit per symbol, and Huffman still spends a whole bit on every symbol, more than three times too much. The last column, rANS, gets to within a fraction of a percent of the entropy, at every skew. On the bytes of Moby-Dick, where no symbol dominates, Huffman's whole bits cost less than one percent.

Arithmetic coding approaches fractional information costs by encoding a whole message through a numerical interval. Jarek Duda's asymmetric numeral systems keep the message as a single integer x and push each symbol into it. Divide x by the symbol's frequency, multiply by the total, and add the remainder and the symbol's offset. Here f is the symbol's frequency out of M. Each step multiplies x by about one over the symbol's probability, so the bit growth approaches its information content. The small trace shows finite-state increments are not exactly equal. In practice x stays inside a machine word by streaming out its low bytes, and decoding runs the same arithmetic backwards. Duda's work from 2009 to 2014 provides state-based entropy coding. Speed and compression depend on the model, precision and implementation. It is inside zstd, Apple's LZFSE and JPEG XL. Our byte-wise implementation round-trips the measured streams. Its frequency table and decoded length are external metadata, excluded from the displayed payload size.

The model determines which events the coder can predict. For these Moby-Dick bytes, empirical entropy falls from about four point four bits with no context, to three point five with one previous byte, and two point eight with two. Better prediction can reduce payload cost. PPM, context mixing and language models supply richer predictions. Comparing complete compressors also requires their model descriptions, framing and computation; this part runs no language-model compression benchmark. zstd combines LZ parsing with Huffman and ANS coding, tuned for practical speed and compression tradeoffs.

12AlignmentGraduate3 min

Part 19's edit distance becomes, in biology, an alignment. Saul Needleman and Christian Wunsch, in 1970, filled the same table, but with scores to maximize: a reward for matching letters, penalties for mismatches and gaps. Each cell is the best of three: extend the alignment by a pair, or by a gap on either side. Here intention against execution, the example of Part 19. Real biology scores amino acids with substitution matrices learned from evolution, and charges more to open a gap than to extend one, because one long insertion is likelier than many short ones.

Often only part of two texts is related. Temple Smith and Michael Waterman added a fourth choice to every cell: zero, meaning start a fresh alignment here. The best local alignment is the highest cell anywhere in the table, traced back until the score drops to zero. Here are the two versions of the anonymous letter from The Count of Monte Cristo that Part 20's MinHash flagged. Smith–Waterman finds the stretch they share and lines it up, word for word, around the places where the second version was reworded.

This screen illustrates affine scoring; our measured alignments use constant gap penalties. Biology, and diff, prefer one long gap to many short ones, so a gap of length l costs an opening charge plus a small charge per character. A single table can't price that, because a cell doesn't know whether its neighbour was already inside a gap. Osamu Gotoh's solution keeps three tables: M for alignments ending in a pair of characters, X for those ending in a gap in one string, and Y for a gap in the other. Moving within X or Y costs only the extension; entering them from M pays opening plus the first extension, matching the displayed o plus e times length convention. The time is still the product of the lengths, and Hirschberg's divide-and-conquer trick from Part 19 brings the memory down to linear.

Full pairwise tables are quadratic. Two genomes of billions of bases require on the order of ten to the nineteen cells. BLAST-style seed-and-extend filters candidate regions, which can miss an optimum. FM-indexes help find candidate seeds in read aligners. The conditional lower bound concerns exact unit-cost edit distance in the worst case; it does not rule out fast structured instances. With a valid edit-distance bound k, unit-cost dynamic programming restricted to the corresponding band is exact, in order N times the quantity k plus one work. These are scaling strategies; our measured examples use complete tables. The next chapter uses Myers' distinct insertion-and-deletion distance.

13Myers' diffDegree3 min

Every git diff answers one question: what is the shortest list of line insertions and deletions that turns one file into another? Gene Myers drew it as a graph. Put the lines of the old file along the top and the new file down the side. A step right deletes a line of the old file, and a step down inserts a line of the new one; each costs one. Wherever two lines are equal there is a diagonal, which keeps the line and costs nothing. A diff is a path from the top-left corner to the bottom-right, and the best diff is the shortest path, Part 18's problem, on a grid. For Myers' own example, A B C A B B A against C B A B A C, five edits, and as many free diagonals as possible.

Dijkstra's algorithm would work, but Myers found something better in 1986. Number the diagonals by x minus y. A path with D edits can only end on diagonals from minus D to D. For D equals zero, one, two and so on, keep, for each diagonal, only the path that has reached furthest along it. Each new path is the best neighbour's path plus one edit, followed by a slide down every free diagonal it can, which Myers called a snake. The first path to reach the corner is a shortest diff, after order N times the quantity D plus one work, where N is the two lengths added and D counts insertions and deletions, so similar files are fast. Patience diff, by Bram Cohen, first anchors on lines that appear exactly once in each file, which keeps code blocks together. And three-way merge, the heart of git merge, diffs both branches against their common ancestor and uses the overlapping edits to identify candidate conflicts; exact merge behavior depends on the merge strategy.

We ran Myers on adjacent pairs in the 52 captured syllabus revisions, in chronological order. Full commit IDs and content hashes fix the input history. The chart shows the exact insertion-and-deletion distances. The timing shown is a host observation for that pair. Similar adjacent revisions usually have smaller D. Identical files still need a linear scan, hence N times the quantity D plus one. Every script reconstructs both inputs, and every distance equals the independent quadratic LCS reference. A shortest script describes a possible transformation, not the author's causal edit history. Git's minimal diff has a different line count on 0 of these 51 pairs. Its preprocessing and heuristics can choose a different script. This is not evidence of corrupt output.

14Rolling hashes at scale: rsync and chunkingIndustry3 min

You have last week's copy of a large file, and the server has today's, which differs by a sentence inserted in the middle. How do you update your copy without downloading all of it? The obvious plan cuts both files into fixed blocks and sends only the blocks whose hashes differ. But an insertion shifts everything after it. We inserted twenty-four bytes into the middle of Moby-Dick: half of the fixed blocks now differ, though almost nothing changed.

Andrew Tridgell and Paul Mackerras's rsync, from 1996, uses a rolling weak checksum to find candidates. Our instrument verifies candidates by full byte equality, standing in for a strong-hash check. The receiver hashes each of its blocks twice, once weakly and once strongly, and sends the list. The sender slides a window over its new file one byte at a time, looking for any old block at any offset. The weak checksum, two running sums, updates in constant time as the window slides, like chapter two's fingerprints. Only when the weak checksum matches is the expensive strong hash checked. For our edited Moby-Dick, 593 of the old blocks were found in place or shifted, and only about three kilobytes had to be sent as literal text.

rsync uses the old file's block hashes. Across a large backup collection, that metadata grows with the number of blocks. Content-defined chunking turns the idea around. Let the content choose where to cut: run a rolling hash over the bytes, and cut wherever its value ends in thirteen zeros, which with a minimum chunk size comes about every ten kilobytes. In this bounded gear-hash experiment, boundaries can resynchronize after the edit. In this instance, the later cuts return to the old content boundaries. Moby-Dick cut into 120 chunks; after our edit, exactly one chunk was new, fourteen kilobytes. Our sixty-four-bit chunk fingerprints are checked against complete byte chunks, so undetected collisions cannot explain the reported reuse. In a production system, store each chunk once under a suitable content hash, and a thousand nightly backups of a slowly changing disk cost little more than one. This is how deduplicating backup tools and cloud file sync work.

15Periods, palindromes and Lyndon wordsGraduate3 min

Some structure lives inside a single string. A string has period p if every character equals the one p places later. This one has periods five and eight. The periods are exactly n minus the borders of chapter three, so the failure function lists them all. Nathan Fine and Herbert Wilf proved in 1965 that if a string has periods p and q and is at least p plus q minus their greatest common divisor long, it also has that divisor as a period. Five and eight have divisor one, so a string of twelve characters with both periods would be a single repeated letter; ours, of eleven, escapes, which shows the bound is tight. Periodicity supports safe skips in methods such as Galil's refinement and two-way matching. The engines selected by actual libraries depend on the implementation and input.

What is the longest palindrome after keeping ASCII letters, lowercasing them and requiring at least four distinct letters? Expanding around each possible centre is quadratic for a text like a run of a's. Glenn Manacher's 1975 algorithm notices that inside a palindrome already found, each centre mirrors one on the other side, so reuse the mirror's radius only up to the known right boundary, then extend by fresh comparisons. The right edge of the furthest palindrome only ever moves right, which makes the whole scan linear. We ran it over the letters of all thirty novels, nineteen million of them, using that diversity filter. This is a query on normalized bytes, not contiguous original prose. The winner, at nineteen letters, is Lenehan in Ulysses: able was I ere I saw Elba.

One more piece of structure. A Lyndon word is strictly smaller, in dictionary order, than every nontrivial rotation. Kuo-Tsai Chen, Ralph Fox and Roger Lyndon proved that every string splits in exactly one way into Lyndon words that never increase. Banana is b, an, an, a. Mississippi is m, iss, iss, ipp, i. Jean-Pierre Duval found the factorization in linear time with constant working memory, excluding the returned factors. It sounds like a curiosity, but it gives a Burrows–Wheeler transform without an end marker, and Lyndon words were the key to the 2017 proof that a string of length n has fewer than n maximal repetitions.

16Frontier: indexes as small as the informationResearch3 min

Repetition changes what a useful index should store. We concatenate 52 captured syllabus revisions in reverse chronological git traversal order, without separators, and append one unique end marker. The comparison uses the same number of bytes from the novels, plus that marker. The table reports complete BWT run counts, not an extrapolation from these two display strips. xz's emitted size is checked by decoding it; the compression ratio is for this exact snapshot. Versioned documents and source histories commonly contain this kind of reuse. Genomic collections are another motivation, although this experiment measures no genome data. Fixed-order statistical entropy can miss long-range copies. BWT run count and phrase count capture different kinds of repetitiveness.

A run-length index stores structure proportional to r. Rank at any queried row combines counts before its run with the partial run; predecessor search finds that run. Periodic suffix-array samples alone cost n over s, so locating needs a different representation to fit run-bounded space. Gagie, Navarro and Prezza's 2018 work, published in 2020, uses run-boundary samples with additional structures. On their word-RAM model, order r words support locating at log log n per occurrence after the pattern-search cost. Later move structures support constant-time LF within order r space. These are theoretical results, not implementations measured in this part. Kempa and Kociumaka's 2020 result bounds r by order z times log squared n. Here z uses the paper's unbounded LZ77 convention, not our fixed-window parser's token count. Delta, attractors, macro schemes and LZ give one hierarchy. But r and z are incomparable; they do not form the simple ladder z less than or equal to r.

Here are selected dated results, rather than a complete current frontier. Backurs and Indyk's 2015 conditional lower bound concerns exact unit-cost edit distance in the worst case. It is not a lower bound for every biological score or every compressible input. Compression can speed up alignment on structured instances. Andoni and Nosatzki's 2020 randomized approximation takes n to the one plus eta, for each fixed positive eta, with an approximation constant depending on eta. That is not a claim of n times polylog n time. Our implemented distance-sensitive method is Myers: order N times the quantity D plus one for insertion-and-deletion distance. Unit-cost Levenshtein distance also allows substitutions, so it is a different problem.

A useful research project begins with precise questions. Compare space and construction costs, then count and locate separately, on fixed text families. For any approximation result, record its factor, running-time exponent, randomness and success probability. For repetitive indexes, fix sentinels, parsing conventions and whether space means bits, machine words or allocated bytes. The starred exercise asks for a reproducible tradeoff study and a dated literature review. Before declaring a question open, check newer primary work; the historical results in this chapter are not a claim about the latest boundary.

Recap, problems, and where this comes backAll tracks2 min

What we built in this part. Naive search and its worst case; rolling hashes; Knuth, Morris and Pratt's automaton; Boyer and Moore's skips; Aho–Corasick for many patterns. A small suffix tree and a suffix array for all the novels. The Burrows–Wheeler transform and the FM-index. Lempel–Ziv, Huffman and ANS. Alignment, Myers' diff, rsync and content-defined chunking. Periods, palindromes and Lyndon words.

Where this comes back. Part 27 proves the conditional lower bounds behind edit distance's quadratic wall. Part 28 adds noise to the information theory and builds error-correcting codes. Parts 34 and 35 compress storage engines and column stores. Part 41 builds git's merges on Myers' diff and its packfiles on delta compression. Part 47's search engine uses inverted indexes and near-duplicate detection, and Part 57 connects learning to compression.

In practice, search tools choose among literal matching, automata and vectorized routines. Familiar compressors combine dictionaries, transforms and entropy coders in different ways. DNA aligners use FM-indexes or seeds. Git offers several diff strategies. Rolling checksums and content-defined chunks support synchronization and deduplication, with stronger content verification where required.

Six exercises are in the notes, with worked mathematical solutions and explicit build guidance. The fifth provides a tested streaming Horspool prototype; a Pebble port and emulator instruction counts remain work for the learner. The starred project reproduces index tradeoffs and audits dated primary papers. It does not ask you to solve a supposedly open problem whose current status has not been established.

Next time, geometry. It looks easy until a computer gets it wrong: a floating-point orientation test can say a point lies on both sides of a line. Get the predicates right and beautiful structure follows: convex hulls, Voronoi diagrams grown by a parabolic beach line, and Delaunay triangulations that are the shadow of a convex hull on a paraboloid. Part 22, Geometry.

The books and papers this part follows are on screen and in the notes. Thank you for watching.

Where it goes next. Part 27 proves the conditional lower bound behind edit distance's quadratic wall; Part 28 adds noise to the information theory; Parts 34 and 35 compress storage engines and column stores; Part 41 builds git's merges on Myers' diff and its packfiles on delta compression; Part 47 uses inverted indexes and near-duplicate detection, and Part 57 connects learning to compression.

Key results

The part's results in one place, for revision.

Rolling hash\(\displaystyle h_{i+1}=\bigl(h_i-t_i\,b^{m-1}\bigr)\,b+t_{i+m}\pmod p,\qquad\allowbreak \Pr[\text{collision}]\le\frac{m-1}{p}\)
Knuth-Morris-Pratt\(\displaystyle \text{comparisons}\le 2n,\qquad\allowbreak \text{periods }\allowbreak \text{of } w=\{\,|w|-|u| : u\text{ a }\allowbreak \text{border }\allowbreak \text{of }w\,\}\)
Last-to-first mapping\(\displaystyle L[i]=T[\mathrm{SA}[i]-1],\qquad\allowbreak \mathrm{LF}(i)=C[L[i]]+\operatorname{rank}_{L[i]}(L,i)\)
Backward search\(\displaystyle lo\leftarrow C[c]+\operatorname{rank}_c(L,lo),\quad\allowbreak hi\leftarrow C[c]+\operatorname{rank}_c(L,hi)\)
Myers' diff\(\displaystyle D=n+m-2\,\mathrm{LCS}(a,b),\qquad\allowbreak \text{time } O\bigl(N(D+1)\bigr),\ N=n+m\)
Fine and Wilf\(\displaystyle \text{periods }p,q,\ |w|\ge p+q-\gcd(p,q)\ \Rightarrow\ \gcd(p,q)\text{ is }\allowbreak \text{a }\allowbreak \text{period}\)

Try it

Lab 21 · Four matchers, one transform, one diff

Count the character comparisons of naive search, Knuth-Morris-Pratt and Boyer-Moore on a text of random words, check the naive count against its exact prefix identity and its worst case, sort the suffixes, invert the Burrows-Wheeler transform, count by backward search, and check Myers' diff against the LCS.

Figure produced by Lab 21: Four matchers, one transform, one diff
Produced by the lab below, seed 0, in 0.3 s.
python -m videos.cs.labs 21 needs numpy, scipy, matplotlib · download lab21.py · source on GitHub
comparisons per character, m = 8   naive 1.142   KMP 1.119   Boyer-Moore 0.168
comparisons per character, m = 32  naive 1.091   KMP 1.062   Boyer-Moore 0.120
worst case, n = 3,000, m = 40      naive 118,440 = (n - m + 1) m   KMP 5,961 <= 2n = 6,000
backward search, 7 characters      7 occurrences counted with 14 rank requests, against 16,461 comparisons for a scan
runs of equal characters           text 15,459   transform 4,273   (15,723 characters)
entropy after move-to-front        text 4.15 bits   transform 1.82 bits   (letters alone: 4.01)
Myers' diff                        D = n + m - 2 LCS on 20 random pairs of sequences

The naive scan costs about one comparison per character on word-like text and (n - m + 1) m at worst; KMP's 2n holds on any text; Boyer-Moore reads less the longer the pattern; and the sorted transform can be both inverted and searched.
The code (111 lines; it asserts its own result)
"""Lab 21: find a pattern four ways in a synthetic text, invert its Burrows-Wheeler transform, and check Myers' diff."""

from videos.coursekit import labs  # noqa: I001  (must stay first: it lets explainer.cs import without manim)

import numpy as np

from explainer.cs.algo import strings as st

TITLE = "Four matchers, one transform, one diff"
GOAL = ("Count the character comparisons of naive search, Knuth-Morris-Pratt and Boyer-Moore on a text of random "
        "words, check the naive count against its exact prefix identity and its worst case, sort the suffixes, invert "
        "the Burrows-Wheeler transform, count by backward search, and check Myers' diff against the LCS.")
TASKS = [
    "Shrink the alphabet to 'ab' in make_text. Boyer-Moore's comparisons per character rise: which of its two shift rules is now doing the work?",
    "Search for a pattern that does not occur and print fm.steps: how many rank requests does backward search make before the interval is empty?",
    "Apply st.move_to_front to the text itself and to its transform, and compare their entropies with the two bars of the figure.",
]


def make_text(rng, words=2500):
    """Space-separated words drawn with Zipf-like frequencies from a vocabulary of 120 random lowercase words."""
    letters = np.array(list("etaoinshrdlucmfwyp"))
    vocab = ["".join(rng.choice(letters, int(rng.integers(2, 9)))) for _ in range(120)]
    p = 1 / np.arange(1, len(vocab) + 1)
    return " ".join(rng.choice(vocab, words, p=p / p.sum())).encode()


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()
    text = make_text(rng)
    n = len(text)

    # 1. three matchers, the same answers; the naive count is an exact sum over matching prefixes
    lengths, per_char = [2, 3, 4, 6, 8, 12, 16, 24, 32], {"naive": [], "KMP": [], "Boyer-Moore": []}
    for m in lengths:
        tot = {k: 0 for k in per_char}
        for _ in range(3):
            i = int(rng.integers(0, n - m))
            pat = text[i:i + m]
            (h1, c1), (h2, c2), (h3, c3, _) = st.naive(text, pat), st.kmp(text, pat), st.boyer_moore(text, pat)
            assert h1 == h2 == h3 and i in h1, "the three matchers find the same occurrences"
            t = np.frombuffer(text, dtype=np.uint8)
            A, alive, identity = n - m + 1, np.ones(n - m + 1, dtype=bool), 0
            for j in range(m):  # alignments whose first j characters match each cost one more comparison
                identity += int(alive.sum())
                alive &= t[j:j + A] == pat[j]
            assert c1 == identity, "naive comparisons = the number of matching proper prefixes, over all alignments"
            assert c2 <= 2 * n, "KMP never exceeds 2n"
            for k, c in zip(per_char, (c1, c2, c3)):
                tot[k] += c / (3 * n)
        for k, series in per_char.items():
            series.append(tot[k])
    i8, i32 = lengths.index(8), lengths.index(32)
    lab.row("comparisons per character, m = 8", "   ".join(f"{k} {per_char[k][i8]:.3f}" for k in per_char))
    lab.row("comparisons per character, m = 32", "   ".join(f"{k} {per_char[k][i32]:.3f}" for k in per_char))
    assert per_char["naive"][i8] < 1.3 and per_char["Boyer-Moore"][i8] < 0.4 and per_char["Boyer-Moore"][i32] < 0.2

    # 2. the worst case: a^n against a^(m-1) b
    wn, wm = 3000, 40
    wt, wp = b"a" * wn, b"a" * (wm - 1) + b"b"
    (_, cn), (_, ck) = st.naive(wt, wp), st.kmp(wt, wp)
    assert cn == (wn - wm + 1) * wm and ck <= 2 * wn
    lab.row("worst case, n = 3,000, m = 40", f"naive {cn:,} = (n - m + 1) m   KMP {ck:,} <= 2n = {2 * wn:,}")

    # 3. suffix array, the Burrows-Wheeler transform and backward search
    T = text + b"\0"
    sa = st.suffix_array(T)
    assert list(sa[:400]) == st.suffix_array_naive(T)[:400] and sorted(sa) == list(range(len(T)))
    L = st.bwt_from_sa(T, sa)
    assert st.inverse_bwt(L) == T, "the LF mapping walks the text back out"
    fm = st.FMIndex(T, sa)
    for m in (1, 2, 4, 7):
        i = int(rng.integers(0, n - m))
        pat = text[i:i + m]
        fm.steps = 0
        count, (lo, hi) = fm.count(pat)
        assert count == len(st.naive(text, pat)[0]) and fm.steps == 2 * m, "two rank requests per pattern character"
        assert sorted(fm.locate(r) for r in range(lo, hi)) == st.naive(text, pat)[0], "and the rows locate the hits"
    lab.row("backward search, 7 characters", f"{count} occurrences counted with 14 rank requests, against {st.naive(text, pat)[1]:,} comparisons for a scan")
    h_text, h_bwt = st.entropy(np.frombuffer(T, dtype=np.uint8)), st.entropy(np.frombuffer(L, dtype=np.uint8))
    mtf_text, mtf_bwt = st.entropy(st.move_to_front(T)), st.entropy(st.move_to_front(L))
    assert st.runs(L) < 0.6 * st.runs(T) and mtf_bwt < 0.7 * mtf_text, "sorting by context gathers equal characters"
    assert abs(h_text - h_bwt) < 0.01, "the transform is a permutation: its letter counts are unchanged"
    lab.row("runs of equal characters", f"text {st.runs(T):,}   transform {st.runs(L):,}   ({len(T):,} characters)")
    lab.row("entropy after move-to-front", f"text {mtf_text:.2f} bits   transform {mtf_bwt:.2f} bits   (letters alone: {h_text:.2f})")

    # 4. Myers' diff: D = n + m - 2 LCS
    for _ in range(20):
        a = [int(v) for v in rng.integers(0, 6, int(rng.integers(5, 40)))]
        b = [v for v in a if rng.random() > 0.2] + [int(v) for v in rng.integers(0, 6, int(rng.integers(0, 5)))]
        d = st.myers(a, b)[0]
        assert d == len(a) + len(b) - 2 * st.lcs_len(a, b), "Myers' D is the insert-delete distance"
    lab.row("Myers' diff", "D = n + m - 2 LCS on 20 random pairs of sequences")
    lab.note = ("The naive scan costs about one comparison per character on word-like text and (n - m + 1) m at worst; "
                "KMP's 2n holds on any text; Boyer-Moore reads less the longer the pattern; and the sorted transform "
                "can be both inverted and searched.")

    fig, ax = labs.figure(2, size=(11, 4.4))
    for (k, v), color in zip(per_char.items(), (labs.RED, labs.BLUE, labs.GREEN)):
        ax[0].loglog(lengths, v, "o-", color=color, label=k)
    ax[0].loglog(lengths, [1 / m for m in lengths], color=labs.MUTED, ls="--", label="1/m")
    ax[0].set(title="Comparisons per character of text", xlabel="pattern length m", ylabel="comparisons / n")
    ax[0].set_xticks(lengths, [str(m) for m in lengths])
    ax[0].minorticks_off()
    ax[0].legend()
    names = ["text,\nletters", "transform,\nletters", "text,\nmove-to-front", "transform,\nmove-to-front"]
    ax[1].bar(names, [h_text, h_bwt, mtf_text, mtf_bwt], color=[labs.BLUE, labs.GOLD, labs.BLUE, labs.GOLD], width=0.6)
    ax[1].set(title="Zero-order entropy before and after the transform", ylabel="bits per character")
    lab.fig = fig
    return lab

Now change it

  1. Shrink the alphabet to 'ab' in make_text. Boyer-Moore's comparisons per character rise: which of its two shift rules is now doing the work?
  2. Search for a pattern that does not occur and print fm.steps: how many rank requests does backward search make before the interval is empty?
  3. Apply st.move_to_front to the text itself and to its transform, and compare their entropies with the two bars of the figure.

Problems, with solutions

Try each problem before opening its solution.

Six exercises with solutions or reproducible build guidance

  1. KMP's bound. Prove O(m) failure preprocessing and at most 2n search comparisons.

    Solution

    Let i be the text position, j the matched-prefix length and s=i−j the alignment start. Every comparison increases i or, on a nonzero fallback, s; both never decrease and are bounded by n. Hence at most 2n. Preprocessing uses the same monotonic accounting on the pattern. Correctness follows because every shorter candidate border is a border of the previous longest border, so the failure chain visits all candidates.

  2. LF is reversible. Assume one unique smallest terminal. Prove that occurrence ranks in L and F align.

    Solution

    Sort the rotations after each occurrence of c. In F, the corresponding rows start with c and are ordered by the following rotation. In L, they end with c and have the same relative order because the following rotations have the same prefixes through their first difference. Thus the k-th c of L corresponds to the k-th c of F: LF(i)=C[c]+rank_c(L,i), using exclusive rank. LF moves the row's start one byte backward cyclically. The unique terminal identifies the original row; n LF steps visit the cycle and emit the reversed text. Without the unique terminal or a valid single cycle, this instrument rejects the input.

  3. Count distinct substrings without counting the terminal. Derive n(n+1)/2−ΣLCP.

    Solution

    Suffix SA[i] contributes n−SA[i] prefixes. Its first LCP[i] prefixes already occur on the preceding suffix. Any earlier suffix sharing a longer prefix would force that same prefix on every intervening sorted suffix, including the predecessor. The longer prefixes are therefore new, giving the formula. If the SA includes a unique smallest terminal, use n equal to the original length: terminal-containing common prefixes are zero, and the terminal-only suffix contributes nothing. Moby-Dick gives 741,383,838,433. banana gives 21−6=15; counting banana\0 as seven original symbols would instead give 22, seven too many.

  4. Fine–Wilf and tightness. If n≥p+q−gcd(p,q), prove gcd(p,q) is a period.

    Solution

    Induct on p+q, with p>q and g=gcd(p,q). If q divides p, q is already a period. Otherwise the prefix u of length n−q has periods q and p−q: for i<n−p, s[i]=s[i+p]=s[i+p−q]. Its length is at least p−g, the induction threshold for those periods, so u has period g. Since p≥q+g, n≥2q; every omitted suffix position has a q-step predecessor in u. As q is a multiple of g, this extends the g-period to the entire string. At length 11, abaababaaba has periods 5 and 8 but not 1; the threshold is 12. A universal threshold cannot be reduced by one.

  5. Build streaming Horspool, then port it to Pebble. Count Queequeg, including overlapping matches.

    Solution

    The completed Python prototype is stream_horspool.py. Precompute shift[c]=m−1−last(c) over pattern positions before the last, default m. Keep m bytes in a ring, compare right to left, then consume the indicated number of bytes through the ring. The search skips comparisons but still reads every input byte. Exhaustive binary strings/patterns at three input chunk sizes agree with brute force and the array instrument. The full corpus returns all 253 exact positions after reading 24,971,555 bytes, with 3,500,231 comparisons. For a Pebble port, use a 256-entry table, ring, head and total-read counters; handle the final partial refill without searching an incomplete window. Compare complete positions/counts before timing the emulator. No Pebble port or emulator instruction count is supplied or claimed here. Instructions per byte must be measured, including all getc, ring maintenance and output operations, rather than inferred from comparison savings.

  6. Research: reproduce an index tradeoff and audit its model. Use growing prefixes of the captured history and novels; pin ordering, separator and end-marker conventions. Measure allocated bytes, construction, count and locate separately; verify every returned occurrence. Compare your teaching FM layout with a named published repetitive index, and record that paper's word size, alphabet, randomization and query assumptions.

    Solution

    A worked starting point is the equal-length 13,758,063-byte experiment: r=150,581 for history and 5,800,029 for novels, or about 91 and 2.37 bytes per run. These are full counts. The 117,040-byte xz stream shows compressibility but provides no rank/locate operation. The teaching FM buffers above exceed the text before Python overhead; their BWT bzip2 file is not a searchable-index measurement. A faithful study reports these distinctions instead of drawing a speed/space conclusion from unlike objects. Extend the size series and add a real index build; do not label a current question open without a dated primary-source review.

Notes and sources

Sources

Primary research references and scope

The packet preserves actual abstract/metadata and keynote reads. These support the scoped statements above; no full-proof verification or exhaustive current open-problem survey is claimed.

About this partfrom its README

Part 21 of the series connects matching, indexing, compression, alignment and synchronization. The instrument is strings.py; compute.py builds 17 guarded schema-2 payloads. measurement_references.py supplies independent references, and stream_horspool.py supplies the tested streaming prototype used in exercise 5.

What is computed and built

The matching corpus has 24,971,555 bytes from thirty novels. Offsets and comparisons in these instruments refer to bytes. The suffix/BWT/FM corpus adds one unique smallest \0 terminator; user queries exclude it. The compression producer's separate literal concatenation has 24,971,526 bytes (29 inter-book separators fewer). Chapter-level BWT experiments also include their terminator. These are distinct, explicitly sized inputs.

  • Queequeg has 253 occurrences. Naive, KMP and Boyer–Moore make 24,974,844, 24,972,212 and 3,500,231 character comparisons. Grep uses -a -o -F and its complete occurrence output is checked. A warm FM count uses 16 rank requests; locating the first five matching rows adds 69 rank requests. These are different units of work. The build is excluded from query timing; positions are checked against full native-match references.
  • The longest exact repeat is 428 bytes, at offsets 13,188,812 and 13,188,303. The following bytes are 66 and 67. The old greedy block extension stopped at 383 after skipping residual matches. The replacement extends every adjacent suffix pair through its first mismatch. An independent native Kasai scan agrees.
  • Moby-Dick has 741,383,838,433 distinct nonempty substrings of its original bytes. The artificial terminal is excluded from n. The former terminal-inclusive result counted an extra 1,217,698 substrings. An independent native LCP sum checks the corrected value and the 102-byte longest repeat.
  • The cached int32 suffix array occupies 99,886,224 array bytes; the .npy header, original text and construction temporaries are separate. Prefix doubling uses O(log n) sorting rounds; its total cost depends on the integer sort used. The small tree is not an executed Ukkonen implementation.
  • The teaching FM-index keeps 24,971,556 BWT bytes, 229,426,428 occurrence-checkpoint bytes and a modeled 3,121,448 bytes of four-byte suffix samples. Python dictionaries and container overhead, input text, the full construction suffix array and temporaries are excluded. The 7,093,132-byte bzip2 file of the BWT is a file-size reference, not the size of a searchable index. Samples are selected by text offset divisible by 32; reaching one takes at most 31 LF steps. Locate timing averages at most the first five matching rows, not all hits.
  • LZ77/Huffman and growing-width LZW columns are payload cost models, without full framing or codebooks. They are not complete DEFLATE/GIF files. LZ tokens round-trip and LZW passes an independent decoder. Actual zlib/bzip2/xz streams are decoded and checked. No universal compressor ranking follows from three novels. Classic universal-LZ asymptotic results do not promise universality for this fixed 32 KiB window/bounded search.
  • rANS uses a quantized empirical model. Emitted state bytes are included; the frequency table and decoded length are external metadata and excluded. Both original and BWT/MTF streams round-trip. The skew experiment compares empirical H0 of each seeded 200,000-symbol sample with coding costs. A finite state step need not add exactly the symbol's information content. The BWT alone is a permutation and leaves H0 unchanged.
  • Both full 300×300 local-alignment tables and the global example are checked against an independent list-DP implementation. The local score is 322. Affine-gap equations are an illustration, not a measured implementation; their convention charges o+eℓ for a gap of length ℓ. Conditional edit-distance lower bounds concern their stated unit-cost problem and worst-case assumptions, not all scoring systems or every structured input.
  • The history snapshot contains 52 full commit IDs and content hashes. Diff uses chronological adjacent pairs (51 scripts), each reconstructed and checked minimal by an independent LCS distance. Repetitiveness uses reverse-chronological git traversal, literal concatenation without separators, then one terminal. The resulting 13,758,063-byte text has 150,581 BWT runs; the equal-length novel prefix has 5,800,029. Display strips are selected for near-average run density, not random samples. xz emits 117,040 bytes and is verified by decoding.
  • Myers' D counts insertions and deletions; a substitution costs two. With N=n+m, O(N(D+1)) covers D=0 too. This implementation retains an O(D²) trace. A shortest script is a possible transformation, not causal edit history. A different git diff length does not imply corrupt output.
  • The rsync instrument uses the rsync-style weak rolling checksum and exact byte equality in place of a strong hash. It is not zlib's Adler-32 convention. Of the edited bytes, 593×2,048 are reused and 3,257 are literal. All gear-hash chunk reuse decisions are checked with full byte chunks, independently of truncated 64-bit hashes. One new chunk has 14,006 bytes in this experiment; resynchronization is not an unconditional guarantee.
  • The palindrome query keeps ASCII letters, lowercases them, and requires at least four distinct letters. Its maximum over 19,384,729 normalized letters is the 19-letter ablewasiereisawelba. Independent native odd/even scans check this filter and maximum. It is not an unrestricted longest-palindrome claim about original prose.

All timings are shared-host observations using perf_counter, with raw repetitions and min/single labels in payloads. Expected references are prepared outside timed regions, and outputs are checked after timers stop. They are not controlled before/after speedup estimates. Regression checks cover empty/long patterns, arbitrary sentinel-like bytes, SA order, invalid BWT/FM input, bounded LF walks, entropy/rANS domains and malformed streams.

The visual languageWhat the pictures establish
  • Slide a pattern, count comparisons, and derive the exact finite-prefix identity. Rolling hashes distinguish fixed-base observations from a randomized-base theorem. KMP's borders and automaton explain its linear bound. Boyer–Moore's shifts and the ANPANMAN example explain safe skipping; the measured implementation omits Galil's refinement and can still take O(nm). Aho–Corasick adds failure links and inherited outputs to a trie.
  • Draw a small suffix tree built from SA/LCP, then illustrate Ukkonen's online construction separately. Sort all suffixes of the corpus by prefix doubling. Follow the BWT rotation matrix and LF mapping, then backward search for ana. A separate two-lane diagram distinguishes count work from locating selected occurrences.
  • Show LZ back-references as arcs and LZ78 dictionary growth as phrase boxes. Separate token bit-cost models from emitted zlib/bzip2/xz files. Trace finite rANS states; context-entropy bars explain why the model matters.
  • Fill global/local alignment grids, illustrate affine scoring, and follow Myers' furthest-reaching paths on the edit graph. Compare fixed blocks, rolling checksums and content-defined chunks after a 24-byte insertion. Draw periods, borders and Lyndon factorizations; scope the palindrome query to its exact normalization/filter.
  • Compare full BWT run counts for equal-length texts. Explain dated repetitive-index results without asserting that a historical open question is still open. Explicit witness bars show two equal 428-byte intervals and the first unequal byte, alongside the complete-search certificate needed to establish a maximum.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Matching, naive: about one comparison per character on English (1 + f(p₁) + f(p₁p₂) + ⋯ predicts the measured cost to four decimals); the worst case (n − m + 1)m, 99 million comparisons at n = 10⁵, m = 10³.
  2. Rabin–Karp (1987): the rolling window animated on digits (one hit, one spurious); collisions ≤ (m − 1)/p by Schwartz–Zippel; Queequeg in Moby-Dick with moduli from 101 (12,042 false alarms against n/p = 12,056) to 10⁹.
  3. KMP (1977): borders and the shift animated; the failure table as Part 12's automaton, run over a text; ≤ 2n comparisons (proved, amortized); the worst case of chapter 1 in 199,901 comparisons.
  4. Boyer–Moore (1977): compare from the right; bad character and good suffix (ANPANMAN, a shift of 6); comparisons per character against pattern length on Moby-Dick (KMP ≈ 1, Boyer–Moore ≈ 1/m, Horspool on top); Queequeg in 3,500,231 comparisons; why grep is fast.
  5. Aho–Corasick (1975): the trie of he, she, his, hers with failure links built level by level; 45 character names in one pass over the corpus (231 states, 25.5 million steps, against 1.1 billion characters read separately).
  6. Suffix trees: banana$ and a walk for ana; Ukkonen's suffix links and open leaves drawn on the tree; the deepest branching node; Moby-Dick's 741 billion distinct substrings; 10–20 bytes per character.
  7. Suffix arrays (Manber & Myers 1990): sorted suffixes and the block for t; prefix doubling as a rank table on banana$; SA-IS and Kasai's LCP; all 24,971,556 suffixes of the novels in 105 s (100 MB); Queequeg's 253 in 167 comparisons; the longest repeat (428 characters of chapter headings).
  8. The Burrows–Wheeler transform (1994): rotations sorted; LF arrows walking banana$ back out (proved; all of Moby-Dick inverted exactly); what precedes he, hi and ho in Moby-Dick (72% t before he); nH_k for every k (Manzini 2001); 578,682 runs, move-to-front, bzip2 against zlib.
  9. The FM-index (Ferragina & Manzini 2000): backward search for ana; wavelet trees and Jacobson's rank; the novels indexed (counts in a fraction of a millisecond; our teaching index larger than the text, bzip2 of L 7.1 MB).
  10. Compression, part one: LZ77 arcs over A Tale of Two Cities; DEFLATE's alphabets, buckets and lazy matching; an LZ78 parse drawn; Ziv–Lempel universality; our LZ77 + Huffman within 6% of zlib -9 on three novels, against LZW, bzip2 and xz.
  11. Compression, part two: Huffman's whole bits against skewed sources (rANS 0.287 against 0.286 bits at p = 0.95); ANS (Duda) worked on four symbols; H₀, H₁, H₂ = 4.44, 3.48, 2.81 bits: compression is prediction; zstd.
  12. Alignment: Needleman–Wunsch on intention/execution with its traceback; Smith–Waterman lining up two versions of the Monte Cristo letter word for word (90,000 cells, score 322); Gotoh's three tables; BLAST and seeds; no O(n^{2−ε}) edit distance under SETH (Backurs & Indyk 2015; Part 27).
  13. Myers' diff (1986): the edit graph of ABCABBA against CBABAC; the furthest-reaching D-paths drawn for D = 0 … 5; patience diff, three-way merge; every revision of this syllabus diffed (all minimal; git's --minimal 2–4 lines longer on 8 of 26).
  14. rsync and chunking: 24 bytes inserted into Moby-Dick (297 of 595 fixed blocks survive); rsync's rolling checksum (593 blocks found, 3,257 literal bytes); content-defined chunks drawn (120 chunks, one new, 14 KB).
  15. Periodicity: Fine–Wilf with periods 5 and 8 drawn (tight at 11); Manacher over 19.4 million letters (able was I ere I saw Elba, Lenehan in Ulysses); Lyndon words and Duval.
  16. Frontier: BWT runs drawn for the novels against 27 versions of this syllabus (n/r = 2.3 against 48; xz 63×); the r-index (Gagie, Navarro & Prezza 2018); r = O(z log² n) (Kempa & Kociumaka 2020); the quadratic wall and its escapes; open problems. Outro.

Computed: every number above, in videos/cs/cs21/compute.py with explainer/cs/algo/strings.py (tested in tests/test_cs21_strings.py): every matcher's comparisons on the novels; Aho–Corasick over the corpus; the suffix array, LCP and longest repeats of all 25 MB; the BWT of Moby-Dick inverted, its runs, MTF entropy and contexts; the FM-index of the novels; our LZ77 + Huffman, LZW and rANS against zlib, bzip2 and xz; Smith–Waterman on the Monte Cristo letters; Myers' diff on this file's history, checked against LCS and git; rsync and content-defined chunking; Manacher over the corpus; BWT runs of the syllabus versions. Visuals: the KMP shift and automaton; Boyer–Moore's skips; the Aho–Corasick trie and its links; suffix trees with suffix links; the BWT's rotation matrix and LF arrows; context bars; the wavelet tree; LZ back-references as arcs; the ANS state table; alignment tables with tracebacks; Myers' D-paths in the edit graph; fixed blocks against content-defined chunks; BWT run strips. In practice: grep and ripgrep, gzip, zstd and bzip2, genome alignment, git diff, rsync and deduplicating backups. Reading: Gusfield, Algorithms on Strings, Trees, and Sequences; Crochemore, Hancart & Lecroq, Algorithms on Strings; Mäkinen, Belazzougui, Cunial & Tomescu, Genome-Scale Algorithm Design; Navarro, Compact Data Structures; Salomon & Motta, Handbook of Data Compression; Knuth, Morris & Pratt 1977; Burrows & Wheeler 1994; Ferragina & Manzini 2000; Ziv & Lempel 1977–78; Myers 1986; Gagie, Navarro & Prezza 2018.

中文讲义

本讲的中文部分(与英文版对应)。

习题与解答
  1. KMP。 令文本位置为 i、已匹配前缀长度为 j,起点 s=i−j。每次比较增加 i,或在失配回退时增加 s; 两者单调且至多 n,因此比较至多 2n 次。失配预处理用相同的单调记账,耗时 O(m)。所有较短候选边界必为 上一个最长边界的边界,因此沿失配链不会漏掉候选。
  2. LF。 假设只有一个唯一最小结束标记。对字符 c 的各次出现,F 中以 c 开头的行按其后旋转排序;L 中 以 c 结束的对应行有相同相对顺序。因此第 k 个 c 对应第 k 个 c,LF(i)=C[c]+rank_c(L,i),rank 不含位置 i。 LF 把起点循环向前移一字节;唯一结束标记确定原始行,走 n 步输出逆序文本。无唯一标记或不是有效单环的输入会被拒绝。
  3. 不同子串。 后缀 SA[i] 有 n−SA[i] 个前缀,其中前 LCP[i] 个已经出现。若更早后缀共享更长前缀,排序区间 中间的后缀也必须共享它,与 LCP 定义矛盾。求和得 n(n+1)/2−ΣLCP。n 应为原文长度,不含人工结束标记; banana 有 15 个不同非空子串。《白鲸》为 741,383,838,433。把人工标记当原文字节会多算。
  4. Fine–Wilf。 对 p+q 归纳,p>q,g=gcd(p,q)。若 q 整除 p 则已成立;否则长度 n−q 的前缀同时有周期 q 和 p−q,因为 s[i]=s[i+p]=s[i+p−q]。前缀长度达到归纳门槛 p−g,故有周期 g。又因 n≥2q,余下每个位置均有 前缀内的 q 步前驱,而 g 整除 q,周期 g 可延伸到整串。长度 11 的 abaababaaba 有周期 5、8,却无周期 1;门槛是 12。
  5. 构建。 已完成的 Python 原型保留 m 字节环形缓冲与 256 项位移表,右到左比较,再读入位移数量的新字节。 跳过比较不等于跳过输入。小例子穷举与三种输入分块通过;完整语料读入 24,971,555 字节,找回全部 253 个位置。 Pebble 移植须处理不完整末窗,并先核验完整输出,再实测模拟器指令数。本部分没有提供或声称已执行 Pebble 移植, 不能从比较次数直接预测每字节指令数。
  6. 研究。 固定输入族、顺序、分隔符与结束标记,分别测实际空间、构造、计数、定位,并核验完整输出。 等长实验中历史与小说的 r 分别是 150,581 与 5,800,029;xz 的 117,040 字节输出不是可搜索索引。 阅读有日期的一手论文,记录字长、字母表、随机性与查询假设,再扩展规模系列并构建真正索引。 声称问题尚未解决之前,必须检查更新工作。

Build the film

python -m videos.cs.cs21.compute        # the part's numbers, into .cache/cs21
python tools/build.py cs21                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs21 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/cs/cs21. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
source /workspace/environment/activate.sh
PYTHONPATH=. .venv/bin/python -m unittest discover -s tests -p test_cs21_strings.py -v
PYTHONPATH=. OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 .venv/bin/python -m videos.cs.cs21.compute sa --force
PYTHONPATH=. OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 .venv/bin/python -m videos.cs.cs21.compute --force
PYTHONPATH=. .venv/bin/python tools/build.py cs21 -q l

Preview QA records and numerical/native reference code live in the workspace evidence packet docs/qa/evidence/cs21-polish-20261110/. Source/preview checks do not certify continuous narrated listening, Chinese synthesized speech/listening, whole-video native production, or production runtime at the chosen pace.