Hash Tables
In questa pagina 7
Motivation
A map (MapsA map is a collection of entries with distinct keys supporting get, put and remove by key, and implementing it with a list costs linear time while an array indexed by the whole key universe is fast but wastes space.Maps →) on an array indexed by the whole key universe needs space, too much when (e.g. all Italian citizens keyed by fiscal code). Idea: the universe is very large (possibly infinite), the number of keys actually stored is much smaller. Instead of one cell per possible key, compress the universe into a small range of indices.
A hash function maps each key of to an integer in , with the size of the table (a design choice that limits the array size).
Ideally:
- is roughly proportional to the current number of entries (it is an upper bound on the expected size, since maps are dynamic);
- assigns each key to a distinct cell. This is rarely possible (unless all keys are known a priori), so some keys map to the same index: collisions occur and must be managed.
controls a space/time trade-off: larger means less crowding, fewer collisions, faster operations; smaller means less space, more collisions, slower access.
Elements of a hash table
- Hash function . In Java it is done in two steps: the hash code converts the key into an integer, the compression function maps this integer into a valid array index.
- Bucket array: array of capacity . is the -th bucket and contains all entries with , .
- Collision handling method. A collision occurs when , with and go to the same bucket.
The name: to "hash" means to chop and mix; the function mixes the keys, breaking regularities between them. If it does not mix enough, many keys land in the same bucket and performance degrades. A good hash function should make all keys look "equally random" in the table, while being deterministic, efficient and reproducible.
Hash function
Goals ( = universe of keys):
- should resemble a random process (uniform hashing): for all in and all
- must be fast to compute.
Hash code
Object.hashCode() returns an int that depends on the object's memory address. It does not stay the same across executions or Java implementations, so it is not a pure map from to int. It can be overridden in user classes to depend on the object's content, and must always return an int.
A good hash code depends on all components (bits) of the key, is well distributed over the integer range, and is independent of the memory address.
Numeric keys.
byte,short,char,int: cast toint((int)k); for the first three the cast only widens to 32 bits.float(32 bits):Float.floatToIntBits(k)converts the binary representation to an integer (reasonable start, not optimal).long(64 bits): the cast(int)kdiscards the 32 most significant bits (half of the information). Better:(int)((k >> 32) + (int)k), wherek >> 32gives the most significant 32 bits,(int)kthe least significant 32 bits, and the sum combines both halves in 32 bits.double(64 bits):Double.doubleToLongBits(k)and then thelongprocedure.
Strings. (each Java char is a 16-bit Unicode value, promoted to integer in arithmetic).
- Sum of the characters: . Not good: it correlates keys, e.g. .
- Polynomial hash code: . Characters in different positions contribute differently. Not all are good (good: similar strings get very different codes); experiments show work well, and Java's
hashCodeof strings uses . - Cyclic-shift hash code: sum the characters, but after each addition do a cyclic shift of the partial sum before adding the next character; a shift of 5 positions works well in practice.
A shift moves all bits left or right: bits leaving one side are lost, zeros enter on the other. With : , . A cyclic shift rotates: bits leaving one side re-enter on the other, so nothing is lost. Cyclic shift left by 3 of gives (the three bits re-enter on the right).
In Java a cyclic shift of 5 is simulated with two shifts and an OR: h = (h << 5) | (h >>> 27) (with ; the right shift must be the unsigned one >>>, so zeros come in on the left).
h <- s_0
for i <- 1 to k-1 do
h <- (h << 5) | (h >>> 27) // cyclic shift of the current value
h <- h + s_i // add the current character
return hThe cyclic shift plays the role of the multiplication by in the polynomial code, but it is faster and spreads the bits more evenly: every bit of the partial sum affects the final hash.
Compression function
Maps the hash code to an index in , = capacity of the bucket array.
Division method: (the remainder of the division by ).
The goal is a uniform distribution of indices; it depends strongly on . Choose prime and far from a power of 2 (and not a power of 10). Poor choices:
- : depends only on the least significant bits of , so keys with similar low bits collide. Example : all end in and .
- : it depends only on the last decimal digits. Example : all give .
A prime breaks regular correlations among hash values and makes depend on all bits of .
Multiply-Add-Divide (MAD) method:
with a prime, and chosen arbitrarily, . The modulo by breaks regular patterns and reduces correlations among hash codes; the modulo by makes the result fit in . The distribution is more uniform and reliable than the division method, at a slightly higher computational cost (trade-off between efficiency and hash quality).
Collision handling
Collisions are inevitable, so every table needs a method. Two main strategies:
- Separate chaining. Each bucket stores an auxiliary structure, typically a list, with all entries that hash to the same index (e.g. : both in the list of bucket 2). The number of entries may exceed the number of buckets .
- Open addressing. Entries are stored directly in the array; on a collision a probing sequence determines another free position. It saves space but complicates insertion and search, and requires . Not studied in detail.
Load factor
For a table with entries and buckets, the load factor is
the average number of entries per bucket (the average length of a bucket with separate chaining).
Example: construction (exercise R-10.5)
Table with , , separate chaining, keys (, so ).
| 12 | |
| 44 | |
| 13 | |
| 88 | |
| 23 | |
| 94 | |
| 11 | |
| 39 | |
| 20 | |
| 16 | |
| 5 |
| Bucket | |
|---|---|
| 0 | 13 |
| 1 | 94, 39 |
| 2 | (empty) |
| 3 | (empty) |
| 4 | (empty) |
| 5 | 44, 88, 11 |
| 6 | (empty) |
| 7 | (empty) |
| 8 | 12, 23 |
| 9 | 16, 5 |
| 10 | 20 |
Map methods with separate chaining
The table is the pair with and ; the entry with key lives in bucket .
Method get(k)
if there is an entry (k, x) in A[h(k)] then return x
else return null
Method put(k, v)
if there is an entry (k, x) in A[h(k)] then
replace x with v
return x
else
insert (k, v) at the end of bucket A[h(k)]
increase the size of the table by 1
return null
Method remove(k)
if there is an entry (k, x) in A[h(k)] then
remove (k, x) from A[h(k)]
decrease the size of the table by 1
return x
else return nullEach method computes to find the bucket, then searches the bucket (a list) for key . Several entries with different keys can share a bucket, never two with the same key.
Performance
The cost of get, put, remove is dominated by the search of the key in its bucket; computing the hash and locating the bucket is .
Worst case. All entries fall in the same bucket (the table degenerates into a list) and the key is missing: for each method.
Average case. Theorem. Under the uniform hashing assumption (each key mapped independently and uniformly at random to the buckets), in a hash table with separate chaining and load factor , get, put, remove take expected time
- : compute the hash and locate the bucket.
- : scan the bucket, whose average length is .
- Unsuccessful search (key absent): the cost is averaged over all entries of , on average.
- Successful search (key present): about half of the entries of (average cost of a linear search in an unordered list).
So .
In practice the load factor is kept below a threshold, typically ; Java's HashMap (separate chaining) uses by default, adjustable. Small : few collisions, more space. Large : higher cost, less space. Performance also depends on how close the hash function is to uniform hashing.
High-probability analysis. Under uniform hashing, with separate chaining and , get, put, remove cost with high probability (probability at least ). This is the occupancy (balls-in-bins) problem: assigning balls independently and uniformly to boxes, the average load is 1 and the maximum load is in the worst case but with high probability.
Rehashing
When the load factor exceeds the threshold (e.g. ) a rehashing is executed:
- create a new bucket array of larger capacity (usually double, in general );
- choose a new hash and compression function ;
- reinsert all existing entries from the old table into the new one.
The keys are already known to be distinct, so no search is needed before reinserting: with hashing the transfer of entries costs . This cost is amortised over many future insertions: if we rehash at , , the next rehash occurs after roughly 750 new insertions.
Pros and cons
| Pros | Cons |
|---|---|
| Easy to implement | High worst-case complexity |
| Good average-case performance | Dependence on the quality of the hash function |
| Keys need not come from an ordered universe | Possible space overhead (to keep low) |
Exercises
Inserting distinct keys into a hash table with separate chaining (no rehash, , hash and bucket location ), from empty.
- Best case: every key goes to a different bucket, chain length always 0, each insertion : total .
- Worst case: all keys hash to the same bucket. The -th insertion scans a chain of length (to exclude a duplicate), cost , total .
Compare with the list-based map (see MapsA map is a collection of entries with distinct keys supporting get, put and remove by key, and implementing it with a list costs linear time while an array indexed by the whole key universe is fast but wastes space.Maps →): for insertions in the worst case.
Most frequent word. Document of words. Idea: scan and keep a hash table of pairs ; if is in increment its counter, otherwise insert it with 1. After the -th iteration holds each word of with its number of occurrences in that prefix. Then traverse for the largest count.
Algorithm WordCount(D)
Input: array of N strings D[0..N-1]
Output: <w, c> where w is a word with the highest count
M <- empty hash table
for i <- 0 to N-1 do
e <- M.get(D[i]) // entry with key D[i], or null
if e != null then
M.put(D[i], e.getValue() + 1) // already present: update count
else
M.put(D[i], 1) // new word: count 1
iterator <- M.entrySet()
maxEntry <- null
maxCount <- 0
while iterator.hasNext() do
e <- iterator.next()
if e.getValue() > maxCount then
maxEntry <- e
maxCount <- e.getValue()
return maxEntry- Average case: each
getandputcosts , which is if resizing keeps bounded by a constant. The loop does operations; the final scan of the entries is (exactly if all words are distinct). Overall . - Worst case: all words hash to the same value. At iteration the chain has length , so
getcosts and the update or insert : ; the final scan is dominated. Overall .
Versione ripasso
- Idea: compress a huge key universe into buckets (a MapsA map is a collection of entries with distinct keys supporting get, put and remove by key, and implementing it with a list costs linear time while an array indexed by the whole key universe is fast but wastes space.Maps → implementation). Three elements: hash function , bucket array ( holds the entries with ), collision handling. Collision: , .
- = hash code (key
int) + compression (int ). Goals: uniform hashing (, no correlations), fast, deterministic. - Hash codes:
byte/short/char/intcast;floatfloatToIntBits;long(int)((k >> 32) + (int)k);doubledoubleToLongBitsthen long. Strings: plain sum is bad (); polynomial with in Java; cyclic shift of 5:h = (h << 5) | (h >>> 27)then add . - Compression: division with prime, far from powers of 2 (and 10); MAD , prime, .
- Collisions: separate chaining (a list per bucket, may exceed ); open addressing (probing, , not studied). Load factor .
- get/put/remove: compute , search the bucket list;
putreplaces (returns old value) or appends and increments the size;removedeletes and decrements. - Cost: worst case (all in one bucket); average under uniform hashing ( locate + about scan; successful search about half the bucket); with , high probability .
- Practice: keep ; Java
HashMapthreshold 0.75. Rehashing when exceeds it: new array , new , reinsert all with no searching, amortised over later insertions. - Examples: on 12, 44, 13, 88, 23, 94, 11, 39, 20, 16, 5 gives 13 | 94, 39 | 44, 88, 11 | 12, 23 | 16, 5 | 20 in buckets 0, 1, 5, 8, 9, 10. distinct inserts: best, worst. WordCount: average, worst.
- Pros: simple, good average, no key order needed. Cons: bad worst case, depends on the hash function, space for low .
- Typical mistakes: choosing ; claiming worst case; forgetting that
putmust first search the bucket for the key; using>>instead of>>>in the rotation.