Hash tables · put/get/remove expected O(1)

Hash table

Buckets, collisions, chaining, load factor and rehashing (conceptual model).

The full explanation, derivation and practice are in the lesson Hash tables: buckets, chaining and load factor.

Implementation

The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.

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