Salta al contenuto
Note per Studenti Hash Tables Report

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 UU needs Θ(∣U∣)\Theta(|U|) space, too much when ∣U∣≫n|U| \gg n (e.g. all Italian citizens keyed by fiscal code). Idea: the universe UU is very large (possibly infinite), the number nn 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 hh maps each key of UU to an integer in [0,N−1][0, N-1], with N≪∣U∣N \ll |U| the size of the table (a design choice that limits the array size).

Ideally:

  • NN is roughly proportional to the current number nn of entries (it is an upper bound on the expected size, since maps are dynamic);
  • hh 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.

NN controls a space/time trade-off: larger NN means less crowding, fewer collisions, faster operations; smaller NN means less space, more collisions, slower access.

Elements of a hash table

  1. Hash function h:U→[0,N−1]h: U \to [0, N-1]. 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.
  2. Bucket array: array AA of capacity NN. A[i]A[i] is the ii-th bucket and contains all entries ⟨k,v⟩\langle k, v \rangle with h(k)=ih(k) = i, 0≤i<N0 \le i < N.
  3. Collision handling method. A collision occurs when ⟨k1,v1⟩\langle k_1, v_1 \rangle, ⟨k2,v2⟩\langle k_2, v_2 \rangle with k1≠k2k_1 \ne k_2 and h(k1)=h(k2)h(k_1) = h(k_2) 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 (UU = universe of keys):

  1. hh should resemble a random process (uniform hashing): for all k≠k′k \ne k' in UU and all i,j∈[0,N−1]i, j \in [0, N-1]

Pr⁡[h(k)=i]=1N(no preferred buckets),Pr⁡[h(k)=i∣h(k′)=j]=Pr⁡[h(k)=i]=1N(no correlations between keys).\Pr[h(k) = i] = \frac{1}{N} \quad \text{(no preferred buckets)}, \qquad \Pr[h(k) = i \mid h(k') = j] = \Pr[h(k) = i] = \frac{1}{N} \quad \text{(no correlations between keys)}.

  1. hh 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 UU 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 to int (k→k \to (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)k discards the 32 most significant bits (half of the information). Better: (int)((k >> 32) + (int)k), where k >> 32 gives the most significant 32 bits, (int)k the least significant 32 bits, and the sum combines both halves in 32 bits.
  • double (64 bits): Double.doubleToLongBits(k) and then the long procedure.

Strings. S=s0s1…sk−1S = s_0 s_1 \dots s_{k-1} (each Java char is a 16-bit Unicode value, promoted to integer in arithmetic).

  1. Sum of the characters: h(S)=∑i=0k−1sih(S) = \sum_{i=0}^{k-1} s_i. Not good: it correlates keys, e.g. h(stop)=h(spot)=h(tops)h(\text{stop}) = h(\text{spot}) = h(\text{tops}).
  2. Polynomial hash code: h(S)=∑i=0k−1si⋅ak−1−ih(S) = \sum_{i=0}^{k-1} s_i \cdot a^{k-1-i}. Characters in different positions contribute differently. Not all aa are good (good: similar strings get very different codes); experiments show a=31,33,37,39,41a = 31, 33, 37, 39, 41 work well, and Java's hashCode of strings uses a=31a = 31.
  3. 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 h=1011 0100h = 1011\,0100: h≪2=1101 0000h \ll 2 = 1101\,0000, h≫2=0010 1101h \gg 2 = 0010\,1101. A cyclic shift rotates: bits leaving one side re-enter on the other, so nothing is lost. Cyclic shift left by 3 of 1011 01001011\,0100 gives 1010 01011010\,0101 (the three bits 101101 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 5+27=325 + 27 = 32; 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 h

The cyclic shift plays the role of the multiplication by aa 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 ii to an index in [0,N−1][0, N-1], NN = capacity of the bucket array.

Division method: i→i mod Ni \to i \bmod N (the remainder of the division by NN).

The goal is a uniform distribution of indices; it depends strongly on NN. Choose NN prime and far from a power of 2 (and not a power of 10). Poor choices:

  • N=2pN = 2^p: i mod Ni \bmod N depends only on the pp least significant bits of ii, so keys with similar low bits collide. Example N=8=23N = 8 = 2^3: 25,17,925, 17, 9 all end in 001001 and 25 mod 8=17 mod 8=9 mod 8=125 \bmod 8 = 17 \bmod 8 = 9 \bmod 8 = 1.
  • N=10pN = 10^p: it depends only on the pp last decimal digits. Example N=102N = 10^2: 123456,987656,3456123456, 987656, 3456 all give 5656.

A prime NN breaks regular correlations among hash values and makes i mod Ni \bmod N depend on all bits of ii.

Multiply-Add-Divide (MAD) method:

i→((a⋅i+b) mod p) mod Ni \to \big((a \cdot i + b) \bmod p\big) \bmod N

with p>Np > N a prime, and a,b∈[0,p−1]a, b \in [0, p-1] chosen arbitrarily, a>0a > 0. The modulo by pp breaks regular patterns and reduces correlations among hash codes; the modulo by NN makes the result fit in [0,N−1][0, N-1]. 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:

  1. Separate chaining. Each bucket A[i]A[i] stores an auxiliary structure, typically a list, with all entries that hash to the same index (e.g. h(28)=2=h(54)h(28) = 2 = h(54): both in the list of bucket 2). The number of entries nn may exceed the number of buckets NN.
  2. 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 n≤Nn \le N. Not studied in detail.

Load factor

For a table with nn entries and NN buckets, the load factor is

λ=nN,\lambda = \frac{n}{N},

the average number of entries per bucket (the average length of a bucket with separate chaining).

Example: construction (exercise R-10.5)

Table with N=11N = 11, h(i)=(3i+5) mod 11h(i) = (3i + 5) \bmod 11, separate chaining, keys 12,44,13,88,23,94,11,39,20,16,512, 44, 13, 88, 23, 94, 11, 39, 20, 16, 5 (n=Nn = N, so λ=1\lambda = 1).

kk h(k)=(3k+5) mod 11h(k) = (3k+5) \bmod 11
12 41 mod 11=841 \bmod 11 = 8
44 137 mod 11=5137 \bmod 11 = 5
13 44 mod 11=044 \bmod 11 = 0
88 269 mod 11=5269 \bmod 11 = 5
23 74 mod 11=874 \bmod 11 = 8
94 287 mod 11=1287 \bmod 11 = 1
11 38 mod 11=538 \bmod 11 = 5
39 122 mod 11=1122 \bmod 11 = 1
20 65 mod 11=1065 \bmod 11 = 10
16 53 mod 11=953 \bmod 11 = 9
5 20 mod 11=920 \bmod 11 = 9
Bucket ii A[i]A[i]
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 (A,h)(A, h) with A=[A[0],…,A[N−1]]A = [A[0], \dots, A[N-1]] and h:K→[0,N−1]h: K \to [0, N-1]; the entry with key kk lives in bucket A[h(k)]A[h(k)].

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 null

Each method computes h(k)h(k) to find the bucket, then searches the bucket (a list) for key kk. 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 O(1)O(1).

Worst case. All entries fall in the same bucket (the table degenerates into a list) and the key is missing: Θ(n)\Theta(n) 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 λ\lambda, get, put, remove take expected time

O(1+λ).O(1 + \lambda).

  • O(1)O(1): compute the hash and locate the bucket.
  • O(λ)O(\lambda): scan the bucket, whose average length is λ=n/N\lambda = n/N.
  • Unsuccessful search (key absent): the cost is averaged over all entries of A[h(k)]A[h(k)], λ\lambda on average.
  • Successful search (key present): about half of the entries of A[h(k)]A[h(k)] (average cost of a linear search in an unordered list).

So Tavg=O(1)+O(λ)=O(1+λ)T_{avg} = O(1) + O(\lambda) = O(1 + \lambda).

In practice the load factor is kept below a threshold, typically λ<0.90\lambda < 0.90; Java's HashMap (separate chaining) uses λ=0.75\lambda = 0.75 by default, adjustable. Small λ\lambda: few collisions, more space. Large λ\lambda: 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 λ=1\lambda = 1, get, put, remove cost O ⁣(log⁡nlog⁡log⁡n)O\!\left(\frac{\log n}{\log\log n}\right) with high probability (probability at least 1−1n1 - \frac1n). This is the occupancy (balls-in-bins) problem: assigning nn balls independently and uniformly to nn boxes, the average load is 1 and the maximum load is O(n)O(n) in the worst case but Θ ⁣(log⁡nlog⁡log⁡n)\Theta\!\left(\frac{\log n}{\log\log n}\right) with high probability.

Rehashing

When the load factor exceeds the threshold (e.g. λ>0.75\lambda > 0.75) a rehashing is executed:

  • create a new bucket array of larger capacity (usually double, in general N′≥2NN' \ge 2N);
  • choose a new hash and compression function h′h';
  • 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 Θ(1)\Theta(1) hashing the transfer of nn entries costs Θ(n)\Theta(n). This cost is amortised over many future insertions: if we rehash at n=750n = 750, N=1000N = 1000, 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 λ\lambda low)

Exercises

Inserting nn distinct keys into a hash table with separate chaining (no rehash, N>nN > n, hash and bucket location Θ(1)\Theta(1)), from empty.

  • Best case: every key goes to a different bucket, chain length always 0, each insertion Θ(1)\Theta(1): total Θ(n)\Theta(n).
  • Worst case: all keys hash to the same bucket. The ii-th insertion scans a chain of length i−1i-1 (to exclude a duplicate), cost Θ(i)\Theta(i), total ∑i=1nΘ(i)=Θ ⁣(n(n+1)2)=Θ(n2)\sum_{i=1}^{n} \Theta(i) = \Theta\!\left(\frac{n(n+1)}{2}\right) = \Theta(n^2).

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 →): Θ(n2)\Theta(n^2) for nn insertions in the worst case.

Most frequent word. Document D[0..N−1]D[0..N-1] of NN words. Idea: scan DD and keep a hash table MM of pairs ⟨word,count⟩\langle word, count \rangle; if D[i]D[i] is in MM increment its counter, otherwise insert it with 1. After the ii-th iteration MM holds each word of D[0..i]D[0..i] with its number of occurrences in that prefix. Then traverse MM 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 get and put costs Θ(1+λ)\Theta(1 + \lambda), which is Θ(1)\Theta(1) if resizing keeps λ\lambda bounded by a constant. The loop does Θ(N)\Theta(N) operations; the final scan of the entries is Θ(N)\Theta(N) (exactly NN if all words are distinct). Overall Θ(N)\Theta(N).
  • Worst case: all words hash to the same value. At iteration ii the chain has length ii, so get costs O(i)O(i) and the update or insert O(1)O(1): ∑i=0N−1O(i)=O(N2)\sum_{i=0}^{N-1} O(i) = O(N^2); the final scan O(N)O(N) is dominated. Overall Θ(N2)\Theta(N^2).

Versione ripasso

  • Idea: compress a huge key universe UU into N≪∣U∣N \ll |U| 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 h:U→[0,N−1]h: U \to [0, N-1], bucket array AA (A[i]A[i] holds the entries with h(k)=ih(k) = i), collision handling. Collision: k1≠k2k_1 \ne k_2, h(k1)=h(k2)h(k_1) = h(k_2).
  • hh = hash code (key →\to int) + compression (int →[0,N−1]\to [0, N-1]). Goals: uniform hashing (Pr⁡[h(k)=i]=1/N\Pr[h(k)=i] = 1/N, no correlations), fast, deterministic.
  • Hash codes: byte/short/char/int cast; float floatToIntBits; long (int)((k >> 32) + (int)k); double doubleToLongBits then long. Strings: plain sum is bad (h(stop)=h(spot)=h(tops)h(\text{stop}) = h(\text{spot}) = h(\text{tops})); polynomial ∑siak−1−i\sum s_i a^{k-1-i} with a=31a = 31 in Java; cyclic shift of 5: h = (h << 5) | (h >>> 27) then add sis_i.
  • Compression: division i mod Ni \bmod N with NN prime, far from powers of 2 (and 10); MAD ((ai+b) mod p) mod N((a i + b) \bmod p) \bmod N, p>Np > N prime, a>0a > 0.
  • Collisions: separate chaining (a list per bucket, nn may exceed NN); open addressing (probing, n≤Nn \le N, not studied). Load factor λ=n/N\lambda = n/N.
  • get/put/remove: compute h(k)h(k), search the bucket list; put replaces (returns old value) or appends and increments the size; remove deletes and decrements.
  • Cost: worst case Θ(n)\Theta(n) (all in one bucket); average under uniform hashing O(1+λ)O(1 + \lambda) (O(1)O(1) locate + about λ\lambda scan; successful search about half the bucket); with λ=1\lambda = 1, high probability O ⁣(log⁡nlog⁡log⁡n)O\!\left(\frac{\log n}{\log\log n}\right).
  • Practice: keep λ<0.9\lambda < 0.9; Java HashMap threshold 0.75. Rehashing when λ\lambda exceeds it: new array N′≥2NN' \ge 2N, new h′h', reinsert all with no searching, Θ(n)\Theta(n) amortised over later insertions.
  • Examples: h(i)=(3i+5) mod 11h(i) = (3i+5) \bmod 11 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. nn distinct inserts: Θ(n)\Theta(n) best, Θ(n2)\Theta(n^2) worst. WordCount: Θ(N)\Theta(N) average, Θ(N2)\Theta(N^2) worst.
  • Pros: simple, good average, no key order needed. Cons: bad worst case, depends on the hash function, space for low λ\lambda.
  • Typical mistakes: choosing N=2pN = 2^p; claiming O(1)O(1) worst case; forgetting that put must first search the bucket for the key; using >> instead of >>> in the rotation.

Teoria collegata