|
ADS
Algorithms and Data Structures
|
The headers of include/ADS/dictionary realize the DICTIONARY of chapter 7 of the book, i.e., the table with direct access, the hash functions of section 7.1 and the hash tables of sections 7.2 to 7.4, and, beyond the book, the engineered hash tables, the universal and the perfect hashing, the skip list and the digital search trees of strings. This page collects what the headers take for granted: the definitions and the notation shared by all of them (see Definitions and notation), the realizations and the costs of their operations (see Realizations and their costs), and, for each family, the property on which its correctness rests and the argument behind its bound (from Hash functions and universal hashing to Ordered dictionaries and tries), with the skip lists of chapter 4 of Morin and their exercises (see The skip lists of Open Data Structures). 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.
A DICTIONARY is a univocal relation from a set of keys to a set of values (section 3.2.3 of the book), with the operations lookup(), insert() and remove(); the keys are drawn from a universe \( U \), and the dictionary holds \( n \) of them at a time. When \( U \) is a small interval of integers, the table with direct access (DirectTable.h) keeps a place for each key of \( U \); otherwise a hash function \( H : U \rightarrow \{ 0 , \ldots , m - 1 \} \) maps the keys to the \( m \) places of a table, and two distinct keys \( k \ne k' \) with \( H( k ) = H( k' ) \) make a collision, which the table must resolve, either by lists of overflow (chaining) or by further places of the table itself (open addressing). A function is perfect on a set \( S \) if it has no collision on \( S \), and minimal if moreover \( m = | S | \).
| Symbol | Meaning |
|---|---|
| \( U \), \( S \) | the universe of the keys, and the set of the keys in the dictionary |
| \( n \), \( m \) | the number of the keys, and the number of the places (or of the lists) of a table |
| \( \alpha = n / m \) | the load factor of a table |
| \( h( k ) \), \( H( k ) \) | the hash of a key, a word of the type std::size_t or of 64 bits, and its place in a table of \( m \) places, often \( H( k ) = h( k ) \bmod m \) |
| \( H( k , i ) \) | the \( i \)-th place of the inspection of \( k \) in a table with open addressing, \( 0 \le i < m \) |
| \( I( \alpha ) \), \( S( \alpha ) \) | the expected places examined by an unsuccessful and by a successful search |
| \( \mathcal{H} \) | a class of hash functions from which one is drawn at random |
| \( \sigma \), \( |k| \) | the size of the alphabet of the strings, and the length of the key \( k \) |
A function \( H \) has the simple uniformity if each place receives the same share of the keys, weighted by the probability \( P( k ) \) that the key \( k \) is in the dictionary,
\[ \sum_{k : H( k ) = i} P( k ) = \frac{1}{m} \quad \forall i \in \{ 0 , \ldots , m - 1 \} , \tag{1} \]
which no fixed function guarantees for every distribution of the keys; the analyses of the tables below assume (1), or, more honestly, a function drawn at random from a class (see Hash functions and universal hashing).
The realizations differ in the time of the operations, in the space and in what they offer besides the three operations of the DICTIONARY (the keys in order, a search by prefix, a static set).
| Realization | lookup() | insert(), remove() | Space | Keys in order |
|---|---|---|---|---|
| DirectTable | \( O( 1 ) \) | \( O( 1 ) \) | \( \Theta( | U | ) \) | yes |
| SortedArrayDictionary | \( O( \log n ) \) | \( O( n ) \) | \( \Theta( n ) \) | yes |
| SkipList | \( O( \log n ) \) expected | \( O( \log n ) \) expected | \( \Theta( n ) \) expected | yes |
| IndexedSkipList | \( O( \log n ) \) expected, also by rank | \( O( \log n ) \) expected | \( \Theta( n ) \) expected | yes |
| ChainedHashTable | \( O( 1 + \alpha ) \) expected | \( O( 1 + \alpha ) \) expected, amortized if it restructures itself | \( \Theta( n + m ) \) | no |
| OpenHashTable, CoalescedHashTable, BrentHashTable | \( O( 1 / ( 1 - \alpha ) ) \) expected, \( \alpha < 1 \) | as lookup() | \( \Theta( m ) \) | no |
| FlatHashTable, DenseHashMap | \( O( 1 ) \) expected, \( \alpha \le 7 / 8 \) | \( O( 1 ) \) expected amortized | \( \Theta( m ) \) | no |
| CuckooHashTable, BucketCuckooTable | \( O( 1 ) \) in the worst case | \( O( 1 ) \) expected amortized | \( \Theta( m ) \) | no |
| DLeftHashTable | \( O( d \log \log n ) \) with high probability | as lookup() | \( \Theta( n + m ) \) | no |
| PerfectHashTable (static) | \( O( 1 ) \) in the worst case | none, built in \( O( n ) \) expected | \( \Theta( n ) \) | no |
| Trie, RadixTree | \( O( |k| \log \sigma ) \) | \( O( |k| \log \sigma ) \) | \( O( N ) \), \( O( n ) \) nodes for RadixTree | yes |
| AdaptiveRadixTree | \( O( |k| ) \) | \( O( |k| ) \) | \( O( n ) \) nodes and the keys | yes |
Here \( N \) is the total length of the keys. The table with direct access is preferable when \( | U | \) is of the order of \( n \); the sorted vector when the lookups far outnumber the changes, or the keys are wanted in order; a hash table in every other case, with the engineered tables (FlatHashTable, DenseHashMap, BucketCuckooTable) when the speed counts, since they compare the fingerprints of a whole group of places at once and touch one or two lines of cache per search, against a pointer per cell of the chaining and a cluster to walk of the linear inspection. The cuckoo tables are preferable when the lookups must be fast in the worst case, the perfect hashing when the set is static, and the tries when the keys are strings to be searched by prefix or kept in order.
The functions of section 7.1 (HashFunctions.h) read a key as an integer \( i \) and reduce it to \( \{ 0 , \ldots , m - 1 \} \): by the division, \( i \bmod m \), best with \( m \) a prime far from a power of 2, whose remainder depends on all the bits of \( i \); by the multiplication, \( \lfloor m \, \mathrm{frac}( C i ) \rfloor \), which works with any \( m \) and, for \( C = ( \sqrt{5} - 1 ) / 2 \), spreads the consecutive keys most evenly, since the points \( \mathrm{frac}( C i ) \) for \( i = 1 , 2 , \ldots \) always fall in the largest gap left by the previous ones (section 6.4 of TAOCP); and by the extraction, the XOR and the middle square of blocks of bits. A fixed function, however good, has a set of \( n \) keys that it sends into one place, when \( |U| \ge n m \) (by the pigeonhole principle); hence the bounds in the worst case of the input need a function drawn at random after the keys are fixed.
A class \( \mathcal{H} \) of functions \( U \rightarrow \{ 0 , \ldots , m - 1 \} \) is universal if
\[ \Pr_{H \in \mathcal{H}}[ H( k ) = H( k' ) ] \le \frac{1}{m} \quad \forall k \ne k' \in U , \tag{2} \]
and \( c \)-universal with \( c / m \) in place of \( 1 / m \) (UniversalHashing.h).
Lemma 1 (Carter and Wegman). With \( p \) a prime larger than the keys, the class of the functions \( h_{a,b}( k ) = ( ( a k + b ) \bmod p ) \bmod m \), \( 1 \le a < p \) and \( 0 \le b < p \), is universal.
Indeed, for \( k \ne k' \) the map from \( ( a , b ) \) to \( ( r , s ) = ( ( a k + b ) \bmod p , ( a k' + b ) \bmod p ) \) is a bijection between the \( p ( p - 1 ) \) pairs with \( a \ne 0 \) and the pairs with \( r \ne s \), since \( \mathbb{Z}_p \) is a field and \( r - s = a ( k - k' ) \) determines \( a \). For each \( r \), at most \( \lceil p / m \rceil - 1 \le ( p - 1 ) / m \) values \( s \ne r \) have \( s \equiv r \pmod{m} \); hence at most \( p ( p - 1 ) / m \) of the functions make \( k \) and \( k' \) collide, which is (2). The same argument on the digits of the keys gives the class of the dot products, and the class of Dietzfelbinger et al., \( ( a k \bmod 2^h ) \operatorname{div} 2^{h - l} \) with \( a \) odd, is 2-universal by an argument on the lowest bit in which \( k \) and \( k' \) differ, with a product and a shift instead of a division.
By (2), the expected number of the other keys in the list of a key \( k \) is \( \sum_{k' \ne k} \Pr[ H( k ) = H( k' ) ] \le ( n - 1 ) / m < \alpha \), whatever the keys; hence every bound of the chaining below holds in expectation over the function, for every set of keys. The engineered tables use instead the folded product of FastHash.h, the two halves of the product of two words XORed, and the simple tabulation of RandomHashing.h, the XOR of a random word per byte of the key, which is only 3-independent but gives the linear inspection and the cuckoo hashing the bounds of a fully random function (Pătrașcu and Thorup).
In the table with lists of overflow (section 7.2.1, ChainedHashTable.h) the place \( i \) holds the list of the keys with \( H( k ) = i \).
Lemma 2 (the cost of the chaining). Under (1), or with a function drawn from a universal class, an unsuccessful search examines on average
\[ I( \alpha ) = 1 + \alpha , \qquad S( \alpha ) = 1 + \frac{n - 1}{2 m} \approx 1 + \frac{\alpha}{2} \tag{3} \]
cells, the nil that ends the unsuccessful search counted.
Indeed, an unsuccessful search scans a whole list, of expected length \( \alpha \), and its end. A successful search of the key inserted \( j \)-th scans the keys inserted after it in its list, since each one was put at the head, i.e., \( ( n - j ) / m \) of them on average; the mean of \( 1 + ( n - j ) / m \) over \( j = 1 , \ldots , n \) is (3). A list that moves the key found to its head (exercise 7.5) keeps the keys looked up often near the head, and a sorted list (exercise 7.10) stops an unsuccessful search at the first larger key, halving its cost on average.
Lemma 3 (the restructuring). If a table doubles \( m \) when \( \alpha \) exceeds a threshold \( \alpha_{\max} \) and halves it when \( \alpha \) falls below \( \alpha_{\min} \le \alpha_{\max} / 4 \), any sequence of operations costs \( O( 1 ) \) amortized time each, beyond the search of each operation (section 7.4).
Indeed, a restructuring of a table of \( m \) places costs \( O( n + m ) = O( m ) \), and it leaves the load factor at \( \alpha_{\max} / 2 \) or at \( 2 \alpha_{\min} \), both between the two thresholds by a factor of at least 2; the next restructuring needs the load to double or to halve, i.e., \( \Omega( m ) \) insertions or removals, which pay for it. With the thresholds of the example of the book, \( 1 / 2 \) and \( 1 / 4 \), a table just doubled sits at the lower threshold, and a sequence that alternates an insertion and a removal pays \( O( m ) \) per operation; the tables of the library keep the thresholds 4 times apart (TableSize.h), and grow to a prime size when the inspection needs one.
With open addressing (section 7.2.2, OpenHashTable.h) the keys lie in the places of the table, each key \( k \) in the first free place of its inspection \( H( k , 0 ) , H( k , 1 ) , \ldots \); a removal leaves a deleted place, which does not stop the inspections of the other keys and is reused by the insertions. Hence \( \alpha < 1 \), and the cost of a search depends on how the inspections of different keys overlap.
Lemma 4 (uniform hashing). If the inspection of each key is a random permutation of the places, independent of the others, then
\[ I( \alpha ) \le \frac{1}{1 - \alpha} , \qquad S( \alpha ) \le \frac{1}{\alpha} \ln \frac{1}{1 - \alpha} . \tag{4} \]
Indeed, an unsuccessful search examines more than \( i \) places only if its first \( i \) places are full, which has probability at most \( \alpha^i \); hence \( I( \alpha ) \le \sum_{i \ge 0} \alpha^i \). A successful search of a key follows the inspection that its insertion followed, which was an unsuccessful search in a table of load \( j / m \) for the \( ( j + 1 ) \)-th key; the mean over \( j = 0 , \ldots , n - 1 \) of \( m / ( m - j ) \) is at most \( \frac{1}{\alpha} \int_0^\alpha \frac{dx}{1 - x} \), the second bound of (4).
| Inspection | \( H( k , i ) \) | Sizes \( m \) | Behavior |
|---|---|---|---|
| linear | \( ( H_0( k ) + \delta i ) \bmod m \) | \( \gcd( \delta , m ) = 1 \) | primary clustering: \( I( \alpha ) \approx \frac{1}{2} ( 1 + \frac{1}{( 1 - \alpha )^2} ) \), but consecutive places in the cache |
| quadratic | \( ( H_0( k ) + c_1 i + c_2 i^2 ) \bmod m \) | prime | secondary clustering only; not a permutation, an insertion may fail with free places |
| triangular | \( ( H_0( k ) + i ( i + 1 ) / 2 ) \bmod m \) | a power of 2 | a permutation, secondary clustering only |
| double hashing | \( ( H_0( k ) + H_\delta( k ) i ) \bmod m \) | prime or a power of 2 | close to (4) |
| pseudo-random | \( ( H_0( k ) + p_i ) \bmod m \) | any | no primary clustering |
The linear inspection makes the full places gather in runs, and a key that falls anywhere in a run lengthens it; this is the primary clustering, whose cost Knuth computed exactly (the formula in the table). The quadratic and the triangular inspections spread the keys of different \( H_0 \), while the keys with the same \( H_0 \) still share their whole inspection (secondary clustering). The triangular inspection visits all the places when \( m \) is a power of 2: if \( i ( i + 1 ) / 2 \equiv j ( j + 1 ) / 2 \pmod{m} \) with \( 0 \le j < i < m \), then \( ( i - j ) ( i + j + 1 ) \equiv 0 \pmod{2 m} \), where one factor is odd and the other is positive and below \( 2 m \), a contradiction. The double hashing comes close to uniform hashing, since the inspections of two keys coincide only if both \( H_0 \) and \( H_\delta \) do. The improvement of Brent (BrentHashTable in KnuthHashing.h) moves, at an insertion, a key already placed a few steps further along its own inspection when this shortens the inspection of the new key, and keeps \( S( \alpha ) \) below 2.5 even in a full table; the coalesced chaining of Algorithm 6.4C (CoalescedHashTable) links the keys of a place inside the table, with a cellar beyond the places addressed by the hash.
The engineered tables (FlatHashTable.h, DenseHashMap.h) inspect groups of 15 or 12 places in the triangular order of the groups, compare the fingerprints of 8 bits of a whole group with one comparison of the vectors of Highway (SSE2, NEON), and stop a search at the first group whose byte of overflow lacks the bit of the key. A search for an absent key then reads one group in the common case, since a group was passed by an insertion only if it was full, which at a load of \( 7 / 8 \) happens to few groups; the removals leave no deleted mark, the bits of overflow staying set until the next rebuild, which Lemma 3 pays for. PointerTable keeps the pointers of the closed list of a search with their whole hashes, by the linear inspection. With ADS_WITH_BOOST defined, FlatHashTable runs on boost::unordered_flat_map, the table whose groups it follows, and PointerTable on boost::unordered_flat_set, whose load stays below \( 7 / 8 \) (a table of \( m \) places still takes the \( 7 m / 10 \) objects of the places of ADS with no growth); the interfaces stay the same, with forward iterators, and the lemmas above are those of the code of ADS.
The cuckoo hashing of Pagh and Rodler (CuckooHashing.h) gives each key two places, \( h_1( k ) \) and \( h_2( k ) \), and keeps it in one of them; a lookup and a removal examine two places, in the worst case. An insertion puts the key in a free one of its places, or evicts the key in \( h_1( k ) \), which moves to its other place, possibly evicting another key, and so on. The cuckoo graph has the places as vertices and an edge \( \{ h_1( k ) , h_2( k ) \} \) per key; a placement is an orientation of the edges in which each vertex receives at most one edge.
Lemma 5 (the cuckoo graph). The keys can be placed if and only if each connected component of the cuckoo graph has at most one cycle, and the walk of the evictions finds the placement whenever there is one. With \( m \ge 2 ( 1 + \varepsilon ) n \) places and random functions, two places are joined by a shortest path of length \( L \) with probability at most \( c^{-L} / m \), \( c = 1 + \varepsilon \) (chapter 8 of Ferragina); hence an insertion moves \( O( 1 ) \) keys in expectation, and a rehash is needed with probability \( O( 1 / n ) \).
Indeed, a component of \( v \) vertices and \( e \) edges can host its keys only if \( e \le v \), i.e., if it is a tree or has one cycle; and in such a component the evictions, which follow a path and turn around at most once at the cycle, end at a free vertex. The expected length of the walk is bounded by the expected size of the component of the new key, which the bound on the paths makes \( O( 1 ) \), while the probability that the final graph has a component with two cycles sums the same bound over the pairs of places. A stash of \( s \) places (Kirsch, Mitzenmacher and Wieder) keeps the keys whose insertion fails, lowering the probability of a rehash to \( O( 1 / n^{s+1} ) \). The buckets of 4 places of BucketCuckooTable.h accept a load of 95 % and more, with a search in breadth of the shortest path of evictions instead of the random walk; the d-left hashing of DLeftHashTable puts a key in the shortest of its \( d \) lists, which makes the longest list \( \ln \ln n / ( d \ln \phi_d ) + O( 1 ) \) with high probability instead of \( \Theta( \log n / \log \log n ) \), the power of two choices (Azar, Broder, Karlin and Upfal; Vöcking).
On a static set \( S \) a perfect function gives lookups in \( O( 1 ) \) time in the worst case (PerfectHashing.h).
Lemma 6 (Fredman, Komlós and Szemerédi). With \( h \) drawn from a universal class into \( n \) lists, \( n_j \) the keys of the list \( j \),
\[ E\Bigl[ \sum_j n_j^2 \Bigr] < 2 n , \tag{5} \]
and a function drawn from a universal class into \( n_j^2 \) places has no collision on the \( n_j \) keys with probability more than \( 1 / 2 \).
Indeed, \( \sum_j n_j^2 = n + 2 C \), \( C \) the number of the pairs of keys that collide, and by (2) \( E[ C ] \le \binom{n}{2} / n = ( n - 1 ) / 2 \), which gives (5). In the same way, \( n_j \) keys in \( n_j^2 \) places collide in \( \binom{n_j}{2} / n_j^2 < 1 / 2 \) pairs on average, and by the inequality of Markov there is no collision with probability more than \( 1 / 2 \); hence each table of the second level is found after fewer than 2 trials on average, and the two levels take \( O( n ) \) places. The first level of PerfectHashTable is drawn until \( \sum_j n_j^2 < 4 n \): since \( \sum_j n_j^2 - n = 2 C \ge 0 \) has expectation below \( n \), the inequality of Markov gives \( \sum_j n_j^2 \ge 4 n \) with probability below \( 1 / 3 \), so that \( h \) is drawn fewer than \( 3 / 2 \) times on average and the second level takes fewer than \( 4 n \) places (a threshold of \( 2 n \), the mean itself, would be met with a probability that the inequality of Markov does not bound away from 0).
A minimal perfect function needs at least \( n \log_2 e \approx 1.44 n \) bits: a random function from \( U \) to \( \{ 0 , \ldots , n - 1 \} \) is minimal perfect on \( S \) with probability \( n! / n^n \approx e^{-n} \sqrt{2 \pi n} \), so that a family that serves every \( S \) must have about \( e^n \) members. The schemes of the area approach the bound at different costs.
| Scheme | Header | Bits per key | Build | Evaluation |
|---|---|---|---|---|
| Czech, Havas and Majewski, order preserving | PerfectHashing.h | \( c \lceil \log_2 n \rceil \), \( c > 2 \) or \( c > 1.23 \) | \( O( n ) \) expected | 2 or 3 accesses |
| fingerprinting (BBHash, FMPH) | FingerprintPerfectHash.h | \( \gamma e^{1 / \gamma} \), 3.3 for \( \gamma = 2 \) | a few passes | \( e^{1 / \gamma} \) levels expected |
| pilots (PTHash) | MinimalPerfectHash.h | about 3 | slower | 2 accesses |
| recursive splitting (RecSplit) | RecSplit.h | about 1.8 | slowest, \( e^\ell \) per leaf | \( O( \log ( b / \ell ) ) \) levels |
The scheme of Czech, Havas and Majewski maps each key to an edge of a random graph of \( c n \) vertices and asks for the values \( g \) of the vertices such that \( g( u ) + g( v ) \equiv i \pmod{n} \) on the edge of the \( i \)-th key: on a forest, a visit from a root with \( g = 0 \) assigns each vertex once, and the equations hold; a random graph is acyclic with probability about \( \sqrt{( c - 2 ) / c} \) for \( c > 2 \). With three vertices per key the equations are solved in the reverse order of the peeling, the repeated removal of a vertex of degree 1 with its edge, which succeeds if the hypergraph has no 2-core, i.e., for \( c > 1.23 \): each vertex removed is assigned after the other vertices of its edge, and no edge assigned later contains it. The fingerprinting keeps, at each level, a bit per place set when exactly one key falls there, and sends the keys that collide to the next level; a key is alone in its place with probability \( e^{-1 / \gamma} \), which gives the geometric series of its header. PTHash places the buckets of keys from the largest, trying for each one the integers \( k_b = 0 , 1 , \ldots \) as pilots until its keys fall in free places; RecSplit splits each bucket recursively until its leaves of \( \ell \) keys can be mapped bijectively by a seed, and writes the seeds by a code of Golomb and Rice, whose total length approaches the bound since the product of the probabilities of the seeds of a tree is \( m! / m^m \) whatever its shape.
The sorted vector (SortedArrayDictionary.h) finds a key by the binary search of section 1.2 in \( O( \log n ) \) and moves the pairs after it at a change. The skip list of Pugh (SkipList.h) keeps the keys in a sorted list with express lanes, each node in the levels \( 0 , \ldots , \ell - 1 \) with \( \Pr[ \ell \ge j + 1 ] = 2^{-j} \).
Lemma 7 (the skip list). A search in a skip list of \( n \) keys examines \( O( \log n ) \) nodes in expectation, and the list takes \( 2 n \) links in expectation.
Indeed, the level \( j \) holds \( n / 2^j \) nodes in expectation, so that the levels above \( \log_2 n \) hold \( O( 1 ) \) nodes in all and the links are \( \sum_j n / 2^j = 2 n \). The path of a search, read backwards from the node where it ends, goes up a level at each node with probability \( 1 / 2 \) (the node has a further level) and left otherwise; hence it makes 2 steps per level in expectation, and \( O( \log n ) \) in all.
A trie (Trie.h) stands for a set of strings by a tree whose node at depth \( d \) is a prefix of \( d \) characters, the children indexed by the next character and the nodes that end a key marked: a search reads one node per character, \( O( |k| \log \sigma ) \) with the children in a sorted map, whatever \( n \), and the keys with a given prefix are the marked nodes below the node of the prefix. The compact trie (RadixTree) merges each chain of unmarked nodes with one child into an edge labeled by a string; every unmarked node then has at least two children, so that it has at most \( n - 1 \) unmarked nodes, and \( 2 n \) nodes in all. The Patricia trie of PatriciaTrie.h drops the labels and keeps in each node only the length of its prefix and the first character of each edge: its blind search goes down by the branching characters alone, reads the one string of a leaf below the point reached, and finds from the longest common prefix \( \ell \) of that string and of the pattern the edge where the pattern leaves the trie. This is correct since the leaf reached shares with the pattern a prefix as long as any other string does: the first \( \ell \) characters of the pattern drive the descent along the path of that prefix, up to the node of depth at most \( \ell \) where they part. It reads one string instead of a label per edge, \( O( p / B ) \) transfers of blocks for a pattern of \( p \) characters (TwoLevelDictionary.h puts it over the front coding of the strings). The adaptive radix tree of Leis, Kemper and Neumann (AdaptiveRadixTree.h) branches on the bytes, with the layout of each node adapted to the number of its children (4, 16, 48 or 256), the path compression of the chains and the whole key compared at the leaf, so that a search takes \( O( |k| ) \) with \( O( 1 ) \) per node.
The Patricia trie in succinct space (SuccinctPatriciaTrie.h) codes the shape of the compact trie of a static dictionary by the degrees of its nodes in depth (DFUDS) of Benoit, Demaine, Munro, Raman, Raman and Rao: the nodes are visited in depth, the children by their first characters, and a node of \( d \) children is written as \( d \) open parentheses and a closed one, after an open parenthesis that balances the whole, i.e., \( 2 N \) bits for \( N \le 2 n \) nodes; the first character of each edge goes in a byte, in the order of the open parentheses, and the rest of its label in a string apart. The node of rank \( v \) in the visit begins after the \( v \)-th closed parenthesis, and its \( i \)-th child, for the node at the place \( p \) with \( d \) children, begins after the closed parenthesis that matches the open one at \( p + d - 1 - i \) (the last open parenthesis of the node is matched by the closed one that ends it, right after which the first child begins); the characters of the children of a node are consecutive, and the child of a character is found by a binary search on them.
Lemma 8 (the subtree in DFUDS). The parentheses of the subtree of the node at the place \( p \) are those from \( p \) to the first place \( e \) whose excess is one less than the one at \( p - 1 \), and the nodes of the subtree are the ranks from \( v \) to the number of closed parentheses up to \( e \).
Indeed, an open parenthesis followed by the code of a subtree is the code of that subtree as a whole tree, which is balanced: its excess comes back to the level before the open parenthesis only at its end. The code of the subtree alone thus goes one level below the excess at \( p - 1 \) for the first time at its last parenthesis, and the visit in depth writes the nodes of the subtree one after the other, from \( v \) on. Hence, with a vector of bits that marks the nodes where a string ends, the rank of a string among the marks is its rank in the lexicographic order (a node comes before its subtree, which holds the strings it prefixes, and the subtrees follow the order of their first characters), and the strings with a prefix \( P \) are the marks of the subtree where the walk of \( P \) ends, a range of ranks found by one forward search; a lookup walks down \( O( | Q | ) \) nodes and the string of a rank walks up by matching the closed parenthesis before each node. The space is \( 2 N + o( N ) \) bits for the shape, \( 8 ( N - 1 ) \) for the first characters, \( 2 N + o( N ) \) for the marks of the ends and of the nodes with a rest, and the rests themselves, with their places by Elias-Fano. The path-decomposed tries of Grossi and Ottaviano and the dictionaries of Martínez-Prieto et al. compress the labels as well (by Re-Pair or by Hu-Tucker codes), which is not done here.
The hash tables of chapter 5 of Morin's book keep \( m = 2^d \) places and take the place of a key from the high bits of a random function of its hash code \( x \) of \( w \) bits, rather than from \( x \bmod m \): the multiplicative hashing \( \mathrm{hash}( x ) = ( z x \bmod 2^w ) \operatorname{div} 2^{w-d} \), \( z \) a random odd word (MultiplicativeHash in UniversalHashing.h), and the tabulation hashing, the top \( d \) bits of the XOR of a random word per byte of \( x \) (TabulationHash in RandomHashing.h); both are a PlaceHash (TableSize.h), which ChainedHashTable and OpenHashTable call in place of \( h( k ) \bmod m \).
Lemma 9 (the multiplicative hashing). For two distinct words \( x \ne y \) and \( z \) drawn among the odd words, \( \Pr[ \mathrm{hash}( x ) = \mathrm{hash}( y ) ] \le 2 / 2^d \) (Lemma 5.1 of Morin's book).
Indeed, with \( x - y = q 2^r \), \( q \) odd, the product \( z ( x - y ) \bmod 2^w \) has its \( r \) low bits at 0, its bit \( r \) at 1 and the \( w - r - 1 \) bits above it uniform, \( z q \) being a uniform odd number modulo \( 2^{w-r} \); the two hashes agree only if the top \( d \) bits of that difference are all 0 or all 1, which happens for at most \( 2 \) of the \( 2^d \) values of those bits. The bound is reached: for \( x = 2^{w-d-2} \) and \( y = 3 x \) the products \( z x \bmod 2^w \) and \( 3 z x \bmod 2^w \) depend on the \( d + 2 \) low bits \( z' \) of \( z \) alone, the two hashes being \( \lfloor z' / 4 \rfloor \) and \( \lfloor ( 3 z' \bmod 2^{d+2} ) / 4 \rfloor \), and they agree for exactly \( 2 \) in \( 2^d \) of the odd \( z' \) (exercise 5.3; the test ods5.1.multiplicative-hash measures it on \( 2^{17} \) multipliers). For a fixed \( z \) and \( d \le w / 2 \), \( 2^d \) keys share a hash already by the pigeonhole principle, \( 2^w \) keys going to \( 2^d \) places, and they are given by \( x_j = z^{-1} j \bmod 2^w \), \( j = 0 , \ldots , 2^d - 1 \), whose products \( z x_j = j < 2^{w-d} \) all hash to 0, \( z^{-1} \) the inverse of the odd \( z \) modulo \( 2^w \) (exercise 5.2).
With the loads \( g = 1 \) and \( s = 1 / 3 \), the table with the lists is the ChainedHashTable of section 5.1: it doubles when \( n > m \) and halves when \( n < m / 3 \), so that after a restructuring the load is about \( 1 / 2 \) or \( 2 / 3 \) and \( \Omega( m ) \) operations come before the next one, and an unsuccessful search reads \( 1 + \alpha \le 2 \) cells in expectation; any \( g > 2 s \) keeps that margin. The table with the linear inspection, the restructuring and the tabulation hashing is the LinearHashTable of section 5.2: it rebuilds when the full and deleted places are more than \( m / 2 \), at the same size when the keys are at most \( m / 4 \), and halves when \( n < m / 8 \).
Lemma 10 (the runs of the linear inspection). With \( n = m / 2 \) keys hashed independently and uniformly, the probability that a run of \( k \) full places starts at a given place is at most \( \sqrt{ n / ( 2 \pi k ( n - k ) ) } \, e^{1 / ( 12 n )} \, ( \sqrt{e} / 2 )^k \).
Indeed, it is at most \( \binom{n}{k} ( k / m )^k ( 1 - k / m )^{n-k} \), and the full form of the formula of Stirling, \( \sqrt{2 \pi n} ( n / e )^n \le n! \le \sqrt{2 \pi n} ( n / e )^n e^{1 / ( 12 n )} \), bounds the binomial by \( \sqrt{ n / ( 2 \pi k ( n - k ) ) } \, e^{1 / ( 12 n )} \, n^n / ( k^k ( n - k )^{n-k} ) \); with \( m = 2 n \) the product is \( 2^{-k} ( 1 + k / ( m - 2 k ) )^{n-k} \le 2^{-k} e^{k / 2} \). This is the bound \( O( c^k ) \), \( c = \sqrt{e} / 2 \approx 0.82 \), of Lemma 5.4 of the book, proved with the inequalities in place of the approximation (exercise 5.4), with the factor \( O( 1 / \sqrt{k} ) \) that the approximation drops; the expected length of the run of a search is then \( O( 1 ) \), and so is the time of an operation.
The exercises of the section that ask for an explanation have it here: the student numbers of one class of first year students differ in their last two digits, which spread them over 100 places, while the first two digits are those of the year of registration, the same for all of them (exercise 5.1); an insertion that puts the key in the first nil place, skipping the deleted ones, makes a table of \( n \) keys spend \( \Theta( n^2 ) \) time on \( O( n ) \) insertions and removals of one key \( x \), each insertion walking past the deleted places left by the earlier copies of \( x \) in its run, \( i \) of them at the \( i \)-th one, until the deleted places fill half of the table and a rebuild clears them, \( \Theta( n ) \) insertions later (exercise 5.5), which is why OpenHashTable::insert() reuses the first deleted place it meets; a hash code that reads the characters of even place only gives one code to the \( 2^{\ell / 2} \) strings of \( \ell \) characters that differ in the others (exercise 5.6), the XOR of two words gives 0 to every pair \( ( x , x ) \) and their sum gives \( c \) to every pair \( ( x , c - x ) \) (exercises 5.7 and 5.8), and every deterministic function of two words into one has a value taken by at least \( 2^{2w} / 2^w = 2^w \) pairs (exercise 5.9). CompoundHash and SequenceHash (UniversalHashing.h) are the codes of section 5.3 that such sets do not foil, by random multipliers: two distinct tuples collide with probability at most \( 3 / 2^w \) (Theorem 5.3 of the book), two distinct sequences, the longer of \( r \) items, at most \( r / ( p - 1 ) \) (Theorem 5.5 with the point drawn in \( [ 1 , p ) \)), the end marker \( p - 1 \) telling apart a sequence from its extensions. Since \( x = a 2^w + b \) and \( 2^w \equiv 1 \pmod{2^w - 1} \), \( x \equiv a + b \pmod{2^w - 1} \), and \( a + b < x \) while \( x \ge 2^w \), so that \( x \bmod ( 2^w - 1 ) \) is the fixed point of \( x \gets ( x \bmod 2^w ) + ( x \operatorname{div} 2^w ) \), taken to 0 if it is \( 2^w - 1 \) (exercise 5.10), the reduction that mulMod61() does for \( 2^{61} - 1 \). The keys of a table with a fixed hash can be chosen to fall in one place, which makes each search linear: the multiples of the number of buckets for std::unordered_map of libstdc++, the multiples of \( 2^{20} \) for a table of at most \( 2^{20} \) places on std::hash, while the random \( z \) and tables of the book hide the places from who chooses the keys; bench/hashattack.cpp measures it (exercise 5.11).
The headers BinaryTrie.h, XFastTrie.h and YFastTrie.h are the SORTED SETs of chapter 13 of Morin's book on the keys \( x \in \{ 0 , \ldots , 2^w - 1 \} \), whose lowerBound( x ), the find( x ) of the book, gives the smallest key \( \ge x \):
| Structure | lowerBound() | insert(), remove() | Space |
|---|---|---|---|
| BinaryTrie, SimpleBinaryTrie | \( O( w ) \) | \( O( w ) \) | \( O( n w ) \) |
| XFastTrie, ListXFastTrie | \( O( \log w ) \) | \( O( w ) \) | \( O( n w ) \) |
| YFastTrie | \( O( \log w ) \) | \( O( \log w ) \) amortized | \( O( n ) \) |
Lemma 11 (the binary search on the prefixes). If the prefix of \( i \) bits of \( x \) is the prefix of some key, so is its prefix of \( j \) bits for every \( j < i \); hence the longest prefix \( \ell \) of \( x \) shared with a key is found by a binary search on \( i \in [ 0 , w ] \), \( \lceil \log_2( w + 1 ) \rceil \) lookups in the tables of the prefixes, and the successor of \( x \) is the smallest key with that prefix if the bit \( \ell \) of \( x \) is 0, the key after the largest one with that prefix otherwise.
Indeed, the node of the prefix of depth \( \ell \) has no child on the side of the bit \( \ell \) of \( x \), so that all its keys are on the other side, all larger than \( x \) if that bit is 0 and all smaller if it is 1; and the keys outside the subtree of that prefix are either below or above all of its keys. The jump pointer of a node with one child is that smallest or largest key, which the binary trie reaches in \( O( w ) \) by walking down and the x-fast trie in \( O( \log w ) \) by the search; SimpleBinaryTrie (exercise 13.1) has no jump pointers and no list, and keeps instead, on its walk down, the child 1 of the deepest node where the path of \( x \) goes to the child 0 while the child 1 is there, the root of the nearest larger keys, whose leftmost leaf it reaches in \( O( w ) \) more steps. ListXFastTrie (exercise 13.2) has no trie at all: its tables map each prefix to the smallest and the largest key that have it, which are all that the lemma needs, and a removal moves the smallest key of a prefix to the next key in the list, the keys of a prefix being consecutive in it.
Lemma 12 (the search near the successor). Let \( d( x ) \) be the difference between the successor of \( x \) and \( x \), \( 2^w \) if there is none, and \( k = \lceil \log_2( d( x ) + 1 ) \rceil \). Then findNear( x ) takes \( O( 1 + \log \log d( x ) ) \) expected time in ListXFastTrie and \( O( 1 + \log d( x ) ) \) in XFastTrie (exercise 13.4).
Indeed, the successor lies in \( [ x , x + 2^k ) \), which meets the blocks of \( 2^K \) keys of the prefixes \( p = \lfloor x / 2^K \rfloor \) and \( p + 1 \) of depth \( w - K \) for every \( K \ge k \). The search tries \( K = 1 , 2 , 4 , \ldots \), one or two lookups each, and stops at the first \( K \) for which one of the two prefixes is there, \( K < 2 k \), after \( O( \log k ) \) steps: if \( p \) is there, the longest prefix of \( x \) lies between \( w - K \) and the depth \( w - K / 2 \) of the step before, where \( p \) was not, and a binary search finds it in \( O( \log K ) \) lookups; if only \( p + 1 \) is there, no key is in the block of \( x \) and the successor is the smallest key of the block \( p + 1 \), which ListXFastTrie reads from its entry and XFastTrie finds by a walk of \( K = O( k ) \) nodes down the trie. The hint of the exercise, a scan of the depths from \( w \) upwards, takes \( \Theta( w ) \) when the successor is past a carry (\( x = 01\ldots1 \) and its successor \( 10\ldots0 \), at distance 1, share no prefix), which the block \( p + 1 \) covers.
Lemma 13 (the groups of the y-fast trie). The group of a key, the keys between two consecutive representatives, has \( O( w ) \) keys in expectation (Lemma 13.3 of Morin's book).
Indeed, each key is a representative with probability \( 1 / w \), independently, so that the keys of a group after \( x \) (and before it) up to the first representative are fewer than a geometric variable of mean \( w \). The treaps of the groups thus have \( O( \log w ) \) expected depth, and the x-fast trie of the \( n / w \) representatives in expectation takes \( O( n ) \) space; an insertion changes it with probability \( 1 / w \), at the cost \( O( w ) \), \( O( 1 ) \) in expectation, and a removal changes it only when it removes a representative, whose group joins the next one.
BitmapTrie (exercise 13.3) carries the binary trie over to strings of bytes of any length: a node of depth \( i \) for each prefix of \( i \) bytes, the strings in a list, and in each node the smallest and the largest string below it, in the place of the jump pointers. A search that stops at the node \( u \), whose child of \( s_i \) is missing, returns the smallest string below the first child of \( u \) of a byte larger than \( s_i \), or else the string after the largest one below \( u \), by the argument of Lemma 11 on the bytes; the children of a node are in an array sorted by byte with a bitmap of 256 bits, whose population counts give both the child of a byte and the first child after it in \( O( 1 ) \), where the hash table of the exercise gives only the former.
The skip lists of chapter 4 of Morin, Open Data Structures, are SkipList, his SkiplistSSet, whose lowerBound() is the find(x) of an SSet (the smallest key not smaller than \( x \)), IndexedSkipList, the skip list with access by rank of exercise 4.9, and, in the area of the sequences, SkipListSequence, his SkiplistList; the space-efficient SSet of exercise 4.13 is in the area of the sets (SpaceEfficientSortedSet.h). Let each node be promoted from a level to the next with probability \( p \), \( p = 1 / 2 \) in the code.
Lemma 14 (the skip list with promotion probability \( p \), exercise 4.7). The expected height is \( \log_{1/p} n + O( 1 ) \), the expected number of links is \( n / ( 1 - p ) \), and the expected length of a search path is at most \( \frac1p \log_{1/p} n + O( 1 ) \), least for \( p = 1 / e \).
Indeed, a node reaches the level \( j \) with probability \( p^j \), so that the level \( j \) holds \( n p^j \) nodes in expectation, which is below 1 above \( \log_{1/p} n \), and the links are \( \sum_j n p^j = n / ( 1 - p ) \). Read backwards from its end, a search path goes up at each node with probability \( p \) (the node has a further level) and left otherwise, so that it makes \( 1 / p \) steps per level in expectation over \( \log_{1/p} n \) levels, and the levels above add \( O( 1 ) \). The factor \( \frac{1}{p \ln( 1 / p )} \) of \( \ln n \) has derivative zero where \( \ln( 1 / p ) = 1 \); at \( p = 1 / e \) the path is \( e \ln n \approx 1.88 \log_2 n \) steps, against \( 2 \log_2 n \) for \( p = 1 / 2 \), a gain that the cost of drawing a level with probability \( 1 / e \) instead of counting the bits of a word does not repay.
An insertion or a removal changes in expectation a constant number of links (exercise 4.6): the \( \ell \) links of the node and the \( \ell \) links into it, \( \ell \) its levels, whose expectation is \( 1 / ( 1 - p ) = 2 \). The search of Morin compares the key again with the node that stopped it on the level above whenever the link it drops to on the next level leads to that same node (exercise 4.8), i.e., at every level where the search makes no step to the right. A search compares the key once per step to the right and once per level to stop, about \( \frac1p \log_{1/p} n \) times, and makes no step at a level with probability \( p \), so that keeping the last node found not smaller than the key, and dropping without a comparison when the next link leads to it, saves \( p \log_{1/p} n \) comparisons in expectation, down to \( ( \frac1p - p ) \log_{1/p} n + O( 1 ) \), i.e., \( 1.5 \log_2 n \) for \( p = 1 / 2 \) (the test of exercise 4.8 counts 16.2 comparisons per search, against 22.6 without the saving, on 3000 keys).
A finger search (exercise 4.10, fingerLookup()) starts from the nodes where the previous search went down: it climbs them from the bottom while the node of the level is not before the key or its successor is, and goes down from the first one that brackets the key; the levels climbed and the steps of the descent are \( O( 1 + \log r ) \) in expectation for \( r \) keys between the two, since the level from which a key at distance \( r \) is reached is \( \log_{1/p} r + O( 1 ) \) in expectation, and the descent from it is a search in a skip list of \( O( r ) \) keys. The finger stays valid along the levels above the one the search starts from, whose nodes still bracket the new key, and an insertion or a removal brings it back to the head. The widths of IndexedSkipList (exercise 4.9) are kept as in SkiplistList, and a search by rank is the search by key on the sums of the widths.
Every substring of a text is a prefix of one of its suffixes, so that an SSet of the suffixes, each a view of the text from its first character, finds a substring \( q \) as the first suffix not smaller than \( q \), when \( q \) is a prefix of it (exercise 4.14): each keystroke costs \( O( |q| \log n ) \) expected time, the comparisons of a search being of \( |q| \) characters at most, and the test of the exercise runs such a search after each character typed. A suffix array (Manber and Myers) holds the same suffixes in \( n \) words with no links, the SSet allowing changes of the text.
A skip list whose links point only right on each level and down from each node to the same node on the level below is a binary tree: the right link and the down link are the two children of a pair (node, level), and the search follows a path of it as in a binary search tree (exercise 4.15). It uses its links better: a binary search tree of \( n \) nodes has \( 2 n \) links of which \( n + 1 \) are nil, while a skip list has \( 2 n \) links in expectation of which only those at the end of each level, \( O( \log n ) \), are nil.