Belajar
← All lessons

How hash tables work

Hash, store, collide, look up

Key
Hash function
Buckets

hash.js

// turn any string into a 32-bit numberfunction hash(key) {  let h = 0x811c9dc5;  for (let i = 0; i < key.length; i++) {    h = Math.imul(h ^ key.charCodeAt(i), 0x01000193);  }  return h >>> 0;}

hash-table.js

class HashTable {  buckets = Array.from({ length: 8 }, () => []);   put(key, value) {    const i = hash(key) % this.buckets.length;    const chain = this.buckets[i];    const hit = chain.find((e) => e[0] === key);    if (hit) hit[1] = value; // same key: replace the value    else chain.push([key, value]);  }   get(key) {    const i = hash(key) % this.buckets.length;    for (const [k, v] of this.buckets[i]) {      if (k === key) return v;    }    return undefined; // not in this bucket, so not in the table  }}

Fill the table and watch it resize

Key to addResize when load factor passes0.75Never
keys
buckets
load
longest chain
The table

hash-table.js

put(key, value) {  const chain = this.buckets[hash(key) % this.buckets.length];  if (chain.some((e) => e[0] === key)) return;  chain.push([key, value]);  this.count++;  // too full: chains are getting long  if (this.count / this.buckets.length > 0.75) {    this.resize();  }} resize() {  const old = this.buckets;  this.buckets = Array.from({ length: old.length * 2 }, () => []);  // the size changed, so every key is hashed again  for (const chain of old) {    for (const [k, v] of chain) {      this.buckets[hash(k) % this.buckets.length].push([k, v]);    }  }}

A bad hash piles keys up 30 words, one function at a time

Hash withFNV-1akey.lengthFirst letterBuckets816
Keys per bucket
longest chain
empty buckets
avg compares per lookup

Lookups are only O(1) when the hash spreads keys evenly

spread.js

// the same 30 words, three different hash functionsconst hashes = {  fnv1a: (key) => hash(key),  length: (key) => key.length,  firstLetter: (key) => key.charCodeAt(0),}; for (const word of words) {  const i = hashes[name](word) % size;  buckets[i].push(word);}

Topics

Next: How binary search works

Open lesson