M10 · Hash Tables and Sets

Hash Tables: Buckets, Chaining and Load Factor

A hash table turns a key into an array index, so it can jump straight to the right place instead of searching. Different keys sometimes land in the same place; how the table handles those collisions, and how full it lets itself get, decides whether lookups stay constant time.

~45 minIntermediateC# · Python · Java · C++
Curriculum: M10 Hash Tables and Sets · 2 of 2 lessons available

You will be able to

  • Trace put, get and remove through hashing, bucket selection and a chain scan.
  • Explain collisions and why separate chaining keeps the table correct no matter how many there are.
  • Define the load factor and relate it to the expected chain length and the expected cost of a lookup.
  • Explain why resizing must rehash every key, and why doubling keeps insertion amortized O(1).
  • State what Dictionary, dict, HashMap and unordered_map actually do, and the equality and hashing contract every key type must follow.

Helpful before this lesson

  • M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.
  • M05 Arrays — Contiguous storage, index arithmetic, and how a dynamic array grows while keeping append cheap.
  • M07 Linked Lists — Nodes and pointers: what O(1) insertion really requires, and the classic pointer techniques.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

Suppose you store a thousand phone numbers in an array and want the one for "Ada". Without order you scan everything: O(n). Sorted, binary search finds it in about ten steps. A hash table does better on average: it computes where Ada's entry must be and looks only there.

It has two parts:

  • A bucket array of capacity slots.
  • A hash function that turns a key into an integer. Reducing that integer to the range 0 … capacity − 1 picks the key's bucket.

To store a key, put it in its bucket. To find a key, compute the same bucket and look only there. If every key had its own bucket, every operation would be one hash and one comparison.

The lab uses integer keys and the simplest possible rule:

bucket = floorMod(key, capacity)

floorMod is the remainder that is never negative, so key -3 in a 4-bucket table goes to bucket 1. Real runtimes first compute a hash code from the key and mix its bits; the runtime section covers that.

Collisions

There are many more possible keys than buckets, so different keys will share a bucket. That is a collision, and it is normal, not an error. Run the Collisions preset: in a 4-bucket table, keys 1, 5 and 9 all give floorMod(k, 4) = 1.

With separate chaining, each bucket holds a small list (a chain) of the entries that hashed there:

put(key, value):
    chain = buckets[bucketOf(key)]
    for each entry in chain:
        if entry.key == key: entry.value = value; return    # keys are unique: update
    if (size + 1) / capacity > 0.75: resize()
    buckets[bucketOf(key)].append((key, value))             # recompute: capacity may have changed
    size += 1

get(key):
    for each entry in buckets[bucketOf(key)]:
        if entry.key == key: return entry.value
    return not found

The hash narrows the search to one bucket; the equality check decides which entry, if any, is the right one. Both are needed. The hash alone cannot distinguish 1 from 5 here, and comparing with == against every key in the table would be a linear scan.

Removal finds the entry the same way and takes it out of its chain. With chaining that is all it takes. Open addressing (below) cannot simply empty a slot.

Load factor

The load factor is

α = size / capacity

the average number of entries per bucket. Under the usual modelling assumption that the hash spreads keys uniformly and independently over the buckets, a chain has α entries on average. Then:

  • an unsuccessful lookup compares against a whole chain: about α comparisons, plus the hash;
  • a successful lookup stops halfway on average: about 1 + α/2 comparisons.

Both are O(1 + α). Keep α below a constant and every operation is expected O(1). "Expected" depends on the hash behaving well for your keys; it is not a guarantee about every input.

The teaching table starts with 4 buckets and doubles when an insert would push α above 0.75. Run Load factor and resize: keys 3, 7 and 12 give α = 3/4 = 0.75, which is allowed; the fourth key would make it 4/4 = 1.0, so the table grows to 8 buckets first.

Resizing means rehashing

A key's bucket depends on the capacity, so after a resize every key must be placed again. Key 7 sits in bucket 3 of a 4-bucket table but in bucket 7 of an 8-bucket table. The lab shows the new bucket array next to the old one while each key moves.

One resize costs O(n). Because the capacity doubles, resizes get rarer as the table grows, and the same argument as for dynamic arrays applies: n insertions cause fewer than 2n key moves in total, so insertion is amortized O(1) (and expected, because of hashing).

The teaching version never shrinks. Neither do most built-ins unless asked, which is why a table that once held a million entries keeps its large bucket array after you remove them.

Costs

Operation Expected (good hash, bounded α) Worst case (all keys in one bucket)
get, contains O(1) O(n) with list chains
put (new key) amortized O(1) O(n)
put (existing key) O(1) O(n)
remove O(1) O(n)
iterate all entries O(n + capacity) O(n + capacity)
space O(n + capacity)

The worst case is real. A poor hash function, or an attacker who chooses keys that collide, can make every operation linear. Python and .NET randomize string hashing per process, and Java's HashMap turns crowded buckets into balanced trees, both to limit that damage.

Why the bucket rule matters

The teaching table's capacities are powers of two, so floorMod(key, capacity) keeps only the lowest bits of the key. Keys that differ only in higher bits collide. Insert 0, 4, 8 and 12: at capacity 4 they all land in bucket 0; after growing to 8 they still share two buckets (0 and 4). Real tables avoid this by mixing the hash first. Java's HashMap XORs the high 16 bits of hashCode() into the low ones before masking; .NET's Dictionary and libstdc++'s unordered_map use prime bucket counts.

Open addressing, briefly

The other main family stores entries directly in the slot array. On a collision, it probes other slots in a fixed sequence until it finds the key or an empty slot: the next slot (linear probing), slots at growing distances (quadratic probing), or steps from a second hash (double hashing). There are no chains and better cache behaviour, but it degrades sharply as the table fills, so the load factor must stay well below 1. Deletion cannot just empty a slot, because that would cut a probe sequence in half and hide keys stored further along; the slot gets a tombstone marker instead. A later lesson in this module covers it in detail.

What real runtimes do

The lab is a conceptual model. The built-ins share its ideas but not its details, and the details below are implementation choices, not language guarantees, unless noted.

C# Dictionary<K,V> Python dict Java HashMap<K,V> C++ std::unordered_map<K,V>
Collision strategy chaining, with chains as index links inside one entries array open addressing with a pseudo-random probe sequence chaining; a crowded bin becomes a red-black tree chaining (the standard's bucket interface requires it in practice)
Bucket count prime power of two power of two, default 16 prime in libstdc++
Grows when the entries array is full (load ≈ 1.0) about two thirds of the slots are used size exceeds 0.75 × capacity (documented default) size exceeds max_load_factor() × bucket_count(); default 1.0 (standard)
Iteration order unspecified insertion order (language guarantee since 3.7) unspecified unspecified
Missing key with [] KeyNotFoundException KeyError get returns null operator[] inserts a default value
Safe lookup TryGetValue get(k, default), in getOrDefault, containsKey find, contains (C++20)
Set type HashSet<T> set HashSet<E> (backed by a HashMap) std::unordered_set<T>

More precisely:

  • .NET Dictionary keeps an int[] of buckets and an array of entries, each with a next index. A bucket points at the first entry of its chain, so chaining happens without allocating a node per entry. Removed entries go on a free list for reuse. It grows to a prime of at least twice the count. Lookups use GetHashCode and Equals, or an IEqualityComparer<TKey> you pass in.
  • CPython dict has, since 3.6, a compact layout: a dense array of entries in insertion order plus a sparse index table that is probed with open addressing. Deleted slots are marked with a dummy value (a tombstone). The hash of an integer is the integer itself for small values, except that hash(-1) is -2, because -1 signals an error inside CPython. set has its own, separate open-addressing implementation.
  • Java HashMap spreads the hash (h ^ (h >>> 16)) and masks it with capacity − 1. When one bin reaches 8 entries and the table has at least 64 buckets, that bin becomes a red-black tree, so a bin full of colliding keys costs O(log n) to search instead of O(n), best when the keys are Comparable. Smaller tables resize instead. LinkedHashMap keeps insertion order.
  • C++ unordered_map exposes buckets directly (bucket_count(), bucket(key), load_factor(), rehash(n), reserve(n)). A rehash invalidates iterators but not pointers or references to elements, which the node-per-element design makes possible. std::hash<int> is the identity function in libstdc++.

The equality and hash contract

Every hash table relies on one rule: if two keys are equal, their hashes must be equal. The reverse need not hold (that is a collision). Break the rule and a key you just stored becomes unfindable, because the lookup computes a different bucket.

  • C#: override Equals and GetHashCode together (or implement IEquatable<T>); records and tuples do it for you.
  • Python: __eq__ and __hash__ go together. Defining __eq__ alone sets __hash__ to None, making instances unhashable. Mutable built-ins such as list are unhashable for this reason.
  • Java: override equals and hashCode together; records generate both.
  • C++: provide operator== and a hash (a std::hash specialization or a hasher type passed as a template argument).

Never mutate a key in a way that changes its hash while it is inside a table: the entry stays in the old bucket and lookups go to the new one.

The teaching implementation

The four listings implement the lab's model exactly: integer keys, floorMod bucket selection (Python's % already floors; C# and C++ use ((k % c) + c) % c; Java uses Math.floorMod), 4 initial buckets, doubling when (size + 1) / capacity > 0.75, checked in integers as 4 × (size + 1) > 3 × capacity. Each chain is the language's dynamic array of key–value pairs rather than a linked list; that keeps the code short and changes no bound. All four recompute the bucket after a resize, because the capacity changed; in C++ the old chain reference would also dangle, since the resize replaced the bucket vector it pointed into. The listings are checked against one shared fixture of put, get and remove sequences, including collisions, overwrites and resizing.

Common mistakes

  • Calling hash tables "O(1)" without the conditions: it is expected O(1) with a good hash and a bounded load factor, amortized for inserts, and O(n) in the worst case.
  • A negative bucket index from % on a negative hash in C#, Java or C++.
  • Not rehashing on resize, or reusing the old bucket index after it.
  • Overriding equality without hashing (or the reverse) in a key type.
  • Mutable keys whose hash changes after insertion.
  • Relying on iteration order of Dictionary, HashMap or unordered_map. Only Python's dict promises one.
  • Using C++ map[key] to test membership: it inserts the key if it is missing.

Edge cases

  • A missing key: get scans one bucket and reports not found; it is not an error in the teaching table.
  • put on an existing key updates the value; the size and load factor do not change, and no resize happens.
  • Removing a missing key: reported, nothing changes (Update and remove preset).
  • Negative keys: floorMod maps them into range (−3 → bucket 1 of 4).
  • Every key in one bucket: correct, just slow.

Worked practice

1. Starting from the empty teaching table (4 buckets), insert keys 0, 4, 8, 12. When does it resize, and where does each key end up?

Answer

0, 4 and 8 all go to bucket 0 (α = 0.75 after the third, allowed). Inserting 12 would make α = 1.0, so the table doubles to 8 and rehashes, in old bucket order: 0 → 0, 4 → 4, 8 → 0. Then 12 → bucket 4. Result: bucket 0 holds 0 and 8, bucket 4 holds 4 and 12, the other six are empty. The keys share low bits, so a bigger table does not separate them.

2. A chained table has 1,000 keys in 512 buckets. Roughly how many comparisons does a lookup of a missing key need, assuming a good hash?

Answer

α = 1000 / 512 ≈ 1.95, so about two key comparisons on average (plus the hash). A linear scan would need 1,000. The teaching table would never be this full: it doubles before α passes 0.75.

3. Why can open addressing not delete by simply emptying the slot?

Answer

A lookup probes until it finds the key or an empty slot. If a key B was placed after probing past key A's slot, emptying A's slot makes later lookups for B stop there and wrongly report B missing. A tombstone says "keep probing, but this slot can be reused for inserts".

4. In Python, d = {}; d[1] = 'a'; d[True] = 'b'. How many entries does d have?

Answer

One: {1: 'b'}. True == 1 and hash(True) == hash(1), so they are the same key; the second assignment updates the value and keeps the original key object 1. It is the equality contract at work.

Summary

  • A hash table hashes a key to a bucket and searches only that bucket; equality picks the entry.
  • Collisions are unavoidable; chaining stores colliding entries in a per-bucket list.
  • Load factor α = size / capacity; with a good hash, operations cost expected O(1 + α).
  • Resizing rehashes every key; doubling makes insertion amortized O(1).
  • Real tables differ: chaining in .NET, Java and C++, open addressing in CPython, tree bins in Java, insertion order only in Python. Every key type must keep equal keys' hashes equal.

Full implementation

The chained hash table in four languages, checked against one shared fixture of put, get and remove sequences, including collisions, overwrites and resizing.

namespace Bekadan.Dsa.Examples.Hashing;
 
/// <summary>
/// A teaching hash table with separate chaining. bucket = floorMod(key, capacity),
/// initial capacity 4, doubling before an insert would push the load factor
/// above 0.75. Dictionary&lt;TKey, TValue&gt; uses other details; the costs are the same.
/// </summary>
public sealed class ChainedHashTable
{
    private List<(int Key, int Value)>[] _buckets = NewBuckets(4);
 
    public int Count { get; private set; }
 
    public int Capacity => _buckets.Length;
 
    private static List<(int Key, int Value)>[] NewBuckets(int capacity)
    {
        var buckets = new List<(int Key, int Value)>[capacity];
        for (int b = 0; b < capacity; b++)
            buckets[b] = [];
        return buckets;
    }
 
    private static int BucketOf(int key, int capacity) => ((key % capacity) + capacity) % capacity;
 
    public void Put(int key, int value)
    {
        var chain = _buckets[BucketOf(key, _buckets.Length)];
        for (int i = 0; i < chain.Count; i++)
        {
            if (chain[i].Key == key)
            {
                chain[i] = (key, value);
                return;
            }
        }
        if (4 * (Count + 1) > 3 * _buckets.Length) // (Count + 1) / capacity > 0.75, in integers
            Resize();
        _buckets[BucketOf(key, _buckets.Length)].Add((key, value));
        Count++;
    }
 
    private void Resize()
    {
        var next = NewBuckets(_buckets.Length * 2);
        foreach (var chain in _buckets)
            foreach (var entry in chain)
                next[BucketOf(entry.Key, next.Length)].Add(entry);
        _buckets = next;
    }
 
    public bool TryGet(int key, out int value)
    {
        var chain = _buckets[BucketOf(key, _buckets.Length)];
        foreach (var entry in chain)
        {
            if (entry.Key == key)
            {
                value = entry.Value;
                return true;
            }
        }
        value = 0;
        return false;
    }
 
    public bool Remove(int key, out int value)
    {
        var chain = _buckets[BucketOf(key, _buckets.Length)];
        for (int i = 0; i < chain.Count; i++)
        {
            if (chain[i].Key == key)
            {
                value = chain[i].Value;
                chain.RemoveAt(i);
                Count--;
                return true;
            }
        }
        value = 0;
        return false;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Hashing/ChainedHashTable.cs

"""A teaching hash table with separate chaining.
 
bucket = key mod capacity (Python's % already floors for negative keys),
initial capacity 4, doubling before an insert would push the load factor
above 0.75. CPython's dict uses open addressing instead; the costs are the same.
"""
 
 
class ChainedHashTable:
    def __init__(self) -> None:
        self._buckets: list[list[tuple[int, int]]] = [[] for _ in range(4)]
        self._count = 0
 
    def __len__(self) -> int:
        return self._count
 
    @property
    def capacity(self) -> int:
        return len(self._buckets)
 
    def put(self, key: int, value: int) -> None:
        chain = self._buckets[key % len(self._buckets)]
        for i, (existing, _) in enumerate(chain):
            if existing == key:
                chain[i] = (key, value)
                return
        if 4 * (self._count + 1) > 3 * len(self._buckets):  # (count + 1) / capacity > 0.75, in integers
            self._resize()
        self._buckets[key % len(self._buckets)].append((key, value))
        self._count += 1
 
    def _resize(self) -> None:
        new_buckets: list[list[tuple[int, int]]] = [[] for _ in range(2 * len(self._buckets))]
        for chain in self._buckets:
            for entry in chain:
                new_buckets[entry[0] % len(new_buckets)].append(entry)
        self._buckets = new_buckets
 
    def get(self, key: int) -> int | None:
        chain = self._buckets[key % len(self._buckets)]
        for existing, value in chain:
            if existing == key:
                return value
        return None
 
    def remove(self, key: int) -> int | None:
        chain = self._buckets[key % len(self._buckets)]
        for i, (existing, value) in enumerate(chain):
            if existing == key:
                del chain[i]
                self._count -= 1
                return value
        return None

Tested on CPython 3.14.0 · examples/python/dsa_examples/hash_table.py

package dev.bekadan.dsa.hashing;
 
import java.util.ArrayList;
import java.util.List;
import java.util.OptionalInt;
 
/**
 * A teaching hash table with separate chaining. bucket = Math.floorMod(key, capacity),
 * initial capacity 4, doubling before an insert would push the load factor above
 * 0.75. HashMap uses other details (power-of-two tables, tree bins); the costs are the same.
 */
public final class ChainedHashTable {
    private record Entry(int key, int value) {
    }
 
    private List<List<Entry>> buckets = newBuckets(4);
    private int count;
 
    private static List<List<Entry>> newBuckets(int capacity) {
        List<List<Entry>> result = new ArrayList<>(capacity);
        for (int b = 0; b < capacity; b++) {
            result.add(new ArrayList<>());
        }
        return result;
    }
 
    public int size() {
        return count;
    }
 
    public int capacity() {
        return buckets.size();
    }
 
    public void put(int key, int value) {
        List<Entry> chain = buckets.get(Math.floorMod(key, buckets.size()));
        for (int i = 0; i < chain.size(); i++) {
            if (chain.get(i).key() == key) {
                chain.set(i, new Entry(key, value));
                return;
            }
        }
        if (4 * (count + 1) > 3 * buckets.size()) { // (count + 1) / capacity > 0.75, in integers
            resize();
        }
        buckets.get(Math.floorMod(key, buckets.size())).add(new Entry(key, value));
        count++;
    }
 
    private void resize() {
        List<List<Entry>> next = newBuckets(buckets.size() * 2);
        for (List<Entry> chain : buckets) {
            for (Entry entry : chain) {
                next.get(Math.floorMod(entry.key(), next.size())).add(entry);
            }
        }
        buckets = next;
    }
 
    public OptionalInt get(int key) {
        List<Entry> chain = buckets.get(Math.floorMod(key, buckets.size()));
        for (Entry entry : chain) {
            if (entry.key() == key) {
                return OptionalInt.of(entry.value());
            }
        }
        return OptionalInt.empty();
    }
 
    public OptionalInt remove(int key) {
        List<Entry> chain = buckets.get(Math.floorMod(key, buckets.size()));
        for (int i = 0; i < chain.size(); i++) {
            if (chain.get(i).key() == key) {
                int value = chain.remove(i).value();
                count--;
                return OptionalInt.of(value);
            }
        }
        return OptionalInt.empty();
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/hashing/ChainedHashTable.java

#pragma once
 
#include <cstddef>
#include <optional>
#include <utility>
#include <vector>
 
namespace bekadan::dsa {
 
// A teaching hash table with separate chaining. bucket = floorMod(key, capacity),
// initial capacity 4, doubling before an insert would push the load factor above
// 0.75. std::unordered_map uses other details (max_load_factor 1.0 by default).
class ChainedHashTable {
    using Entry = std::pair<int, int>;  // key, value
    using Chain = std::vector<Entry>;
 
public:
    [[nodiscard]] std::size_t size() const noexcept { return count_; }
    [[nodiscard]] std::size_t capacity() const noexcept { return buckets_.size(); }
 
    void put(int key, int value) {
        Chain& chain = buckets_[bucket_of(key, buckets_.size())];
        for (Entry& entry : chain) {
            if (entry.first == key) {
                entry.second = value;
                return;
            }
        }
        if (4 * (count_ + 1) > 3 * buckets_.size())  // (count + 1) / capacity > 0.75, in integers
            resize();  // `chain` may dangle after this: look the bucket up again
        buckets_[bucket_of(key, buckets_.size())].emplace_back(key, value);
        ++count_;
    }
 
    [[nodiscard]] std::optional<int> get(int key) const {
        const Chain& chain = buckets_[bucket_of(key, buckets_.size())];
        for (const Entry& entry : chain) {
            if (entry.first == key)
                return entry.second;
        }
        return std::nullopt;
    }
 
    std::optional<int> remove(int key) {
        Chain& chain = buckets_[bucket_of(key, buckets_.size())];
        for (std::size_t i = 0; i < chain.size(); ++i) {
            if (chain[i].first == key) {
                int value = chain[i].second;
                chain.erase(chain.begin() + static_cast<std::ptrdiff_t>(i));
                --count_;
                return value;
            }
        }
        return std::nullopt;
    }
 
private:
    static std::size_t bucket_of(int key, std::size_t capacity) {
        const auto c = static_cast<long long>(capacity);
        return static_cast<std::size_t>(((key % c) + c) % c);
    }
 
    void resize() {
        std::vector<Chain> next(buckets_.size() * 2);
        for (const Chain& chain : buckets_)
            for (const Entry& entry : chain) next[bucket_of(entry.first, next.size())].push_back(entry);
        buckets_ = std::move(next);
    }
 
    std::vector<Chain> buckets_ = std::vector<Chain>(4);
    std::size_t count_ = 0;
};
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/chained_hash_table.hpp

References