|
ADS
Algorithms and Data Structures
|
The headers of include/ADS/string realize the algorithms on strings of chapters 13 and 14 of the book (the approximate matching, the longest common subsequence, the alignments, the segmentations and the code of Huffman, all by dynamic programming or by a greedy choice) and, beyond the book, those of chapters 9, Searching Strings by Prefix, and 10, Searching Strings by Substring, of Ferragina's book and of the papers that the headers cite, i.e., the exact search of one pattern and of many, the edit distance by bit vectors, the dictionaries searched by prefix, the suffix arrays, trees and automata with their applications, and a few classical problems on palindromes, Lyndon words and parentheses. This page collects what the headers take for granted: the definitions and the notation shared by all of them (see Definitions and notation), and, for each family of algorithms, the property on which its correctness rests and the argument behind its bound (from The search of one pattern to Segmentations, cuts and the code of Huffman). The pseudocode of each algorithm is instead on the page of its header, in the comment of its function, together with the section of the book, or the paper, that it follows.
An alphabet \( \Sigma \) is a finite set of \( \sigma \) symbols with a total order, the bytes of a std::string_view ( \( \sigma \le 256 \)) or the integers in \( [ 0 , K ) \) of a vector of Symbols, and a string \( T = T[ 0 .. n - 1 ] \) of length \( n = |T| \) is a sequence of \( n \) symbols, the places counting from 0 as in the code (the book and Ferragina's book count from 1, and the headers say where they translate). The string \( T[ i .. j ] \), for \( 0 \le i \le j < n \), is a substring of \( T \), a prefix if \( i = 0 \) and a suffix if \( j = n - 1 \); the suffix that starts at \( i \) is called the suffix \( i \), \( T[ i .. ] \) for short, and the prefix of \( i \) symbols of the book is \( T( i ) = T[ 0 .. i - 1 ] \). A subsequence keeps some of the symbols in their order, not necessarily contiguous. Two strings are compared in the lexicographic order, a string that is a prefix of another being the smaller; the terminator \( \$ \) that some structures append is a symbol smaller than all the others, so that no suffix of \( T \$ \) is a prefix of another.
| Symbol | Meaning |
|---|---|
| \( T \), \( n \); \( P \), \( m \) (or \( p \)) | the text and its length; the pattern searched in it and its length, \( P_0 , \ldots , P_{k-1} \) for several patterns of \( M \) symbols in all |
| \( \mathrm{Occ}( P , T ) \), \( \mathit{occ} \) | the places \( s \in [ 0 , n - m ] \) with \( T[ s .. s + m - 1 ] = P \), and their number |
| \( \mathrm{lcp}( x , y ) \), \( \mathrm{lce}( i , j ) \) | the length of the longest common prefix of two strings, and that of the suffixes \( i \) and \( j \) of one text, their longest common extension |
| \( \mathit{SA} \), \( \mathit{SA}^{-1} \), \( \mathit{LCP} \) | the suffix array, \( \mathit{SA}[ r ] \) the start of the \( r \)-th smallest suffix; its inverse, the rank of each suffix; and \( \mathit{LCP}[ r ] = \mathrm{lcp}( T[ \mathit{SA}[ r ] .. ] , T[ \mathit{SA}[ r + 1 ] .. ] ) \), \( n - 1 \) entries |
| \( F[ q ] \) | the failure function of \( P \), the length of the longest proper border of \( P[ 0 .. q - 1 ] \), a border being a string that is both a prefix and a suffix |
| \( D[ i ][ j ] \), \( \mathit{DP}[ i ][ j ] \) | the table of a dynamic programming on the prefixes of \( i \) symbols of the first string and of \( j \) of the second; \( \delta_{ij} \) is 0 (or \( +1 \) in a score) when the symbols \( i - 1 \) and \( j - 1 \) are equal |
| \( d \), \( k \) | the edit distance of two strings, and a bound on it, i.e., the errors (or the mismatches) allowed |
| \( w \) | the length of a machine word, 64 bits, by which the bit-parallel algorithms divide their work |
The edit distance (of Levenshtein) of two strings is the least number of substitutions, insertions and deletions of single symbols that turn one into the other. A period of \( P \) is an integer \( q > 0 \) with \( P[ i ] = P[ i + q ] \) wherever both are defined; \( q \) is a period if and only if \( P[ 0 .. m - q - 1 ] \) is a border, and the smallest period is \( m - F[ m ] \).
The problem is to find \( \mathrm{Occ}( P , T ) \). Trying every shift costs \( O( n m ) \) comparisons (naiveMatching() of StringMatching.h), and the algorithms differ in how much they learn from a comparison and how far they then move the pattern.
Lemma 1 (the failure function). If \( P[ 0 .. q - 1 ] \) matches the text up to the place \( j - 1 \) and \( P[ q ] \ne T[ j ] \), no occurrence starts at a place \( s \) with \( j - q < s < j - F[ q ] \), and the next candidate has \( P[ 0 .. F[ q ] - 1 ] \) already matched, i.e.,
\[ q \gets F[ q ] \quad \text{and } T[ j ] \text{ compared again with } P[ q ] . \tag{1} \]
Indeed, an occurrence that starts at \( j - q + s \) with \( 0 < s < q - F[ q ] \) would make \( P[ 0 .. q - s - 1 ] \) a border of \( P[ 0 .. q - 1 ] \) longer than \( F[ q ] \). The algorithm of Knuth, Morris and Pratt (kmp()) applies (1) at each mismatch, and each comparison either advances \( j \), which happens at most \( n \) times, or moves the start \( j - q \) of the pattern forward, which also happens at most \( n \) times; hence at most \( 2 n \) comparisons, and the same argument on \( P \) against itself computes \( F \) in \( O( m ) \). The strong failure function of Knuth (kmpStrong()) skips a border whose next symbol is the one that just failed, so that a symbol of \( T \) is never compared twice with the same symbol of \( P \).
The Z-function \( Z[ i ] = \mathrm{lcp}( S , S[ i .. ] ) \) (zFunction()) rests on the same reuse: inside the box \( [ l , r ) \) that reaches farthest, \( S[ i .. r - 1 ] \) equals \( S[ i - l .. r - l - 1 ] \), and hence \( Z[ i ] \ge \min( Z[ i - l ] , r - i ) \); only the symbols past \( r \) are compared, each successful comparison moves \( r \) forward, and each \( i \) fails at most once, which gives \( \Theta( n ) \). The bit-parallel Shift-Or (shiftOr()) keeps in one word \( D \) the prefixes of \( P \) that end at the current symbol, the bit \( i \) clear when \( P[ 0 .. i ] = T[ j - i .. j ] \), and updates them for all \( i \) at once by
\[ D \gets ( D \ll 1 ) \vee B[ T[ j ] ] , \tag{2} \]
the bit \( i \) of \( B[ c ] \) clear when \( P[ i ] = c \), since \( P[ 0 .. i ] \) ends at \( j \) exactly when \( P[ 0 .. i - 1 ] \) ends at \( j - 1 \) and \( P[ i ] = T[ j ] \); an occurrence ends at \( j \) when the bit \( m - 1 \) is clear, \( \Theta( n ) \) word operations for \( m \le w \).
The algorithm of Boyer and Moore (boyerMoore()) compares the window from right to left, and on a mismatch moves it by the larger of two safe shifts: the bad character rule aligns the symbol of \( T \) that failed with its last place in \( P \), and the strong good suffix rule aligns the suffix already matched with its previous occurrence in \( P \) preceded by another symbol (or with the longest prefix of \( P \) that is its suffix). A shift is safe because any smaller one would put a different symbol under a symbol of \( T \) already read. When the symbols of \( T \) seldom occur in \( P \), the window moves by about \( m \) after a few comparisons, \( O( n / m ) \) comparisons at best; the worst case is \( O( n m ) \) for all the occurrences (each of the \( n - m + 1 \) windows of \( a^m \) in \( a^n \) is read whole). Horspool (horspool()) keeps only the bad character of the last symbol of the window, which is simpler and often faster on large alphabets.
Theorem 2 (the critical factorization). Every pattern with \( m \ge 2 \) can be cut as \( P = u v \) with \( |u| \) smaller than the period of \( P \), so that the local period at the cut, the least \( q \) such that \( u \) and \( v \) agree with a shift of \( q \) around it, equals the period of \( P \); the cut is found from the two maximal suffixes of \( P \) for an order of the symbols and its reverse (Crochemore and Perrin, after Césari and Vincent).
The Two-Way algorithm (twoWay()) compares \( v \) from left to right and then \( u \) from right to left: a mismatch in \( v \) at the place \( i \) moves the window by \( i - |u| + 1 \), each symbol of \( T \) read in \( v \) being left behind, and a mismatch in \( u \) moves it by the period, the prefix of the period known to match being remembered when \( P \) is periodic. By Theorem 2 neither shift passes an occurrence; it makes at most \( 2 n \) comparisons in \( O( 1 ) \) extra space, which is why the engineered StringSearcher of StringSearch.h falls back on it once its filters have compared more than \( 16 n + 4096 \) bytes.
| Function | Preparation | Search, worst case | Remarks |
|---|---|---|---|
| naiveMatching() | none | \( O( n m ) \) | \( O( n ) \) expected on random texts |
| kmp(), kmpStrong() | \( O( m ) \) | at most \( 2 n \) comparisons | reads \( T \) forward, never backs up |
| boyerMoore(), horspool() | \( O( m + \sigma ) \) | \( O( n m ) \) | \( O( n / m ) \) comparisons at best |
| shiftOr() | \( O( m + \sigma ) \) | \( \Theta( n ) \) word operations | \( m \le 64 \) |
| zMatching() | \( O( m ) \) | \( \Theta( n + m ) \) | the Z-boxes of \( T \) against \( P \) |
| twoWay() | \( O( m ) \) | at most \( 2 n \) comparisons | \( O( 1 ) \) extra space |
| StringSearcher | \( O( 256 + m ) \) | \( O( n + m ) \) | filters of probes or of q-grams, about \( n / m \) windows on random texts |
The automaton of Aho and Corasick (AhoCorasick.h) generalizes Lemma 1 to \( k \) patterns: its states are the nodes of the trie of the patterns, each the string \( u \) spelt from the root, and the failure of \( u \) is the state of the longest proper suffix of \( u \) that is in the trie.
Lemma 3 (the invariant of the automaton). After the automaton has read \( T[ 0 .. j ] \), its state is the longest suffix of \( T[ 0 .. j ] \) that is a prefix of some pattern, and the patterns that end at \( j \) are the suffixes of that state that are patterns.
Indeed, if \( u \) is the state after \( T[ 0 .. j - 1 ] \), every suffix of \( T[ 0 .. j ] \) that is a prefix of a pattern is \( x c \) with \( c = T[ j ] \) and \( x \) a suffix of \( u \) in the trie, and the chain \( u , \mathit{fail}( u ) , \ldots \) lists those suffixes by decreasing length; the transition \( \delta( u , c ) \) takes the first of them that goes on with \( c \). With the transitions tabulated for every symbol a byte of \( T \) costs one lookup, and the output links (each to the nearest proper suffix of a state that is a whole pattern) list the occurrences that end at \( j \) at \( O( 1 ) \) each; hence \( O( n + \mathit{occ} ) \) time after a preparation of \( O( \sigma M ) \), the failures computed in breadth first order from \( \mathit{fail}( u c ) = \delta( \mathit{fail}( u ) , c ) \). The engineered MultiSearcher of MultiSearch.h puts filters in front of it, by the shuffles of the halves of the bytes or by a shift-or on super characters, which let through every occurrence and few other places; it checks the candidates directly and gives the text to the automaton when the bytes compared with the patterns exceed \( 16 s + 4096 \) at the place \( s \), as StringSearcher does; since the bytes, not the checks, are counted, a check of a long pattern counts all that it compares, and the worst case is \( O( n + M + \mathit{occ} \log \mathit{occ} ) \), \( M \) the total length of the patterns (the bytes of the last block before the switch) and the last term for sorting the occurrences.
The problems of chapter 13 of the book compare two strings, \( P \) of \( m \) symbols and \( T \) of \( n \), by a table on their prefixes. The edit distance of editDistance() of ApproximateMatching.h is
\[ D[ i ][ j ] = \min\{ D[ i - 1 ][ j - 1 ] + \delta_{ij} , D[ i - 1 ][ j ] + 1 , D[ i ][ j - 1 ] + 1 \} , \tag{3} \]
with \( D[ i ][ 0 ] = i \) and \( D[ 0 ][ j ] = j \), since the last column of an optimal sequence of edits aligns \( P[ i - 1 ] \) with \( T[ j - 1 ] \), or deletes one of the two, and what precedes it is an optimal sequence for the shorter prefixes; the table costs \( \Theta( m n ) \) time, and two rows suffice for the value, which is all that editDistance() returns, its rows on the shorter string (\( O( \min( m , n ) ) \) space), as stringMatchingSingleRow() does for the approximate matching. With \( D[ 0 ][ j ] = 0 \) instead, an occurrence may start anywhere in \( T \), and \( D[ m ][ j ] \) is the least number of errors of an occurrence of \( P \) that ends at \( j \) (stringMatching(), the approximate matching of section 13.1, after Sellers). The same scheme with a maximum gives the longest common subsequence of LongestCommonSubsequence.h (section 13.7),
\[ \mathit{DP}[ i ][ j ] = \left\{ \begin{array}{ll} \mathit{DP}[ i - 1 ][ j - 1 ] + 1 & P[ i - 1 ] = T[ j - 1 ] , \cr \max\{ \mathit{DP}[ i - 1 ][ j ] , \mathit{DP}[ i ][ j - 1 ] \} & \text{otherwise,} \end{array} \right. \tag{4} \]
since a common subsequence either uses both last symbols, when they are equal (and then some longest one does, by an exchange), or leaves out one of them; and the alignments of Alignment.h (exercises 13.7 to 13.9), whose score is the maximum of \( \mathit{DP}[ i - 1 ][ j - 1 ] + \delta_{ij} \) and of \( \mathit{DP}[ i - 1 ][ j ] - 2 \) and \( \mathit{DP}[ i ][ j - 1 ] - 2 \), global with the borders \( -2 i \) and \( -2 j \) (Needleman and Wunsch), semiglobal with the borders 0 and the best of the last row and column, local with 0 as a fourth term of the maximum and the best entry (Smith and Waterman). A solution, not only its value, is read back from the table by following, from the last entry, a term that gave the maximum or the minimum, in \( O( m + n ) \) steps (lcs(), diff(), globalAlignment()).
The relatives of SubsequenceProblems.h follow from (4). A shortest common supersequence of \( X \) and \( Y \) writes the items of a longest common subsequence once and the others in their order, hence its length \( |X| + |Y| - | \mathrm{LCS}( X , Y ) | \); the occurrences of \( P \) as a subsequence of \( T \) add, at each symbol of \( T \) equal to \( P[ j - 1 ] \), the occurrences of \( P[ 0 .. j - 2 ] \) before it; and three strings need the table in three dimensions, \( \Theta( n m l ) \), since a longest common subsequence of two of them may leave out the items that the third shares. The problems on an unbounded number of strings are NP-hard (Maier; Mansfield for the shuffle).
The engineered algorithms of EditDistance.h rest on two properties of (3).
Lemma 4 (the differences of the table). Two adjacent entries of (3), in a row or in a column, differ by \( -1 \), 0 or \( +1 \), and along a diagonal the entries never decrease,
\[ D[ i ][ j ] - D[ i - 1 ][ j ] \in \{ -1 , 0 , +1 \} , \qquad D[ i - 1 ][ j - 1 ] \le D[ i ][ j ] . \tag{5} \]
The first holds since an alignment of \( P( i - 1 ) \) with \( T( j ) \) becomes one of \( P( i ) \) by one more edit, and back, and likewise for \( T \); the second follows from the first, since each term of (3) is at least \( D[ i - 1 ][ j - 1 ] \), e.g., \( D[ i - 1 ][ j ] + 1 \ge D[ i - 1 ][ j - 1 ] \) by a horizontal difference. By the first, a column is determined by its top entry and the vertical differences, two bit vectors \( P_v \) and \( M_v \) of \( m \) bits, and Myers moves them to the next column by a constant number of operations on words, the carries of one addition propagating the horizontal differences down the column; hence \( O( n \lceil m / w \rceil ) \) time for the distance and for the search (levenshtein(), approximateMatches()), and the bit-parallel LCS of Allison and Dix in the same bound (lcsLength()). By the second part, a cell of value at most \( k \) has one of value at most \( k \) on its diagonal in the column before; hence the last row of value at most \( k \) goes down by at most one row per column, and the search of \( k \) errors needs only the blocks down to the last one with a cell of value at most \( k + 1 \) at its bottom (the cut-off of Ukkonen), \( O( n k / w ) \) expected on random texts. The distance, finally, crosses only the diagonals \( i - j \in [ -d , d - ( n - m ) ] \), each step off the main diagonal costing 1, and doubling a guess \( t \) of \( d \) until the band of \( t \) gives a value at most \( t \) costs \( O( n d / w ) \) blocks in all, a geometric sum.
By the second part of (5) the furthest row \( F_h( k ) \) of the diagonal \( k = j - i \) that \( h \) edits reach determines the table: it is the row reached by sliding along the matches of the diagonal from the best of the three cells that one more edit reaches,
\[ F_h( k ) = \mathit{slide}_k( \max\{ F_{h-1}( k ) + 1 , F_{h-1}( k + 1 ) + 1 , F_{h-1}( k - 1 ) \} ) , \tag{6} \]
and the distance is the least \( d \) with \( F_d( n - m ) = m \) (the diagonal transitions of Landau and Vishkin, the furthest reaching paths of Myers). The rounds \( h \le d \) handle \( O( d ) \) diagonals each, and the slides of one diagonal never go back, so that the time is \( O( ( n + m ) d ) \) in the worst case, \( O( n + d^2 ) \) expected on random strings, and \( O( n + d^2 ) \) in the worst case when each slide is a query of longest common extension in \( O( 1 ) \) (see Suffix arrays, trees and automata).
| Function | Time | Space | Remarks |
|---|---|---|---|
| lcs() | \( \Theta( m n ) \) | \( \Theta( m n ) \) | the table of the book, a solution read back |
| editDistance() | \( \Theta( m n ) \) | \( O( \min( m , n ) ) \) | two rows on the shorter string, the value alone |
| stringMatchingSingleRow() | \( \Theta( m n ) \) | \( O( n ) \) | two rows, the value alone |
| levenshtein() | \( O( n \lceil m / w \rceil ) \), about \( O( n d / w ) \) | \( O( m / w + \sigma \lceil m / w \rceil ) \) | the diagonals (6) for small \( d \), then the band of Ukkonen |
| approximateMatches() | \( O( n \lceil m / w \rceil ) \), \( O( n k / w ) \) expected | as above | the cut-off of Ukkonen |
| lcsLength() | \( O( n \lceil m / w \rceil ) \) | as above | Allison and Dix |
The suffixes of \( T \) hold all its substrings as their prefixes, and the three indexes of this section sort them, or merge their common prefixes, so that a pattern is searched in time that depends on \( m \) rather than on \( n \).
Lemma 5 (the range of a pattern). The suffixes prefixed by \( P \) are consecutive in \( \mathit{SA} \): they are the suffixes not smaller than \( P \) and smaller than \( P \# \), \( \# \) a symbol larger than all the others.
Indeed, the strings prefixed by \( P \) are exactly those between \( P \) and \( P \# \) in the lexicographic order. Hence two binary searches give the range (range() of SuffixArray.h), each step a comparison of \( P \) with a suffix, \( O( m \log n ) \) time, and the occurrences are then listed in \( O( \mathit{occ} ) \). The search of Manber and Myers (rangeLcp()) keeps the lcp \( l \) and \( r \) of \( P \) with the suffixes at the two ends of the range, and stores for the middle of each range of the search its lcp with the two ends (\( \mathit{Llcp} \) and \( \mathit{Rlcp} \), \( 2 n \) integers); if, e.g., \( l \ge r \) and \( \mathit{Llcp} \) of the middle differs from \( l \), the side is decided with no comparison, and otherwise the comparison starts from \( \max( l , r ) \). That maximum never decreases, each equal symbol increases it and each step ends at the first different one; hence \( O( m + \log n ) \) comparisons.
Lemma 6 (Kasai et al.). If the suffix \( i \) has lcp \( h > 0 \) with the suffix before it in \( \mathit{SA} \), then the suffix \( i + 1 \) has lcp at least \( h - 1 \) with the suffix before it in \( \mathit{SA} \):
\[ \mathit{PLCP}[ i + 1 ] \ge \mathit{PLCP}[ i ] - 1 , \tag{7} \]
\( \mathit{PLCP}[ i ] \) being the lcp of the suffix \( i \) with its predecessor in \( \mathit{SA} \).
In fact, if the suffix \( k \) precedes the suffix \( i \) and shares \( h > 0 \) symbols with it, the suffix \( k + 1 \) precedes the suffix \( i + 1 \) and shares \( h - 1 \) symbols with it, and so does every suffix between them in \( \mathit{SA} \). Computing the lcp in the order of the text from the value at \( i - 1 \) less one (lcpArray(), lcpArrayPhi() of SuffixSorting.h) therefore decreases \( h \) at most \( n \) times, and \( h \le n \); hence at most \( 2 n \) comparisons of symbols.
The constructions of the suffix array differ in how they reuse the order of shorter strings. The prefix doubling sorts the suffixes by their prefixes of \( 2^{k+1} \) symbols as the pairs of the ranks of two prefixes of \( 2^k \) symbols, each round a radix sort in \( O( n ) \), and \( \lceil \log_2 n \rceil \) rounds suffice. The Skew algorithm sorts recursively the suffixes at the places \( i \bmod 3 \ne 0 \) by the names of their triples, sorts the others by a symbol and the rank of the next suffix, which is in the sample, and merges the two lists in \( O( n ) \) by comparing a pair or a triple that ends in the sample, so that \( T( n ) = T( 2 n / 3 ) + O( n ) = O( n ) \). The induced sorting of SA-IS rests on the following property.
Lemma 7 (the induced sorting). Call the suffix \( i \) of type S if it is smaller than the suffix \( i + 1 \) and of type L otherwise, and LMS if it is of type S and the suffix \( i - 1 \) of type L. If the LMS-suffixes are placed at the ends of the buckets of their first symbols in their sorted order, a scan from left to right that puts each suffix \( i - 1 \) of type L at the head of its bucket, after reading the suffix \( i \), and a scan from right to left that puts each suffix \( i - 1 \) of type S at the tail of its bucket sort all the suffixes.
Indeed, within the bucket of a symbol \( c \) the suffixes of type L come before those of type S, since the first are followed by a run of \( c \) and then a smaller symbol, the second by a larger one; and two suffixes \( i - 1 \) and \( j - 1 \) of type L in one bucket compare as the suffixes \( i \) and \( j \), which the first scan meets in their order, by induction on the scan, since each is smaller than the suffix before it. The second scan does the same for the type S, from the largest down. The LMS-substrings (from an LMS place to the next one) are sorted by the same two scans; if two of them are equal, their names form a string of at most \( n / 2 \) symbols, two LMS places never being adjacent, whose suffix array orders the LMS-suffixes; hence \( T( n ) \le T( n / 2 ) + O( n ) = O( n ) \).
| Function | Time | Remarks |
|---|---|---|
| suffixArraySorting() | \( O( n^2 \log n ) \), near \( O( n \log^2 n ) \) on random texts | a sort of comparisons, each as long as an lcp |
| suffixArrayDoubling() | \( O( n \log n ) \) | Manber and Myers, a radix sort of pairs of ranks a round |
| suffixArrayLarssonSadakane() | \( O( n \log^2 n ) \) here, \( O( n \log n ) \) with a ternary quicksort | only the groups still tied are sorted |
| suffixArraySkew() | \( O( n ) \) | the recursion on \( 2 n / 3 \) suffixes; optimal I/Os on disk |
| suffixArraySais() | \( O( n ) \) | Lemma 7, the recursion on at most \( n / 2 \) suffixes |
| suffixArray() | \( O( n \log n ) \), \( O( n ) \) by the radix sorts and the recursion | SA-IS engineered in SuffixSorting.h, the ties sorted by comparisons or by the doubling |
| suffixArrayScan() | \( O( ( n^2 / b ) \log b ) \) comparisons of suffixes | blocks of \( b \) symbols, all its passes sequential |
The suffix tree (SuffixTree.h) is the compact trie of the suffixes of \( T \$ \): it has \( n + 1 \) leaves, and since each internal node but the root has two children or more, at most \( n \) internal nodes; with each label kept as two places of \( T \) it takes \( O( n ) \) space. An internal node spells a substring that occurs twice followed by different symbols, and the lowest common ancestor of the leaves \( i \) and \( j \) spells their longest common prefix; hence \( \mathrm{lce}( i , j ) \) is the string depth of that ancestor, found in \( O( 1 ) \) by the range minima of the depths along an Euler tour (Bender and Farach-Colton), and equivalently the minimum of \( \mathit{LCP} \) between the ranks of the two suffixes. McCreight's construction inserts the suffixes from the longest one, and starts the walk of the suffix \( i \) from the suffix link of the node of \( \mathit{head}_{i-1} \) (the longest prefix of the suffix \( i - 1 \) that occurs earlier), since \( \mathit{head}_{i-1} \) without its first symbol is a prefix of \( \mathit{head}_i \). The rescan of a link not yet set jumps over whole edges, and the node depth drops by at most 2 at each link, so that its total is \( O( n ) \); the scan compares the symbols past the head, and since \( |\mathit{head}_i| \ge |\mathit{head}_{i-1}| - 1 \) its total is \( O( n ) \) too. With the children in a balanced tree, the time is \( O( n \log \sigma ) \). From \( \mathit{SA} \) and \( \mathit{LCP} \) instead the leaves are inserted in the order of \( \mathit{SA} \), each climbing from the previous leaf to the depth \( \mathit{LCP}[ r - 1 ] \); an edge climbed leaves the rightmost path for good, and the construction is linear.
The suffix automaton (SuffixAutomaton.h) merges instead the substrings with the same set of end places, \( \mathrm{endpos}( u ) = \{ j : T[ j - |u| + 1 .. j ] = u \} \); two such sets are disjoint or nested, so that the classes form a tree, the suffix links, whose leaves are classes of prefixes of \( T \), and it has at most \( 2 n - 1 \) states and \( 3 n - 4 \) transitions (Blumer et al.). A class holds the suffixes of its longest member of lengths in \( ( \mathit{len}( \mathit{link}( v ) ) , \mathit{len}( v ) ] \), which gives the number of distinct nonempty substrings as \( \sum_{v} ( \mathit{len}( v ) - \mathit{len}( \mathit{link}( v ) ) ) \); in terms of the suffix array the same number is
\[ \frac{n ( n + 1 )}{2} - \sum_{r} \mathit{LCP}[ r ] , \tag{8} \]
since the suffix \( \mathit{SA}[ r ] \) adds its prefixes but those it shares with the suffix before it (distinctSubstrings() of SuffixApplications.h). The other applications of that header follow from Lemma 5 and from the constant-time \( \mathrm{lce} \): a substring that occurs \( C \) times is a run of \( C - 1 \) entries of \( \mathit{LCP} \) that are at least its length; the occurrences of \( P \) with at most \( k \) mismatches are checked at each place by at most \( k + 1 \) extensions on the suffix array of \( T \# P \), \( O( n k ) \) (Landau and Vishkin); and the parsing of Ziv and Lempel copies at each place the longest prefix of the suffix that starts earlier, found on the suffix tree by walking down while the least leaf below the next node is smaller than the place. The engineered LceIndex of LongestCommonExtension.h answers the extensions by comparing the first 64 symbols directly, which settles most of them on usual texts, and the others by range minima on blocks of 16 entries of \( \mathit{LCP} \), in \( O( 1 ) \) with two reads of memory in a row.
By Lemma 5 applied to a sorted array of \( n \) strings, the strings prefixed by \( P \) are those between the lexicographic positions of \( P \) and of \( P \# \) (prefixRange() of PrefixSearch.h), two binary searches of \( O( m \log n ) \) time and of \( O( ( m / B ) \log n ) \) transfers of blocks of \( B \) symbols, a string far from the others being read at each step. The front coding of FrontCoding.h stores each string as the length \( \ell_i \) of its lcp with the string before and the rest of it, and decodes a string from the last one stored whole (an anchor); an anchor every \( b \) strings bounds the scan of a decoding, and the search becomes a binary search on the anchors and the scan of one bucket (a two-level scheme, whose first level is small enough to stay in memory). The locality-preserving front coding of Bender, Farach-Colton and Kuszmaul stores \( s_i \) whole when the anchor before it is more than \( c | s_i | \) characters back: the decoding then reads at most \( ( c + 1 ) | s_i | \) characters, and the anchors cost at most a factor \( 1 + 2 / ( c - 2 ) \) on the space of the front coding, since each anchor is paid by the \( c | s_i | \) characters coded before it, as Bender, Farach-Colton and Kuszmaul prove; the time of a decoding thus controls the space. The rear coding of Ferragina, Grossi, Gupta, Shah and Vitter (rearCode() of RearCoding.h) writes \( r_i = | s_{i-1} | - \ell_i \), the characters to take off the end of the string before, in place of \( \ell_i \): the same information, but a smaller number where the prefixes shared are long, and fewer bytes in a code of variable length. RearCodedDictionary is the front coding with buckets of Martínez-Prieto, Brisaboa, Cánovas, Claude and Navarro in the rear coding, entropy-coded as their HTFC: one string of bits (the first string of a bucket past its 16 bytes below, then \( r_i \), \( | \hat s_i | \) and the rest \( \hat s_i \) of each string), the characters, the rears and the lengths each in a canonical code of Huffman of its own frequencies, of codewords of at most 11 bits decoded by a table (and up to 3 characters at a time by a second one), the places of the buckets by Elias-Fano, and the 16 bytes after the prefix common to all the strings of the first string of each bucket kept in two words, so that the binary search decodes a first string only when those bytes do not decide. Its scan of a bucket compares a string with the pattern \( Q \) only when it must: with \( \lambda \) the prefix that the current string shares with \( Q \) and the current string smaller than \( Q \), a next string that keeps more than \( \lambda \) characters of it has the same character at the place \( \lambda \), which is below the one of \( Q \), and is smaller than \( Q \) as well; only a string that keeps at most \( \lambda \) characters is compared, from the place where its rest begins, while that rest is decoded, and no string is rebuilt. The search by bins of Demaine, Jones and Pătrașcu (BinnedSearch) cuts the range of \( m \) sorted integers into \( m \) bins of equal width; a bin is at most as wide as the largest gap, and hence holds at most \( \Delta \) items, \( \Delta \) the ratio of the largest gap to the smallest, which bounds a search by \( O( \log \min( \Delta , m ) ) \).
A palindrome reads the same in both directions. The algorithm of Manacher (longestPalindromicSubstring() of Palindromes.h) computes the radius of the longest palindrome about each of the \( 2 n - 1 \) centers, and keeps the palindrome found so far whose right end \( r \) is the largest: a center inside it starts from the radius of its mirror, capped at \( r \), since the palindrome is symmetric, and compares only the symbols past \( r \); each successful comparison moves \( r \) forward, so that the time is \( \Theta( n ) \). The longest palindromic subsequence is the longest common subsequence of \( s \) and of its reverse, by (4). The eertree (Eertree) has a node per distinct nonempty palindrome, and there are at most \( n \) of them, since a symbol added at the end creates at most one new palindrome, the longest palindromic suffix (a shorter one is a suffix of it, and hence its mirror, a prefix, occurred before); the lengths of the palindromic suffixes of a prefix form \( O( \log n ) \) arithmetic series, which gives the fewest palindromes of a factorization in \( O( n \log n ) \) (palindromicFactorization()).
Theorem 8 (Chen, Fox and Lyndon). A Lyndon word is a nonempty string strictly smaller than all its proper suffixes; every string has exactly one factorization
\[ S = w_1 w_2 \cdots w_k , \qquad w_1 \ge w_2 \ge \cdots \ge w_k , \tag{9} \]
into Lyndon words.
The algorithm of Duval (lyndonFactorization() of Lyndon.h) keeps the unfactored part as \( w^h w' \), \( w \) a Lyndon word and \( w' \) a proper prefix of it, and compares the next symbol with the one \( |w| \) places before: an equal one extends \( w' \), a larger one makes the whole part a Lyndon word, and a smaller one outputs the \( h \) copies of \( w \), which are factors of (9). Each comparison either advances the scan or comes with the output of factors at least as long as the symbols scanned again, hence \( O( n ) \) time; the least rotation of \( S \) starts where the factor of \( S S \) that covers the place \( n \) starts. The longest balanced subsequence of parentheses (Parentheses.h) matches each close with the nearest open still unmatched, which an exchange shows to lose no pair, and the longest balanced substring ending at a close starts after the open still unmatched below it on a stack, both in \( \Theta( n ) \). Two words are anagrams when their symbols sorted are equal, which gives a canonical signature for the hashing of anagramGroups() of Anagrams.h.
A string \( s \) is a sequence of words of a dictionary if and only if some prefix \( s[ 0 .. j ) \) is and \( s[ j .. i ) \) is a word for \( i = n \) (exercise 13.13), which wordBreak() of WordBreak.h fills for every \( i \); the number of the segmentations adds, instead, the counts of the words that start at each place (countSegmentations() of Segmentations.h), and the readings of a string of digits as letters are its segmentations into the words 1 to 26 (countDecodings()). The cuts of a string of length \( L \) at the places \( w_1 < \cdots < w_n \), each costing the length of the piece it splits, cost at least
\[ D[ i ][ j ] = w_j - w_i + \min_{i < k < j} ( D[ i ][ k ] + D[ k ][ j ] ) , \tag{10} \]
\( w_0 = 0 \) and \( w_{n+1} = L \), \( \Theta( n^3 ) \) in general. The cost \( w_j - w_i \) satisfies the quadrangle inequality as an equality and grows with the interval; hence (Knuth, Yao) the largest optimal split \( K[ i ][ j ] \) lies between \( K[ i ][ j - 1 ] \) and \( K[ i + 1 ][ j ] \), the candidates of the intervals of one length telescope to \( O( n ) \), and StringBreaking.h fills (10) in \( \Theta( n^2 ) \).
The code of Huffman (huffman() of Huffman.h, section 14.4 of the book) builds a prefix code of least expected length by merging, \( n - 1 \) times, the two least frequent characters into a new one of their total frequency. Some optimal tree has the two least frequent characters as sibling leaves at the largest depth, since exchanging them with the leaves there does not increase the cost; and the cost of the tree with the merged character differs from that of the full tree by the sum of their frequencies, a constant; hence, by induction on the number of characters, the greedy choice is optimal, and with a heap it takes \( O( n \log n ) \) time.