Hash table

Store key–value pairs in an array of buckets chosen by a hash of the key, so lookups, inserts and deletes take constant time on average.

Description

A hash table turns a key into an array index. A hash function converts the key, such as a string, into a number; taking that number modulo the number of buckets picks a bucket. To find the key again, you hash it the same way and look only in that bucket, instead of searching everything.

Different keys sometimes land in the same bucket: a collision. The simplest fix is separate chaining: each bucket holds a short list of entries, and a lookup scans that list. Another approach, open addressing, stores entries directly in the array and probes the next slots on a collision.

As the table fills, chains get longer. The load factor, entries divided by buckets, measures this. When it passes a threshold, typically around 0.75, the table resizes: it allocates more buckets, usually double, and rehashes every entry. Resizing is expensive, but it happens rarely enough that inserts stay constant time on average.

Hash tables are everywhere: JavaScript's Map and objects, Python's dict, Java's HashMap, database hash indexes, caches and deduplication.

How it works

[0]"apple""fig"[1]empty[2]"grape"[3]"cherry"[4]"banana""date""elder"

Seven keys in five buckets, with separate chaining

  1. bucket 0: apple, fig
  2. bucket 1: empty
  3. bucket 2: grape
  4. bucket 3: cherry
  5. bucket 4: banana, date, elder
Seven keys in five buckets, with separate chaining

Step through: inserting seven keys

[0]empty[1]empty[2]empty[3]empty[4]empty

Step 1 of 20An empty table with 5 buckets.

0 comparisons

Complexity

OperationAverageWorst
LookupWorst case when every key collides into one bucket.O(1)O(n)
InsertAmortized: an occasional resize is O(n).O(1)O(n)
DeleteO(1)O(n)
Iterate all entriesO(n + buckets)O(n + buckets)

Space: O(n)

Constant time depends on a good hash function and a bounded load factor. In practice, hash tables are also very cache-friendly when implemented with open addressing, which is why many modern implementations prefer it.

TypeScript implementation

A hash table with separate chaining that doubles its bucket count when the load factor passes 0.75.

hash-table.ts
// A hash table with separate chaining: each bucket holds a small list of
// entries. When the load factor passes 0.75, the bucket array doubles.

type Entry<V> = { key: string; value: V };

export class HashTable<V> {
  private buckets: Entry<V>[][];
  private count = 0;

  constructor(initialBuckets = 8) {
    this.buckets = Array.from({ length: initialBuckets }, () => []);
  }

  // Polynomial string hash (base 31), kept as an unsigned 32-bit integer.
  private hash(key: string): number {
    let h = 0;
    for (let i = 0; i < key.length; i++) h = (h * 31 + key.charCodeAt(i)) >>> 0;
    return h;
  }

  private bucketFor(key: string): Entry<V>[] {
    return this.buckets[this.hash(key) % this.buckets.length];
  }

  get size(): number {
    return this.count;
  }

  get loadFactor(): number {
    return this.count / this.buckets.length;
  }

  get(key: string): V | undefined {
    return this.bucketFor(key).find((e) => e.key === key)?.value;
  }

  has(key: string): boolean {
    return this.bucketFor(key).some((e) => e.key === key);
  }

  set(key: string, value: V): void {
    const bucket = this.bucketFor(key);
    const existing = bucket.find((e) => e.key === key);
    if (existing) {
      existing.value = value; // update in place
      return;
    }
    bucket.push({ key, value });
    this.count++;
    if (this.loadFactor > 0.75) this.resize(this.buckets.length * 2);
  }

  delete(key: string): boolean {
    const bucket = this.bucketFor(key);
    const i = bucket.findIndex((e) => e.key === key);
    if (i === -1) return false;
    bucket.splice(i, 1);
    this.count--;
    return true;
  }

  // Rehash every entry into a larger bucket array: O(n), but rare.
  private resize(newSize: number): void {
    const old = this.buckets;
    this.buckets = Array.from({ length: newSize }, () => []);
    for (const bucket of old) for (const e of bucket) this.bucketFor(e.key).push(e);
  }

  get bucketCount(): number {
    return this.buckets.length;
  }
}

export function demo(): string[] {
  const stock = new HashTable<number>(8);
  const fruit = [["apple", 12], ["banana", 7], ["cherry", 30], ["date", 4], ["elder", 9], ["fig", 21]] as const;
  for (const [name, n] of fruit) stock.set(name, n);
  const lines = [`6 keys in ${stock.bucketCount} buckets (load factor ${stock.loadFactor.toFixed(2)})`];

  stock.set("grape", 16); // pushes the load factor past 0.75: resize
  lines.push(`after a 7th key: ${stock.bucketCount} buckets (load factor ${stock.loadFactor.toFixed(2)})`);

  stock.set("apple", 15); // update, not a new entry
  lines.push(`apple = ${stock.get("apple")}, size = ${stock.size}`);

  stock.delete("banana");
  lines.push(`has banana: ${stock.has("banana")}, size = ${stock.size}`);
  return lines;
}

When to use it

Use it when

  • You need fast lookup, insert and delete by key: caches, indexes, counting occurrences, deduplication.
  • Keys can be hashed and compared for equality, and order doesn't matter.
  • You're joining or grouping data in memory, such as grouping orders by customer.

Avoid it when

  • You need keys in sorted order, or range queries such as "all keys between A and F". Use a balanced search tree.
  • You need the smallest or largest item repeatedly. Use a binary heap.
  • Memory is very tight and the data is small: a sorted array with binary search may use less memory.

Pitfalls

  • Mutable keys. If a key's hash changes after insertion, the entry can never be found again.
  • Poor hash functions. A hash that clusters keys into a few buckets makes every operation linear.
  • Hash flooding. Attackers who know your hash function can send keys that all collide. Languages use randomized or keyed hashes (such as SipHash) to prevent this.
  • Inconsistent equality and hashing. In languages with custom hash methods, two equal objects must produce the same hash.
  • Iteration order. Many hash tables don't preserve insertion order; don't depend on it unless the language guarantees it (JavaScript's Map does).

Alternatives

Balanced search tree

Choose it when you need keys in order, range queries, or guaranteed O(log n) worst-case time.

Trie

Choose it when keys are strings and you need prefix searches such as autocomplete.

Bloom filter

Choose it when you only need to know whether a key might be present, using far less memory, and can accept false positives.

Sorted array with binary search

Choose it when the data rarely changes and you want compact memory with O(log n) lookups.