Docsity

Collision Resolution in Hash Tables: Separate Chaining and Rehashing, Summaries of Design

Toggle sidebar
bg1
CMSC 420 Dave Mount
CMSC 420: Lecture 11
Hashing - Handling Collisions
Hashing: In the previous lecture we introduced the concept of hashing as a method for imple-
menting the dictionary abstract data structure, supporting insert(),delete() and find().
Recall that we have a table of given size m, called the table size. We select an easily com-
putable hash function h(x), which is designed to scatter the keys in a virtually random manner
to indices in the range [0..m-1]. We then store x(and its associated value) in index h(x) in
the table.
In the previous lecture we discussed how to design a hash function in order to achieve good
scattering properties. But, given even the best hash function, it is possible that distinct keys
can map to the same location, that is, h(x) = h(y), even though x6=y. Such events are called
collisions, and a fundamental aspect in the design of a good hashing system how collisions
are handled. We focus on this aspect of hashing in this lecture, called collision resolution.
Separate Chaining: If we have additional memory at our disposal, a simple approach to collision
resolution, called separate chaining, is to store the colliding entries in a separate linked list,
one for each table entry. More formally, each table entry stores a reference to a list data
structure that contains all the dictionary entries that hash to this location.
To make this more concrete, let hbe the hash function, and let table[] be an m-element
array, such that each element table[i] is a linked list containing the key-value pairs (x, v),
such that h(x) = i. We will set the value of mso that each linked list is expected to contain
just a constant number of entries, so there is no need to be clever by trying to sort the
elements of the list. The dictionary operations reduce to applying the associated linked-list
operation on the appropriate entry of the hash table.
•insert(x,v): Compute i = h(x), and then invoke table[i].insert(x,v) to insert
(x, v) into the associated linked list. If xis already in the list, signal a duplicate-key
error (see Fig. 1).
0
1
2
3
4
5
6
7
w
f
z
t
d
p
table
m= 8
h("d") = 1
h("f") = 0
h("p") = 7
h("t") = 4
h("w") = 0
h("z") = 4
insert("d")
insert("z")
insert("p")
insert("w")
insert("t")
insert("f")
Fig. 1: Collision resolution by separate chaining.
•delete(x): Compute i = h(x), and then invoke table[i].delete(x) to remove x’s
entry from the associated linked list. If xis not in the list, signal a missing-key error.
•find(x): Compute i = h(x), and then invoke table[i].find(x) to determine (by
simple brute-force search) whether xis in the list.
Lecture 11 1 Fall 2019
pf3
pf4
pf5
pf8
pf9

Partial preview of the text

Download Collision Resolution in Hash Tables: Separate Chaining and Rehashing and more Summaries Design in PDF only on Docsity!

CMSC 420: Lecture 11

Hashing - Handling Collisions

Hashing: In the previous lecture we introduced the concept of hashing as a method for imple- menting the dictionary abstract data structure, supporting insert(), delete() and find(). Recall that we have a table of given size m, called the table size. We select an easily com- putable hash function h(x), which is designed to scatter the keys in a virtually random manner to indices in the range [0..m-1]. We then store x (and its associated value) in index h(x) in the table. In the previous lecture we discussed how to design a hash function in order to achieve good scattering properties. But, given even the best hash function, it is possible that distinct keys can map to the same location, that is, h(x) = h(y), even though x 6 = y. Such events are called collisions, and a fundamental aspect in the design of a good hashing system how collisions are handled. We focus on this aspect of hashing in this lecture, called collision resolution.

Separate Chaining: If we have additional memory at our disposal, a simple approach to collision resolution, called separate chaining, is to store the colliding entries in a separate linked list, one for each table entry. More formally, each table entry stores a reference to a list data structure that contains all the dictionary entries that hash to this location. To make this more concrete, let h be the hash function, and let table[] be an m-element array, such that each element table[i] is a linked list containing the key-value pairs (x, v), such that h(x) = i. We will set the value of m so that each linked list is expected to contain just a constant number of entries, so there is no need to be clever by trying to sort the elements of the list. The dictionary operations reduce to applying the associated linked-list operation on the appropriate entry of the hash table.

  • insert(x,v): Compute i = h(x), and then invoke table[i].insert(x,v) to insert (x, v) into the associated linked list. If x is already in the list, signal a duplicate-key error (see Fig. 1).

w f

z t

d

p

table

m = 8

h("d") = 1

h("f") = 0

h("p") = 7

h("t") = 4

h("w") = 0

h("z") = 4

insert("d") insert("z") insert("p") insert("w") insert("t") insert("f")

Fig. 1: Collision resolution by separate chaining.

  • delete(x): Compute i = h(x), and then invoke table[i].delete(x) to remove x’s entry from the associated linked list. If x is not in the list, signal a missing-key error.
  • find(x): Compute i = h(x), and then invoke table[i].find(x) to determine (by simple brute-force search) whether x is in the list.

Clearly, the running time of this procedure depends on the number of entries that are stored in the given table entry. To get a handle on this, consider a hash table of size m containing n keys. Define its load factor to be λ = n/m. If we assume that our hash function has done a good job of scattering keys uniformly about the table entries, it follows that the expected number of entries in each list is λ. We say that a search find(x) is successful if x is in the table, and otherwise it is unsuccessful. Assuming that the entries appear in each linked list in random order, we would expect that we need to search roughly half the list before finding the item being sought after. It follows that the expected running time of a successful search with separate chaining is roughly 1 + λ/2. (The initial “+1” accounts for the fact that we need to check one more entry than the list contains, if just to check the null pointer at the end of the list.) On the other hand, if the search is unsuccessful, we need to enumerate the entire list, and so the expected running time of an unsuccessful search with separate chaining is roughly 1 + λ. In summary, the successful and unsuccessful search times for separate chaining are:

SSC = 1 +

λ 2 USC = 1 + λ,

Observe that both are O(1) under our assumption that λ is O(1). Since we can insert and delete into a linked list in constant time, it follows that the expected time for all dictionary operations is O(1 + λ). Note the “in expectation” condition is not based on any assumptions about the insertion or deletion order. It depends simply on the assumption that the hash function uniformly scatters the keys. Assuming that we use universal hashing (see the previous lecture), this uniformity assumption is very reasonable, since the user cannot predict which random hash function will be used. It has been borne out through many empirical studies that hashing is indeed very efficient. The principal drawback of separate chaining is that additional storage is required for linked- list pointers. It would be nice to avoid this additional wasted space. The remaining methods that we will discuss have this property. Before discussing them, we should discuss the issue of controlling the load factor.

Controlling the Load Factor and Rehashing: Recall that the load factor of a hashing scheme is λ = n/m, and the expected running time of hashing operations using separate chaining is O(1 + λ). We will see below that other popular collision-resolution methods have running times that grow as O(λ/(1 − λ)). Clearly, we would like λ to be small and in fact strictly smaller than 1. Making λ too small is wasteful, however, since it means that our table size is significantly larger than the number of keys. This suggests that we define two constants 0 < λmin < λmax < 1, and maintain the invariant that λmin ≤ λ ≤ λmax. This is equivalent to saying that n ≤ λmaxm (that is, the table is never too close to being full) and m ≤ n/λmin (that is, the table size is not significantly larger than the number of entries). Define the ideal load factor to be the mean of these two, λ 0 = (λmin + λmax)/2. Now, as we insert new entries, if the load factor ever exceeds λmax (that is, n > λmaxm), we replace the hash table with a larger one, devise a new hash function (suited to the larger size), and then insert the elements from the old table into the new one, using the new hash function. This is called rehashing (see Fig. 2). More formally:

  • Allocate a new hash table of size m′^ = dn/λ 0 e

the stack overflowed, the amortized cost of each operation is just O(1). There was no magic to doubling. Increasing the storage by any constant factor works, and the same analysis applies here as well. Each time we rehash, we are either increasing or decreasing the hash-table size by a constant factor. Assuming that the hash operations themselves take constant time, we can “charge” the expensive rehashing time to the inexpensive insertions or deletions that led up to the present state of affairs.

Recall that the amortized cost of a series of operations is the total cost divided by the number of operations.

Theorem: Assuming that individual hashing operations take O(1) time each, if we start with an empty hash table, the amortized complexity of hashing using the above rehashing method with minimum and maximum load factors of λmin and λmax, respectively, is at most 1 + 2λmax/(λmax − λmin).

Proof: Our proof is based on the same token-based argument that we used in the earlier lecture. Let us assume that each standard hashing operation takes exactly 1 unit of time, and rehashing takes time n, where n is the number of entries currently in the table. Whenever we perform a hashing operation, we assess 1 unit to the actual operation, and save 2λmax/(λmax − λmin) work tokens to pay for future rehashings. There are two ways to trigger rehashing: expansion due to insertion, and contraction due to deletion. Let us consider insertion first. Suppose that our most recent insertion has triggered rehashing. This implies that the current table contains roughly n ≈ λmax m entries. (Again, to avoid worrying about floors and ceilings, let’s assume that n is quite large.) The last time the table was rehashed, the table contained n′^ = λ 0 m entries immediately after the rehashing finished. This implies that we inserted at least n−n′^ = (λmax−λ 0 )m entries. Therefore, the number of work tokens we have accumulated since then is at least

(λmax − λ 0 )m 2 λmax λmax − λmin

λmax − λmax + λmin 2

m 2 λmax λmax − λmin

=

λmax − λmin 2

m 2 λmax λmax − λmin = λmax m ≈ n,

which implies that we have accumulated enough work tokens to pay the cost of n to rehash. Next, suppose that our most recent deletion has triggered rehashing. This implies that the current table contains roughly n ≈ λmin m entries. (Again, to avoid worrying about floors and ceilings, let’s assume that n is quite large.) The last time the table was rehashed, the table contained n′^ = λ 0 m entries immediately after the rehashing finished. This implies that we deleted at least n′^ −n = (λ 0 −λmin)m entries. Therefore, the number of work tokens we have accumulated since then is at least

(λ 0 − λmin)m

2 λmax λmax − λmin

λmax + λmin 2 − λmin

m

2 λmax λmax − λmin

=

λmax − λmin 2

m

2 λmax λmax − λmin = λmax m ≥ λmin m ≈ n,

again implying that we have accumulated enough work tokens to pay the cost of n to rehash.

To make this a bit more concrete, suppose that we set λmin = 1/4 and λmax = 3/4, so that λ 0 = 1/2 (see Fig. 2). Then the amortized cost of each hashing operation is at most 1 + 2λmax/(λmax − λmin) = 1 + 2(3/4)/(1/2) = 4. Thus, we pay just additional factor of four due to rehashing. Of course, this is a worst case bound. When the number of insertions and deletions is relatively well balanced, we do not need rehash very often, and the amortized cost is even smaller.

Open Addressing: Let us return to the question of collision-resolution methods that do not require additional storage. Our objective is to store all the keys within the hash table. (Therefore, we will need to assume that the load factor is never greater than 1.) To know which table entries store a value and which do not, we will store a special value, called empty, in the empty table entries. The value of empty must be such that it matches no valid key. Whenever we attempt to insert a new entry and find that its position is already occupied, we will begin probing other table entries until we discover an empty location where we can place the new key. In it most general form, an open addressing system involves a secondary search function, f. If we discover that location h(x) is occupied, we next try locations

(h(x) + f (1)) mod m, (h(x) + f (2)) mod m, (h(x) + f (3)) mod m,....

until finding an open location. (To make this a bit more elegant, let us assume that f (0) = 0, so even the first probe fits within the general pattern.) This is called a probe sequence, and ideally it should be capable of searching the entire list. How is this function f chosen? There are a number of alternatives, which we consider below.

Linear Probing: The simplest idea is to simply search sequential locations until finding one that is open. In other words, the probe function is f (i) = i. Although this approach is very simple, it only works well for fairly small load factor. As the table starts to get full, and the load factor approaches 1, the performance of linear probing becomes very bad. To see what is happening consider the example shown in Fig 3. Suppose that we insert four keys, two that hash to table[0] and two that hash to table[2]. Because of the collisions, we will fill the table entries table[1] and table[3] as well. Now, suppose that the fifth key (“t”) hashes to location table[1]. This is the first key to arrive at this entry, and so it is not involved any collisions. However, because of the previous collisions, it needs to slide down three positions to be entered into table[4].

h("d") = 0

h("p") = 2

h("t") = 1

h("w") = 0

h("z") = 2

d 0 1 2 3 4 5

d

insert(z)

insert(d)

z

d

insert(p) z p

d insert(w)

z p

w

d insert(t) z p

w

t

Fig. 3: Linear probing.

following indices:

12 mod 4 = 1 22 mod 4 = 0 32 mod 4 = 1 42 mod 4 = 0...

It can be shown that it will only check table entries 0 and 1. This means that you cannot find a slot to insert this key, even though your table is only half full! A more realistic example is when m = 105. In this case, The following lemma shows that, if you choose your table size m to be a prime number, then quadratic probing is guaranteed to visit at least half of the table entries before repeating. This means that it will succeed in finding an empty slot, provided that m is prime and your load factor is smaller than 1/2.

Theorem: If quadratic probing is used, and the table size m is a prime number, the first bm/ 2 c probe sequences are distinct. Proof: Suppose by way of contradiction that for 0 ≤ i < j ≤ bm/ 2 c, both h(x) + i^2 and h(x) + j^2 are equivalent modulo m. Then the following equivalencies hold modulo m:

i^2 ≡ j^2 ⇔ i^2 − j^2 ≡ 0 ⇔ (i − j)(i + j) ≡ 0 (mod m)

This means that the quantity (i − j)(i + j) is a multiple of m. But this cannot be, since m is prime and both i − j and i + j are nonzero and strictly smaller than m. (The fact that i < j ≤ bm/ 2 c implies that their sum is strictly smaller than m.) Thus, we have the desired contradiction.

This is a rather weak result, however, since people usually want their hash tables to be more than half full. You can do better by being more careful in the choice of the table size and/or the quadratic increment. Here are two examples, which I will present without proof.

  • If the table size m is a prime number of the form 4k + 3, then quadratic probing will succeed in probing every table entry before repeating an entry.
  • If the table size m is a power of two, and the increment is chosen to be 12 (i^2 + i) (thus, you probe locations h(x), h(x) + 1, h(x) + 3, h(x) + 6, and so on) then you will succeed in probing every table entry before repeating an entry.

Double Hashing: Both linear probing and quadratic probing have their shortcomings (secondary clustering for the first and short cycles for the second). Our final method overcomes both of these limitations. Recall that in any open-addressing scheme, we are accessing the probe sequence h(x) + f (1), h(x) + f (2), and so on. How about if we make the increment function f (i) a function of the search key? Indeed, to make it as random as possible, let’s use another hash function! This leads to the concept of double hashing. More formally, we define two hash functions h(x) and g(x). We use h(x) to determine the first probe location. If this entry is occupied, we then try:

h(x) + g(x), h(x) + 2g(x), h(x) + 3g(x),...

More formally, the probe sequence is defined by the function f (i) = i · g(x). In order to be sure that we do not cycle, it should be the case that m and g(x) are relatively prime, that is, they share no common factors. There are lots of ways to achieve this. For example, we could adjust the table size so that m is always prime, and then we are free to select g(x)

to be any non-zero value. Alternately, we could be careful in the choice of g(x) so that it is prime, and then we could make m arbitrary. In short, we should be careful in the design of a double-hashing scheme, but there is a lot of room for adjustment. Fig. 4 provides an illustration of how the various open-addressing probing methods work.

Linear probing

h(x)

Quadratic probing

insert

Double hashing

h(x)

+1 +

+g(x)

+9 +

+2g(x) +3g(x) +4g(x)

insert

insert

h(x)

Fig. 4: Various open-addressing systems. (Shaded squares are occupied and the black square indicates where the key is inserted.)

Theoretical running-time analysis shows that double hashing is the most efficient among the open-addressing methods of hashing, and it is competitive with separate chaining. The running times of successful and unsuccessful searches for open addressing using double hashing are SDH =

λ ln

1 − λ

UDH =

1 − λ

To get some feeling for what these quantities mean, consider the following table:

λ 0.50 0.75 0.90 0.95 0. U (λ) 2.00 4.00 10.0 20.0 100. S(λ) 1.39 1.89 2.56 3.15 4.

Note that, unlike tree-based search structures where the search time grows with n, these search times depend only on the load factor. For example, if you were storing 100,000 items in your data structure, the above search times (except for the very highest load factors) are superior to a running time of O(log n).

Deletions: Deletions are a bit tricky with open-addressing schemes. Can you see why?

The issue is illustrated Fig. 5. When we insert “a”, an existing key “f” was on the probe path, and we inserted “a” beyond “f”. Then we delete “f” and then search for “a”. The problem is that with “f” no longer on the probe path, we arrive at the empty slot and take this to mean that “a” is not in the dictionary, which is not correct. To handle this we create a new special value (in addition to empty) for cells whose keys have been deleted, called, say “deleted”. If the entry is marked deleted this means that the