Hash tables · expected O(1) with a good hash and bounded load; O(n) worst

Hash table (open addressing)

Linear, quadratic and double-hashing probes, tombstones on delete, resize at load 0.5.

The full explanation, derivation and practice are in the lesson Open addressing: probing and tombstones.

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;
 
public enum Probing { Linear, Quadratic, Double }
 
/// <summary>
/// A teaching hash table with open addressing and tombstones. Integer keys live
/// directly in one slot array. Probe i is at home + i (linear), home + i(i+1)/2
/// (quadratic) or home + i·step (double hashing, step odd), all mod a power-of-two
/// capacity, with home = floorMod(key, capacity). Removal leaves a tombstone.
/// Capacity starts at 8 and doubles before an insert that would make
/// (size + tombstones + 1) / capacity exceed 0.5. Dictionary&lt;TKey, TValue&gt;
/// uses chaining instead.
/// </summary>
public sealed class OpenAddressingTable(Probing probing = Probing.Linear)
{
    private enum State : byte { Empty, Live, Tombstone }
 
    private State[] _states = new State[8];
    private int[] _keys = new int[8];
    private int[] _values = new int[8];
 
    public int Count { get; private set; }
    public int Tombstones { get; private set; }
    /// <summary>Slots inspected, in every operation and during resizes.</summary>
    public int Probes { get; private set; }
    public int Capacity => _states.Length;
 
    private static int Home(int key, int capacity) => ((key % capacity) + capacity) % capacity;
 
    private static int FloorDiv(int key, int capacity) => (key - Home(key, capacity)) / capacity;
 
    // Odd, so it is coprime with the power-of-two capacity and reaches every slot.
    private static int Step(int key, int capacity) => 2 * Home(FloorDiv(key, capacity), capacity / 2) + 1;
 
    /// <summary>Distance from probe i - 1 to probe i.</summary>
    private int Advance(int i, int step) => probing switch
    {
        Probing.Linear => 1,
        Probing.Quadratic => i, // 1 + 2 + ... + i = i(i + 1)/2 in total
        _ => step,
    };
 
    public void Put(int key, int value)
    {
        int cap = _states.Length;
        int index = Home(key, cap), step = Step(key, cap), tomb = -1;
        for (int i = 0; i < cap; i++)
        {
            Probes++;
            var state = _states[index];
            if (state == State.Empty)
                break; // the key is not further along
            if (state == State.Tombstone)
            {
                if (tomb < 0)
                    tomb = index; // first reusable slot; keep probing
            }
            else if (_keys[index] == key)
            {
                _values[index] = value;
                return;
            }
            index = (index + Advance(i + 1, step)) & (cap - 1);
        }
        if (2 * (Count + Tombstones + 1) > cap) // (used + 1) / capacity > 0.5
        {
            Resize();
            tomb = -1;
            index = FirstEmpty(key); // the slots moved: probe the new table
        }
        if (tomb >= 0)
        {
            index = tomb;
            Tombstones--;
        }
        (_states[index], _keys[index], _values[index]) = (State.Live, key, value);
        Count++;
    }
 
    public bool TryGet(int key, out int value)
    {
        int cap = _states.Length;
        int index = Home(key, cap), step = Step(key, cap);
        for (int i = 0; i < cap; i++)
        {
            Probes++;
            var state = _states[index];
            if (state == State.Empty)
                break; // an empty slot ends every probe sequence
            if (state == State.Live && _keys[index] == key)
            {
                value = _values[index];
                return true;
            }
            index = (index + Advance(i + 1, step)) & (cap - 1);
        }
        value = 0;
        return false;
    }
 
    public bool Remove(int key, out int value)
    {
        int cap = _states.Length;
        int index = Home(key, cap), step = Step(key, cap);
        for (int i = 0; i < cap; i++)
        {
            Probes++;
            var state = _states[index];
            if (state == State.Empty)
                break;
            if (state == State.Live && _keys[index] == key)
            {
                value = _values[index];
                _states[index] = State.Tombstone; // not Empty: other keys may have probed past here
                Count--;
                Tombstones++;
                return true;
            }
            index = (index + Advance(i + 1, step)) & (cap - 1);
        }
        value = 0;
        return false;
    }
 
    private void Resize()
    {
        var (oldStates, oldKeys, oldValues) = (_states, _keys, _values);
        int cap = 2 * oldStates.Length;
        (_states, _keys, _values) = (new State[cap], new int[cap], new int[cap]);
        Tombstones = 0; // tombstones are not copied
        for (int s = 0; s < oldStates.Length; s++)
        {
            if (oldStates[s] == State.Live)
            {
                int t = FirstEmpty(oldKeys[s]);
                (_states[t], _keys[t], _values[t]) = (State.Live, oldKeys[s], oldValues[s]);
            }
        }
    }
 
    private int FirstEmpty(int key)
    {
        int cap = _states.Length;
        int index = Home(key, cap), step = Step(key, cap);
        for (int i = 0; i < cap; i++)
        {
            Probes++;
            if (_states[index] == State.Empty)
                return index;
            index = (index + Advance(i + 1, step)) & (cap - 1);
        }
        throw new InvalidOperationException("No empty slot."); // unreachable: at most half the slots are used
    }
 
    /// <summary>One token per slot: "." empty, "x" tombstone, otherwise the key.</summary>
    public string Layout() =>
        string.Join(' ', _states.Select((s, i) => s == State.Empty ? "." : s == State.Tombstone ? "x" : _keys[i].ToString()));
}

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

"""A teaching hash table with open addressing and tombstones.
 
Integer keys live directly in one slot array (no chains). The probe sequence
starts at home = key mod capacity and continues by one of three rules:
 
- linear:    home, home + 1, home + 2, ...
- quadratic: home + i(i + 1)/2 (triangular numbers), which visits every slot
             when the capacity is a power of two
- double:    home + i * step with step = 2 * ((key // capacity) mod (capacity / 2)) + 1,
             an odd number, so it is coprime with the power-of-two capacity
 
Removing a key leaves a tombstone. Lookups probe past tombstones and stop at an
empty slot; insertion reuses the first tombstone it saw, but only after probing
to an empty slot proves the key is not further along. Capacity starts at 8 and
doubles before an insert that would make (size + tombstones + 1) / capacity
exceed 0.5; a resize reinserts live keys only, so tombstones disappear.
Python's own dict is open addressing too, with a different probe recurrence.
"""
 
EMPTY, LIVE, TOMBSTONE = 0, 1, 2
PROBING = ("linear", "quadratic", "double")
 
 
class OpenAddressingTable:
    def __init__(self, probing: str = "linear") -> None:
        if probing not in PROBING:
            raise ValueError(f"probing must be one of {PROBING}")
        self.probing = probing
        self._states = [EMPTY] * 8
        self._keys = [0] * 8
        self._values = [0] * 8
        self.size = 0
        self.tombstones = 0
        self.probes = 0  # slots inspected, in every operation and during resizes
 
    @property
    def capacity(self) -> int:
        return len(self._states)
 
    @staticmethod
    def _step(key: int, capacity: int) -> int:
        return 2 * ((key // capacity) % (capacity // 2)) + 1  # odd: reaches every slot
 
    def _advance(self, i: int, step: int) -> int:
        """Distance from probe i - 1 to probe i."""
        if self.probing == "linear":
            return 1
        if self.probing == "quadratic":
            return i  # 1 + 2 + ... + i = i(i + 1)/2 in total
        return step
 
    def put(self, key: int, value: int) -> None:
        cap = len(self._states)
        index, step, tomb = key % cap, self._step(key, cap), -1
        for i in range(cap):
            self.probes += 1
            state = self._states[index]
            if state == EMPTY:
                break  # the key is not further along
            if state == TOMBSTONE:
                if tomb < 0:
                    tomb = index  # first reusable slot; keep probing
            elif self._keys[index] == key:
                self._values[index] = value
                return
            index = (index + self._advance(i + 1, step)) & (cap - 1)
        if 2 * (self.size + self.tombstones + 1) > cap:  # (used + 1) / capacity > 0.5
            self._resize()
            tomb = -1
            index = self._first_empty(key)  # the slots moved: probe the new table
        if tomb >= 0:
            index = tomb
            self.tombstones -= 1
        self._states[index], self._keys[index], self._values[index] = LIVE, key, value
        self.size += 1
 
    def get(self, key: int) -> int | None:
        cap = len(self._states)
        index, step = key % cap, self._step(key, cap)
        for i in range(cap):
            self.probes += 1
            state = self._states[index]
            if state == EMPTY:
                break  # an empty slot ends every probe sequence
            if state == LIVE and self._keys[index] == key:
                return self._values[index]
            index = (index + self._advance(i + 1, step)) & (cap - 1)
        return None
 
    def remove(self, key: int) -> int | None:
        cap = len(self._states)
        index, step = key % cap, self._step(key, cap)
        for i in range(cap):
            self.probes += 1
            state = self._states[index]
            if state == EMPTY:
                break
            if state == LIVE and self._keys[index] == key:
                value = self._values[index]
                self._states[index] = TOMBSTONE  # not EMPTY: other keys may have probed past here
                self.size -= 1
                self.tombstones += 1
                return value
            index = (index + self._advance(i + 1, step)) & (cap - 1)
        return None
 
    def _resize(self) -> None:
        old_states, old_keys, old_values = self._states, self._keys, self._values
        cap = 2 * len(old_states)
        self._states, self._keys, self._values = [EMPTY] * cap, [0] * cap, [0] * cap
        self.tombstones = 0  # tombstones are not copied
        for s, state in enumerate(old_states):
            if state == LIVE:
                t = self._first_empty(old_keys[s])
                self._states[t], self._keys[t], self._values[t] = LIVE, old_keys[s], old_values[s]
 
    def _first_empty(self, key: int) -> int:
        cap = len(self._states)
        index, step = key % cap, self._step(key, cap)
        for i in range(cap):
            self.probes += 1
            if self._states[index] == EMPTY:
                return index
            index = (index + self._advance(i + 1, step)) & (cap - 1)
        raise RuntimeError("no empty slot")  # unreachable: at most half the slots are used
 
    def layout(self) -> list[str]:
        """One token per slot: '.' empty, 'x' tombstone, otherwise the key."""
        return ["." if s == EMPTY else "x" if s == TOMBSTONE else str(k) for s, k in zip(self._states, self._keys)]

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

package dev.bekadan.dsa.hashing;
 
import java.util.OptionalInt;
 
/**
 * A teaching hash table with open addressing and tombstones. Integer keys live
 * directly in one slot array. Probe i is at home + i (linear), home + i(i+1)/2
 * (quadratic) or home + i*step (double hashing, step odd), all mod a power-of-two
 * capacity, with home = floorMod(key, capacity). Removal leaves a tombstone.
 * Capacity starts at 8 and doubles before an insert that would make
 * (size + tombstones + 1) / capacity exceed 0.5. java.util.HashMap uses chaining instead.
 */
public final class OpenAddressingTable {
    public enum Probing { LINEAR, QUADRATIC, DOUBLE }
 
    private static final byte EMPTY = 0;
    private static final byte LIVE = 1;
    private static final byte TOMBSTONE = 2;
 
    private final Probing probing;
    private byte[] states = new byte[8];
    private int[] keys = new int[8];
    private int[] values = new int[8];
    private int size;
    private int tombstones;
    private int probes;
 
    public OpenAddressingTable(Probing probing) {
        this.probing = probing;
    }
 
    public int size() {
        return size;
    }
 
    public int tombstones() {
        return tombstones;
    }
 
    /** Slots inspected, in every operation and during resizes. */
    public int probes() {
        return probes;
    }
 
    public int capacity() {
        return states.length;
    }
 
    // Odd, so it is coprime with the power-of-two capacity and reaches every slot.
    private static int step(int key, int capacity) {
        return 2 * Math.floorMod(Math.floorDiv(key, capacity), capacity / 2) + 1;
    }
 
    /** Distance from probe i - 1 to probe i. */
    private int advance(int i, int step) {
        return switch (probing) {
            case LINEAR -> 1;
            case QUADRATIC -> i; // 1 + 2 + ... + i = i(i + 1)/2 in total
            case DOUBLE -> step;
        };
    }
 
    public void put(int key, int value) {
        int cap = states.length;
        int index = Math.floorMod(key, cap), step = step(key, cap), tomb = -1;
        for (int i = 0; i < cap; i++) {
            probes++;
            byte state = states[index];
            if (state == EMPTY) {
                break; // the key is not further along
            }
            if (state == TOMBSTONE) {
                if (tomb < 0) {
                    tomb = index; // first reusable slot; keep probing
                }
            } else if (keys[index] == key) {
                values[index] = value;
                return;
            }
            index = (index + advance(i + 1, step)) & (cap - 1);
        }
        if (2 * (size + tombstones + 1) > cap) { // (used + 1) / capacity > 0.5
            resize();
            tomb = -1;
            index = firstEmpty(key); // the slots moved: probe the new table
        }
        if (tomb >= 0) {
            index = tomb;
            tombstones--;
        }
        states[index] = LIVE;
        keys[index] = key;
        values[index] = value;
        size++;
    }
 
    public OptionalInt get(int key) {
        int cap = states.length;
        int index = Math.floorMod(key, cap), step = step(key, cap);
        for (int i = 0; i < cap; i++) {
            probes++;
            byte state = states[index];
            if (state == EMPTY) {
                break; // an empty slot ends every probe sequence
            }
            if (state == LIVE && keys[index] == key) {
                return OptionalInt.of(values[index]);
            }
            index = (index + advance(i + 1, step)) & (cap - 1);
        }
        return OptionalInt.empty();
    }
 
    public OptionalInt remove(int key) {
        int cap = states.length;
        int index = Math.floorMod(key, cap), step = step(key, cap);
        for (int i = 0; i < cap; i++) {
            probes++;
            byte state = states[index];
            if (state == EMPTY) {
                break;
            }
            if (state == LIVE && keys[index] == key) {
                int value = values[index];
                states[index] = TOMBSTONE; // not EMPTY: other keys may have probed past here
                size--;
                tombstones++;
                return OptionalInt.of(value);
            }
            index = (index + advance(i + 1, step)) & (cap - 1);
        }
        return OptionalInt.empty();
    }
 
    private void resize() {
        byte[] oldStates = states;
        int[] oldKeys = keys;
        int[] oldValues = values;
        int cap = 2 * oldStates.length;
        states = new byte[cap];
        keys = new int[cap];
        values = new int[cap];
        tombstones = 0; // tombstones are not copied
        for (int s = 0; s < oldStates.length; s++) {
            if (oldStates[s] == LIVE) {
                int t = firstEmpty(oldKeys[s]);
                states[t] = LIVE;
                keys[t] = oldKeys[s];
                values[t] = oldValues[s];
            }
        }
    }
 
    private int firstEmpty(int key) {
        int cap = states.length;
        int index = Math.floorMod(key, cap), step = step(key, cap);
        for (int i = 0; i < cap; i++) {
            probes++;
            if (states[index] == EMPTY) {
                return index;
            }
            index = (index + advance(i + 1, step)) & (cap - 1);
        }
        throw new IllegalStateException("no empty slot"); // unreachable: at most half the slots are used
    }
 
    /** One token per slot: "." empty, "x" tombstone, otherwise the key. */
    public String layout() {
        StringBuilder out = new StringBuilder();
        for (int i = 0; i < states.length; i++) {
            if (i > 0) {
                out.append(' ');
            }
            out.append(states[i] == EMPTY ? "." : states[i] == TOMBSTONE ? "x" : Integer.toString(keys[i]));
        }
        return out.toString();
    }
}

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

#pragma once
 
#include <cstddef>
#include <cstdint>
#include <optional>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
 
namespace bekadan::dsa {
 
// A teaching hash table with open addressing and tombstones. Integer keys live
// directly in one slot array. Probe i is at home + i (linear), home + i(i+1)/2
// (quadratic) or home + i*step (double hashing, step odd), all mod a power-of-two
// capacity, with home = floorMod(key, capacity). Removal leaves a tombstone.
// Capacity starts at 8 and doubles before an insert that would make
// (size + tombstones + 1) / capacity exceed 0.5. std::unordered_map uses chaining instead.
 
enum class Probing { linear, quadratic, double_hashing };
 
class OpenAddressingTable {
public:
    explicit OpenAddressingTable(Probing probing = Probing::linear) : probing_(probing) {}
 
    [[nodiscard]] int size() const { return size_; }
    [[nodiscard]] int tombstones() const { return tombstones_; }
    // Slots inspected, in every operation and during resizes.
    [[nodiscard]] int probes() const { return probes_; }
    [[nodiscard]] int capacity() const { return static_cast<int>(states_.size()); }
 
    void put(int key, int value) {
        const int cap = capacity();
        int index = home(key, cap), step = step_of(key, cap), tomb = -1;
        for (int i = 0; i < cap; ++i) {
            ++probes_;
            const State state = states_[at(index)];
            if (state == State::empty) {
                break;  // the key is not further along
            }
            if (state == State::tombstone) {
                if (tomb < 0) tomb = index;  // first reusable slot; keep probing
            } else if (keys_[at(index)] == key) {
                values_[at(index)] = value;
                return;
            }
            index = (index + advance(i + 1, step)) & (cap - 1);
        }
        if (2 * (size_ + tombstones_ + 1) > cap) {  // (used + 1) / capacity > 0.5
            resize();
            tomb = -1;
            index = first_empty(key);  // the slots moved: probe the new table
        }
        if (tomb >= 0) {
            index = tomb;
            --tombstones_;
        }
        states_[at(index)] = State::live;
        keys_[at(index)] = key;
        values_[at(index)] = value;
        ++size_;
    }
 
    [[nodiscard]] std::optional<int> get(int key) {
        const int cap = capacity();
        int index = home(key, cap), step = step_of(key, cap);
        for (int i = 0; i < cap; ++i) {
            ++probes_;
            const State state = states_[at(index)];
            if (state == State::empty) {
                break;  // an empty slot ends every probe sequence
            }
            if (state == State::live && keys_[at(index)] == key) {
                return values_[at(index)];
            }
            index = (index + advance(i + 1, step)) & (cap - 1);
        }
        return std::nullopt;
    }
 
    std::optional<int> remove(int key) {
        const int cap = capacity();
        int index = home(key, cap), step = step_of(key, cap);
        for (int i = 0; i < cap; ++i) {
            ++probes_;
            const State state = states_[at(index)];
            if (state == State::empty) {
                break;
            }
            if (state == State::live && keys_[at(index)] == key) {
                const int value = values_[at(index)];
                states_[at(index)] = State::tombstone;  // not empty: other keys may have probed past here
                --size_;
                ++tombstones_;
                return value;
            }
            index = (index + advance(i + 1, step)) & (cap - 1);
        }
        return std::nullopt;
    }
 
    // One token per slot: "." empty, "x" tombstone, otherwise the key.
    [[nodiscard]] std::string layout() const {
        std::string out;
        for (std::size_t i = 0; i < states_.size(); ++i) {
            if (i > 0) out += ' ';
            out += states_[i] == State::empty ? "." : states_[i] == State::tombstone ? "x" : std::to_string(keys_[i]);
        }
        return out;
    }
 
private:
    enum class State : std::uint8_t { empty, live, tombstone };
 
    static std::size_t at(int index) { return static_cast<std::size_t>(index); }
    static int home(int key, int capacity) { return ((key % capacity) + capacity) % capacity; }
    static int floor_div(int key, int capacity) { return (key - home(key, capacity)) / capacity; }
    // Odd, so it is coprime with the power-of-two capacity and reaches every slot.
    static int step_of(int key, int capacity) { return 2 * home(floor_div(key, capacity), capacity / 2) + 1; }
 
    // Distance from probe i - 1 to probe i.
    [[nodiscard]] int advance(int i, int step) const {
        switch (probing_) {
            case Probing::linear: return 1;
            case Probing::quadratic: return i;  // 1 + 2 + ... + i = i(i + 1)/2 in total
            case Probing::double_hashing: return step;
        }
        return 1;
    }
 
    void resize() {
        auto old_states = std::move(states_);
        auto old_keys = std::move(keys_);
        auto old_values = std::move(values_);
        const std::size_t cap = 2 * old_states.size();
        states_.assign(cap, State::empty);
        keys_.assign(cap, 0);
        values_.assign(cap, 0);
        tombstones_ = 0;  // tombstones are not copied
        for (std::size_t s = 0; s < old_states.size(); ++s) {
            if (old_states[s] == State::live) {
                const std::size_t t = at(first_empty(old_keys[s]));
                states_[t] = State::live;
                keys_[t] = old_keys[s];
                values_[t] = old_values[s];
            }
        }
    }
 
    int first_empty(int key) {
        const int cap = capacity();
        int index = home(key, cap), step = step_of(key, cap);
        for (int i = 0; i < cap; ++i) {
            ++probes_;
            if (states_[at(index)] == State::empty) return index;
            index = (index + advance(i + 1, step)) & (cap - 1);
        }
        throw std::logic_error("no empty slot");  // unreachable: at most half the slots are used
    }
 
    Probing probing_;
    std::vector<State> states_ = std::vector<State>(8, State::empty);
    std::vector<int> keys_ = std::vector<int>(8, 0);
    std::vector<int> values_ = std::vector<int>(8, 0);
    int size_ = 0;
    int tombstones_ = 0;
    int probes_ = 0;
};
 
}  // namespace bekadan::dsa

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