4 FREE Hash Tables and Associative Arrays
If you want to get a book from the central library of the University of Karlsruhe, you have to order the book in advance. The library personnel fetch the book from the stacks and deliver it to a room with 100 shelves. You find your book on a shelf numbered with the last two digits of your library card. Why the last digits and not the leading digits? Probably because this distributes the books more evenly among the shelves. The library cards are numbered consecutively as students sign up, and the University of Karlsruhe was founded in 1825. Therefore, the students enrolled at the same time are likely to have the same leading digits in their card number, and only a few shelves would be in use if the leadingCOPY digits were used.
The subject of this chapter is the robust and efficient implementation of the above “delivery shelf data structure”. In computer science, this data structure is known as a hash1 table. Hash tables are one implementation of associative arrays, or dictio- naries. The other implementation is the tree data structures which we shall study in Chap. 7. An associative array is an array with a potentially infinite or at least very large index set, out of which only a small number of indices are actually in use. For example, the potential indices may be all strings, and the indices in use may be all identifiers used in a particular C++ program.Or the potential indices may be all ways of placing chess pieces on a chess board, and the indices in use may be the place- ments required in the analysis of a particular game. Associative arrays are versatile data structures. Compilers use them for their symbol table, which associates iden- tifiers with information about them. Combinatorial search programs often use them for detecting whether a situation has already been looked at. For example, chess pro- grams have to deal with the fact that board positions can be reached by different sequences of moves. However, each position needs to be evaluated only once. The solution is to store positions in an associative array. One of the most widely used implementations of the join operation in relational databases temporarily stores one of the participating relations in an associative array. Scripting languages such as AWK
1 Photograph of the mincer above by Kku, Rainer Zenz (Wikipedia), Licence CC-by-SA 2.5. 82 4 Hash Tables and Associative Arrays
[7] and Perl [203] use associative arrays as their main data structure. In all of the examples above, the associative array is usually implemented as a hash table. The exercises in this section ask you to develop some further uses of associative arrays. FREEFormally, an associative array S stores a set of elements. Each element e has an associated key key(e) Key. We assume keys to be unique, i.e., distinct elements have distinct keys. Associative∈ arrays support the following operations: S.insert(e : Element): S := S e . • S.remove(k : Key): S := S e∪{, where} e is the unique element with key(e)= k. • S.find(k : Key): If there is\{ an e} S with key(e)= k, return e; otherwise, return . • ∈ ⊥ In addition, we assume a mechanism that allows us to retrieve all elements in S. Since this forall operation is usually easy to implement, we discuss it only in the exercises. Observe that the find operation is essentially the random access operator for an array; hence the name “associative array”. Key is the set of potential array indices, and the elements of S are the indices in use at any particular time. Throughout this chapter, we use n to denote the size of S, and N to denote the size of Key. In a typical appli- cation of associative arrays, N is humongous and hence the use of an array of size N is out of the question. We are aiming for solutions which use space O(n). In the library example, Key is the set of all library card numbers, and elements are the book orders. Another precomputer example is provided by an English–German dictionary. The keys are English words, and an element is an English word together with its German translations. The basic idea behind the hash table implementation of associative arrays is sim- ple. We use a hash function h to mapCOPY the set Key of potential array indices to a small range 0..m 1 of integers. We also have an array t with index set 0..m 1, the hash table. In order− to keep the space requirement low, we want m to be about− the num- ber of elements in S. The hash function associates with each element e a hash value h(key(e)). In order to simplify the notation, we write h(e) instead of h(key(e)) for the hash value of e. In the library example, h maps each library card number to its last two digits. Ideally, we would like to store element e in the table entry t[h(e)]. If this works, we obtain constant execution time2 for our three operations insert, remove, and find. Unfortunately, storing e in t[h(e)] will not always work, as several elements might collide, i.e., map to the same table entry. The library example suggests a fix: allow several book orders to go to the same shelf. The entire shelf then has to be searched to find a particular order. A generalization of this fix leads to hashing with chaining. We store a set of elements in each table entry, and implement the set using singly linked lists. Section 4.1 analyzes hashing with chaining using some rather optimistic (and hence unrealistic) assumptions about the properties of the hash function. In this model, we achieve constant expected time for all three dictionary operations. In Sect. 4.2, we drop the unrealistic assumptionsand construct hash functions that come with (probabilistic) performance guarantees. Even our simple examples show 2 Strictly speaking, we have to add additional terms for evaluating the hash function and for moving elements around. To simplify the notation, we assume in this chapter that all of this takes constant time. 4.1 Hashing with Chaining 83 that finding good hash functions is nontrivial. For example, if we apply the least- significant-digit idea from the library example to an English–German dictionary, we might come up with a hash function based on the last four letters of a word. But then weFREE would have many collisions for words ending in “tion”, “able”, etc. We can simplify hash tables (but not their analysis) by returning to the original idea of storing all elements in the table itself. When a newly inserted element e finds the entry t[h(x)] occupied, it scans the table until a free entry is found. In the library example, assume that shelves can hold exactly one book. The librarians would then use adjacent shelves to store books that map to the same delivery shelf. Section 4.3 elaborates on this idea, which is known as hashing with open addressing and linear probing. Why are hash tables called hash tables? The dictionary defines “to hash” as “to chop up, as of potatoes”. This is exactly what hash functions usually do. For example, if keys are strings, the hash function may chop up the string into pieces of fixed size, interpret each fixed-size piece as a number, and then compute a single number from the sequence of numbers. A good hash function creates disorder and, in this way, avoids collisions.
Exercise 4.1. Assume you are given a set M of pairs of integers. M defines a binary relation RM. Use an associative array to check whether RM is symmetric. A relation is symmetric if (a,b) M : (b,a) M. ∀ ∈ ∈ Exercise 4.2. Write a programthat readsa text file andoutputsthe 100 most frequent words in the text. COPY Exercise 4.3 (a billing system). Assume you have a large file consisting of triples (transaction, price, customer ID). Explain how to compute the total payment due for each customer. Your algorithm should run in linear time.
Exercise 4.4 (scanning a hash table). Show how to realize the forall operation for hashing with chaining and for hashing with open addressing and linear probing.What is the running time of your solution?
4.1 Hashing with Chaining
Hashing with chaining maintains an array t of linear lists (see Fig. 4.1). The associative-array operations are easy to implement. To insert an element e, we in- sert it somewhere in the sequence t[h(e)]. To remove an element with key k, we scan through t[h(k)]. If an element e with h(e)= k is encountered, we remove it and re- turn. To find the element with key k, we also scan through t[h(k)]. If an element e with h(e)= k is encountered, we return it. Otherwise, we return . Insertions take constant time. The space consumption is O(n ⊥+ m). To remove or find a key k, we have to scan the sequence t[h(k)]. In the worst case, for example if find looks for an element that is not there, the entire list has to be scanned. If we are 84 4 Hash Tables and Associative Arrays abcdefghijklmnopqrstuvwxyz 01234567890123456789012345 00000000001111111111222222 t t t
insert remove
"slash" "clip"
Fig. 4.1. Hashing with chaining. We have a table t of sequences. The figure shows an example where a set of words (short synonyms of “hash”) is stored using a hash function that maps the last character to the integers 0..25. We see that this hash function is not very good
unlucky, all elements are mapped to the same table entry and the execution time is Θ(n). So, in the worst case, hashing with chaining is no better than linear lists. Are there hash functions that guaranteeCOPY that all sequences are short? The answer is clearly no. A hash function maps the set of keys to the range 0..m 1, and hence for every hash function there is always a set of N/m keys that all map− to the same table entry. In most applications, n < N/m and hence hashing can always deteriorate to a linear search. We shall study three approaches to dealing with the worst-case behavior. The first approach is average-case analysis. We shall study this approach in this section. The second approach is to use randomization,and to choose the hash function at random from a collection of hash functions. We shall study this approach in this section and the next. The third approach is to change the algorithm. For ex- ample, we could make the hash function depend on the set of keys in actual use. We shall investigate this approach in Sect. 4.5 and shall show that it leads to good worst-case behavior. Let H be the set of all functions from Key to 0..m 1. We assume that the hash function h is chosen randomly3 from H and shall show− that for any fixed set S of n keys, the expected execution time of remove or find will be O(1 + n/m).
Theorem 4.1. If n elements are stored in a hash table with m entries and a random hash function is used, the expected execution time of remove or find is O(1 + n/m).
3 This assumption is completely unrealistic. There are mN functions in H, and hence it re- quires N logm bits to specify a function in H. This defeats the goal of reducing the space requirement from N to n. 4.2 Universal Hashing 85
Proof. The proof requires the probabilistic concepts of random variables, their ex- pectation, and the linearity of expectations as described in Sect. A.3. Consider the execution time of remove or find for a fixed key k. Both need constant time plus theFREE time for scanning the sequence t[h(k)]. Hence the expected execution time is O(1 + E[X]), where the random variable X stands for the length of the sequence t[h(k)]. Let S be the set of n elements stored in the hash table. For each e S, let Xe be the indicator variable which tells us whether e hashes to the same location∈ as k, i.e., Xe = 1 if h(e)= h(k) and Xe = 0 otherwise. In shorthand, Xe = [h(e)= h(k)]. We have X = ∑e S Xe. Using the linearity of expectations, we obtain ∈ E[X]= E[∑ Xe]= ∑ E[Xe]= ∑ prob(Xi = 1) . e S e S e S ∈ ∈ ∈ A random hash function maps e to all m table entries with the same probability, independent of h(k). Hence, prob(Xe = 1)= 1/m and therefore E[X]= n/m. Thus, the expected execution time of find and remove is O(1 + n/m). ⊓⊔ We can achieve a linear space requirement and a constant expected execution time of all three operations by guaranteeing that m = Θ(n) at all times. Adaptive reallocation, as described for unbounded arrays in Sect. 3.2, is the appropriate tech- nique. Exercise 4.5 (unbounded hash tables). Explain how to guarantee m = Θ(n) in hashing with chaining. You may assume the existence of a hash function h : Key ′ → Æ. Set h(k)= h′(k) mod m and use adaptiveCOPY reallocation. Exercise 4.6 (waste of space). The waste of space in hashing with chaining is due to empty table entries. Assuming a random hash function, compute the expected number of empty table entries as a function of m and n. Hint: define indicator random variables Y0,..., Ym 1, where Yi = 1 if t[i] is empty. − Exercise 4.7 (average-case behavior). Assume that the hash function distributes the set of potential keys evenly over the table, i.e., for each i,0 i m 1, we have k Key : h(k)= i N/m . Assume also that a random set≤S of≤n keys− is stored in|{ the∈ table, i.e., S is}|≤⌈ a randomsubset⌉ of Key of size n. Show that for any table position i, the expected number of elements in S that hash to i is at most N/m n/N n/m. ⌈ ⌉· ≈
4.2 Universal Hashing
Theorem 4.1 is unsatisfactory, as it presupposes that the hash function is chosen randomly from the set of all functions4 from keys to table positions. The class of all such functions is much too big to be useful. We shall show in this section that the same performance can be obtained with much smaller classes of hash functions. The families presented in this section are so small that a member can be specified in constant space. Moreover, the functions are easy to evaluate. 4 We shall usually talk about a class of functions or a family of functions in this chapter, and reserve the word “set” for the set of keys stored in the hash table. 86 4 Hash Tables and Associative Arrays
Definition 4.2. Let c be a positive constant. A family H of functions from Key to 0..m 1 is called c-universal if any two distinct keys collide with a probability of at most− c/m, i.e., for all x, y in Key with x = y, 6 FREE c h H : h(x)= h(y) H . |{ ∈ }|≤ m| | In other words, for random h H, ∈ c prob(h(x)= h(y)) . ≤ m This definition has been constructed such that the proof of Theorem 4.1 can be ex- tended.
Theorem 4.3. If n elements are stored in a hash table with m entries using hashing with chaining and a random hash function from a c-universal family is used, the expected execution time of remove or find is O(1 + cn/m).
Proof. We can reuse the proof of Theorem 4.1 almost word for word. Consider the execution time of remove or find for a fixed key k. Both need constant time plus the time for scanning the sequence t[h(k)]. Hence the expected execution time is O(1 + E[X]), where the random variable X stands for the length of the sequence t[h(k)]. Let S be the set of n elements stored in the hash table. For each e S, let Xe be the indicator variable which tells us whether e hashes to the same location∈ as k, i.e., Xe = 1 if h(e)= h(k) and Xe =COPY0 otherwise. In shorthand, Xe = [h(e)= h(k)]. We have X = ∑e S Xe. Using the linearity of expectations, we obtain ∈
E[X]= E[∑ Xe]= ∑ E[Xe]= ∑ prob(Xi = 1) . e S e S e S ∈ ∈ ∈
Since h is chosen uniformly from a c-universal class, we have prob(Xe = 1) c/m, and hence E[X]= cn/m. Thus, the expected execution time of find and remove≤ is O(1 + cn/m). ⊓⊔ Now it remains to find c-universal families of hash functions that are easy to construct and easy to evaluate. We shall describe a simple and quite practical 1- universal family in detail and give further examples in the exercises. We assume that our keys are bit strings of a certain fixed length; in the exercises, we discuss how the fixed-length assumption can be overcome. We also assume that the table size m is a prime number. Why a prime number? Because arithmetic modulo a prime is
particularly nice; in particular, the set Zm = 0,...,m 1 of numbers modulo m form a field.5 Let w = logm . We subdivide the{ keys into− pieces} of w bits each, say k pieces. We interpret⌊ each piece⌋ as an integer in the range 0..2w 1 and keys as − k-tuples of such integers. For a key x, we write x = (x1,...,xk) to denote its partition
5 A field is a set with special elements 0 and 1 and with addition and multiplication oper- ations. Addition and multiplication satisfy the usual laws known for the field of rational numbers. 4.2 Universal Hashing 87
w into pieces. Each xi lies in 0..2 1. We can now define our class of hash functions. − k For each a = (a1,...,ak) 0..m 1 , we define a function ha from Key to 0..m 1 ∈{ − } ∑k − as follows. Let x = (x1,...,xk) be a key and let a x = i=1 aixi denote the scalar productFREE of a and x. Then · ha(x)= a x mod m . · It is time for an example. Let m = 17 and k = 4. Then w = 4 and we view keys as 4-tuples of integers in the range 0..15, for example x = (11,7,4,3). A hash function is specified by a 4-tuple of integers in the range 0..16, for example a = (2,4,7,16). Then ha(x) = (2 11 + 4 7 + 7 4 + 16 3) mod 17 = 7. · · · · Theorem 4.4. k H· = ha : a 0..m 1 ∈{ − } is a 1-universal family of hash functionsn if m is prime. o
In other words, the scalar product between a tuple representation of a key and a random vector modulo m defines a good hash function.
Proof. Consider two distinct keys x = (x1,...,xk) and y = (y1,...,yk). To determine prob(ha(x)= ha(y)), we count the number of choices for a such that ha(x)= ha(y). Fix an index j such that x j = y j. Then (x j y j) 0(mod m), and hence any equa- 6 − 6≡ tion of the form a j(x j y j) b(mod m), where b Zm, has a unique solution in − 1 ≡ ∈ 1 a j, namely a j (x j y j)− b(mod m). Here (x j y j)− denotes the multiplicative 6 ≡ − − inverse of (x j y j). − We claim that for each choice ofCOPY the ai’s with i = j, there is exactly one choice 6 of a j such that ha(x)= ha(y). Indeed,
ha(x)= ha(y) ∑ aixi ∑ aiyi (mod m) ⇔ 1 i k ≡ 1 i k ≤ ≤ ≤ ≤ a j(x j y j) ∑ ai(yi xi) (mod m) ⇔ − ≡ i= j − 6 1 a j (y j x j)− ∑ ai(xi yi) (mod m) . ⇔ ≡ − i= j − 6 k 1 There are m − ways to choose the ai with i = j, and for each such choice there is a 6 k unique choice for a j. Since the total number of choices for a is m , we obtain
mk 1 1 prob(h (x)= h (y)) = − = . a a mk m ⊓⊔ Is it a serious restriction that we need prime table sizes? At first glance, yes. We certainly cannot burden users with the task of providing appropriate primes. Also, when we adaptively grow or shrink an array, it is not clear how to obtain prime
6 In a field, any element z = 0 has a unique multiplicative inverse, i.e., there is a unique 6 element z 1 such that z 1 z = 1. Multiplicative inverses allow one to solve linear equations − − · of the form zx = b, where z = 0. The solution is x = z 1b. 6 − 88 4 Hash Tables and Associative Arrays numbers for the new value of m. A closer look shows that the problem is easy to resolve. The easiest solution is to consult a table of primes. An analytical solution is not muchharder to obtain.First, numbertheory[82] tells us that primes are abundant. More precisely, for any integer k there is a prime in the interval [k3,(k+1)3].So,ifwe FREE 3 3 are aiming for a table size of about m, we determine k such that k m (k+1) and then search for a prime in this interval. How does this search work?≤ Any≤ nonprime in the interval must have a divisor which is at most (k + 1)3 = (k + 1)3/2. We therefore iterate over the numbers from 1 to (k + 1)3/2, and for each such j remove p its multiples in [k3,(k + 1)3]. For each fixed j, this takes time ((k + 1)3 k3)/ j = O k2/ j . The total time required is −