Hashing
Introducido
7:45
Estructuras de datos y algoritmos
This course is about choosing a container by what it costs. The first unit is the yardstick: how cost grows with the size of the input. The next four are the…
Narración en inglés · subtítulos en inglés y 中文 que puedes cambiar
En esta lección
| English | Significado |
|---|---|
| hash function/hæʃ ˈfʌŋkʃn/ | función hash |
| collision/kəˈlɪʒn/ | colisión |
| Chaining/ˈtʃeɪnɪŋ/ | a hash-table method that keeps all keys with the same hash in a list at that slot |
| Open addressing/ˈəʊpən əˈdresɪŋ/ | a hash-table method that stores every key in the array itself and probes other slots when one is taken |
| load factor/ləʊd ˈfæktə/ | factor de carga |
| Clustering/ˈklʌstərɪŋ/ | the build-up of long runs of occupied slots in a hash table, which makes probes longer |
| resizes/rɪˈsaɪzɪz/ | grows the table (usually doubling it) and re-inserts every key when it becomes too full |
| Universal hashing/ˌjuːnɪˈvɜːsl ˈhæʃɪŋ/ | Choosing a hash function at random from a family so that any two keys collide with probability at most one over the number of buckets. |
Dispersión, colisión y resolución
- Una función hash mapea una clave a un cubo: $h(k) = k \bmod 13$ envía $4, 17, 30, 43$ todas al cubo $4$ — una colisión. El encadenamiento cuelga una lista de cada cubo; la resolución abierta busca el siguiente espacio libre.


Under h(k) = k mod 13, the keys 4, 17, 30, 43 all land —
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Each key leaves remainder 4 on division by 13 — one crowded bucket.
El factor de carga rige la cadena
- Con $m$ cubos y $n$ claves, el factor de carga $\alpha = n/m$ es también la longitud media de la cadena: nuestras claves fijas $[4, 17, 30, 43, 12, 25, 38]$ dan $\alpha = 7/13 \approx 0.54$ — el cubo $4$ contiene cuatro claves, el cubo $12$ contiene tres, diez cubos permanecen vacíos.
- La búsqueda exitosa cuesta unas $1 + \alpha/2$ comparaciones con encadenamiento; crece $m$ con $n$ y el costo esperado se mantiene en $O(1)$ — esa redimensión es por qué los diccionarios permanecen rápidos.
Seven keys in thirteen buckets give a load factor of —
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Alpha is keys over buckets: 7/13 is about 0.54 — also the average chain length.
Sondeo y agrupamiento
- Sonda lineal en $4, 17, 30, 43$: ranura $4$; luego $17$ sonda $4 \to 5$; $30$ sonda $4, 5 \to 6$; $43$ sonda $4, 5, 6 \to 7$. Total: $1 + 2 + 3 + 4 = 10$ sondas para cuatro inserciones.
- El agrupamiento aumenta esas secuencias, por lo que las tablas reales mantienen $\alpha$ bajo aproximadamente $0.75$. No use módulo de una potencia de dos cuando las claves comparten bits bajos (elija un primo) y nunca modifique una clave mientras permanece en la tabla.
Linear-probing inserts of 4, 17, 30, 43 take —
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
1 + 2 + 3 + 4 = 10: each new key walks the growing cluster.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
When the table fills up
- Open addressing pays for a high load factor. With linear probing, the expected cost of a miss is about $\tfrac12\left(1 + \dfrac{1}{(1-\alpha)^2}\right)$: $2.5$ probes at $\alpha = 0.5$, but $8.5$ at $\alpha = 0.75$ and $50.5$ at $\alpha = 0.9$.
- So the table resizes 扩容: it roughly doubles $m$ (to a prime such as $29$ after $13$) and reinserts every key, because $h(k) = k \bmod m$ changes when $m$ changes. One resize costs $O(n)$, but doubling makes it amortised $O(1)$ per insert, like a growing array.
Using the linear-probing estimate for a miss, how many probes at load factor 0.8?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
One half of (1 + 1/0.2^2) = one half of (1 + 25) = 13 probes.
After a resize, every key can stay in its old bucket number.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
The bucket is k mod m, and m has changed, so every key must be rehashed.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Collisions come early: the birthday bound
- With $m$ buckets, a collision 冲突 becomes more likely than not after about $1.18\sqrt m$ keys: 23 people for 365 birthdays.
- In the 13-bucket table, 4 keys all miss each other with probability $13 \cdot 12 \cdot 11 \cdot 10/13^4 = 0.60$, and 5 keys with only $0.42$. Collisions are normal, so the table must handle them well.
Probability that 5 keys land in 5 different buckets of 13 (two decimals)?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
$13 \cdot 12 \cdot 11 \cdot 10 \cdot 9/13^5 = 0.416$.
With 13 buckets, collisions are unlikely until the table is nearly full.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Five keys already collide with probability 0.58.
Esta tarjeta se corrigió, por eso aparece en inglés hasta que se actualice su traducción.
Worked example: universal hashing
- An attacker who knows $h(k) = k \bmod 13$ can send only keys that leave remainder 4, and every search becomes $O(n)$. Universal hashing 通用哈希 picks $h(k) = ((ak + b) \bmod p) \bmod m$ at random when the table is made.
- With $a = 7$, $b = 5$, $p = 101$: keys 4, 17, 30, 43 go to buckets 7, 10, 0 and 3. For distinct keys in $\{0,\ldots,p-1\}$, choosing $a$ uniformly from $\{1,\ldots,p-1\}$ and $b$ uniformly from $\{0,\ldots,p-1\}$ gives collision probability at most $1/m$.
$h(k) = ((7k + 5) \bmod 101) \bmod 13$: bucket of key 17?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
$7 \times 17 + 5 = 124$; $124 \bmod 101 = 23$; $23 \bmod 13 = 10$.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Marks that slip away
- A power of two with patterned keys. $k \bmod 16$ keeps only the low 4 bits, so all keys that share them collide. Use a prime $m$.
- Letting the load factor climb. Linear probing at $\alpha = 0.75$ already costs about $8.5$ probes per miss. Resize before that.
- Changing a key in the table. Its bucket came from the old value, so the table can no longer find it.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
Recap
- Load factor 负载因子 $\alpha = n/m$ is the average chain length; with chaining a hit costs about $1 + \alpha/2$.
- Linear probing forms clusters: keep $\alpha$ under about $0.75$, then resize and rehash.
- Use a prime modulus, and never change a key that is in the table.
¿Qué salió mal? Solo el equipo del sitio ve esta información.