M10 · Hash Tables and Sets

Open Addressing: Probing and Tombstones

Open addressing stores every entry directly in the slot array. When a key's home slot is taken, the table follows a fixed probe sequence to other slots. That keeps memory compact and cache friendly, but it makes deletion subtle and punishes high load factors. This lesson steps through three probe rules, tombstones and resizing, and compares them with what real runtimes do.

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

You will be able to

  • Compute the probe sequence of a key under linear probing, quadratic probing and double hashing, and say why each one reaches every slot of a power-of-two table.
  • Explain primary and secondary clustering and which probe rule suffers from which.
  • Explain why deletion leaves a tombstone, how lookups and inserts treat tombstones, and why tombstones count toward the load.
  • Relate the expected number of probes to the load factor, and explain why open-addressing tables resize well before they are full.
  • Describe how CPython's dict probes (the perturbation recurrence) and which built-in tables use chaining instead.

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.

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

The chaining lesson gave every bucket its own list. Open addressing has no lists at all: there is one array of slots, and each slot holds at most one entry. If a key's home slot is already taken by another key, the table tries other slots in a fixed order, the key's probe sequence, and uses the first free one.

Think of a car park where every car has an assigned space. If someone is already parked there, you do not leave; you drive along a route that is the same every time for your car, and park in the first free space on it. To find your car later you start at your assigned space and follow the same route. If you reach an empty space before you find the car, it is not in the car park: you would have parked there.

That last sentence is the whole contract of open addressing:

  • Insert follows the key's probe sequence to the first free slot.
  • Lookup follows the same sequence and stops at the key, or at the first empty slot.

The lab starts with 8 slots and uses home = floorMod(key, capacity), like the chaining lab.

Three probe rules

Probe number i (starting at 0) inspects one slot. All three rules start at the home slot and work modulo the capacity, which is a power of two here.

Rule Probe i is at Key 9, capacity 8
Linear probing home + i 1, 2, 3, 4, 5, 6, 7, 0
Quadratic probing (triangular numbers) home + i(i + 1)/2 1, 2, 4, 7, 3, 0, 6, 5
Double hashing home + i · step, step from a second hash step 3: 1, 4, 7, 2, 5, 0, 3, 6

A probe sequence must eventually visit every slot; otherwise an insert could fail while free slots exist. Each rule above does, for a power-of-two capacity:

  • Linear: trivially, one slot at a time.
  • Quadratic with triangular numbers: the offsets 0, 1, 3, 6, 10, … are distinct modulo any power of two for the first capacity probes. Plain squares (0, 1, 4, 9, …) do not have this property; with them the usual guarantee is weaker (a prime capacity and a load factor at most 0.5).
  • Double hashing: the lab uses step = 2 · floorMod(floorDiv(key, capacity), capacity / 2) + 1. The step is always odd, so it shares no factor with a power of two, and stepping by it visits every slot before repeating. It is computed from the bits above the home slot on purpose: keys with the same home usually get different steps.

In the implementations the next slot is computed incrementally: add 1 (linear), add i (quadratic, because 1 + 2 + … + i is the triangular number) or add step (double hashing), then mask with capacity − 1. No multiplication can overflow.

Clustering

Run the first three presets of the lab. They insert the same keys, 1, 9, 17 and 2, and then look up the missing key 33. Keys 1, 9, 17 and 33 all have home slot 1.

  • Linear probing stores 1, 9, 17 in slots 1, 2, 3, and then key 2, whose home is slot 2, has to walk past them to slot 4. One run of occupied slots grew from two different homes. That is primary clustering: a run attracts more keys, because every key whose home falls anywhere in the run lands at its end, making it longer still. get(33) needs 5 probes.
  • Quadratic probing jumps away from the home slot (1, 2, 4, 7, …), so key 2 finds slot 3 free after one extra probe, and get(33) needs 4 probes. Keys with the same home still follow the same sequence, though: secondary clustering.
  • Double hashing gives 9 and 17 steps 3 and 5, so they leave slot 1 in different directions and key 2 goes straight into its home slot. get(33) needs 3 probes. Different keys with the same home follow different sequences, which removes secondary clustering too (unless the step also matches).

Linear probing has one big advantage in real hardware: its probes touch neighbouring slots, often in the same cache line. That is why careful implementations still use it, or variations of it, and keep the load low instead.

How many probes?

Under the standard modelling assumption that keys hash uniformly and independently, Knuth's analysis of linear probing gives, for a table with load factor α = n / capacity:

successful lookup    ≈ ½ · (1 + 1 / (1 − α))
unsuccessful lookup  ≈ ½ · (1 + 1 / (1 − α)²)       (also the cost of inserting a new key)

For an idealised "uniform hashing" scheme, where every probe sequence behaves like a random order of all slots (double hashing comes close), an unsuccessful lookup costs about 1 / (1 − α) probes.

α Linear, successful Linear, unsuccessful Uniform hashing, unsuccessful
0.25 1.17 1.39 1.33
0.5 1.5 2.5 2
0.75 2.5 8.5 4
0.9 5.5 50.5 10

Compare that with chaining, where an unsuccessful lookup costs about α comparisons and the table can work happily above α = 1. In open addressing α can never exceed 1, and the cost explodes as α approaches it. So open-addressing tables resize early. The teaching table resizes before an insert that would push the load above 0.5; CPython's dict allows about 2/3.

With the load kept below a constant, every operation is expected O(1), inserts amortized (because of resizing), and O(n) in the worst case, when many keys share a probe path.

Deletion and tombstones

Run the Tombstones on delete preset. Keys 1 and 9 both have home slot 1, so 9 lives in slot 2. Now remove 1. If slot 1 simply became empty, get(9) would start at slot 1, see an empty slot, and conclude that 9 is absent, which is wrong. Deleting an entry would make unrelated entries unreachable.

So removal writes a tombstone (also called a deleted or dummy marker) instead:

  • Lookups treat a tombstone as occupied: keep probing.
  • Inserts may reuse it, but only after making sure the key is not stored further along. put remembers the first tombstone it passes, keeps probing until it finds the key (then it updates in place) or an empty slot (then the key is new and goes into the remembered tombstone). In the preset, put(9, 99) passes the tombstone in slot 1 and finds 9 in slot 2: an update, not a second copy of 9. put(17, 17) reaches an empty slot, so it reuses slot 1.
put(key, value):
    tomb = none
    for each slot s in probe sequence of key:
        if s is EMPTY: break                       # key is not in the table
        if s is TOMBSTONE: tomb = tomb or s        # reusable, keep looking
        else if s.key == key: s.value = value; return
    if (size + tombstones + 1) / capacity > 0.5:
        resize(); tomb = none; s = first empty slot in the new table
    store (key, value) in tomb if there is one, else in s

Tombstones have a cost: they never end a probe sequence, so a table full of tombstones is as slow to search as a full table, even if it holds almost nothing. That is why the teaching table counts them in its load check. Run Load factor 0.5 and resize: after three removals the table holds 1 key and 3 tombstones, so the next new key would make (1 + 3 + 1) / 8 = 0.625, and it resizes. A resize reinserts only live keys, so all tombstones disappear.

For linear probing there is an alternative that needs no tombstones: after emptying a slot, scan the rest of the run and move back any entry that would otherwise become unreachable (often called backward-shift deletion). Quadratic probing and double hashing have no simple equivalent.

Resizing

A key's home depends on the capacity, so a resize must place every live key again, exactly as with chaining. The lab shows the new slot array next to the old one while keys move; each reinsertion probes the new table, which has no tombstones, for the first empty slot. One resize costs O(n), but doubling makes them rare, so n inserts cost O(n) in total: amortized O(1) per insert.

Costs

Operation Expected (good hash, bounded load) Worst case
get, contains O(1) O(n): one long probe path
put (new key) amortized O(1) O(n)
put (existing key) O(1) O(n)
remove O(1) (writes a tombstone) O(n)
iterate all entries O(capacity) O(capacity)
space O(capacity), no per-entry nodes or pointers

What real runtimes do

Strategy Notes
Python dict open addressing perturbation probing, dummy markers, grows at about 2/3
Python set open addressing its own implementation in setobject.c
C# Dictionary<K,V>, HashSet<T> chaining chains are next indices inside one entries array
Java HashMap, HashSet chaining a crowded bin becomes a red-black tree
Java IdentityHashMap linear probing documented as "a simple linear-probe hash table"
C++ std::unordered_map chaining the bucket interface and reference stability effectively require it

CPython's dict deserves a closer look, because its design is explained in long comments inside Objects/dictobject.c. Since Python 3.6 a dict is compact: a dense array of entries (hash, key, value) in insertion order, plus a sparse index table whose slots hold small integers pointing into that array. Only the index table is probed. Its size is a power of two (at least 8), and a slot holds an entry index, DKIX_EMPTY or DKIX_DUMMY. The dummy is CPython's tombstone: deleting a key sets its index slot to DKIX_DUMMY and clears the entry.

Probing starts at i = hash & mask and continues with

perturb >>= 5                      # PERTURB_SHIFT
i = (i * 5 + perturb + 1) & mask

where perturb starts as the full hash. The first few probes therefore mix in the higher bits of the hash, which matters because CPython's hashes of small integers are the integers themselves and would otherwise collide on their low bits. Once perturb has shifted down to zero, the recurrence becomes i = 5i + 1 mod 2ᵏ, which visits every slot, so the search always terminates. The number of entries the table can hold before it must grow is USABLE_FRACTION, about two thirds of the index table size; growing builds a new index table and compacts the entries, which drops deleted ones, just like the lab's resize.

Open addressing is also the design of several widely used high-performance tables outside the standard libraries discussed here. Abseil's "Swiss tables" (C++) probe groups of slots using a separate array of one-byte metadata, and Rust's standard HashMap is a port of that design.

The teaching implementation

The four listings implement the lab's model exactly: three parallel arrays (state, key, value) where the state is empty, live or tombstone; capacity 8, doubling when 2 · (size + tombstones + 1) > capacity; floorMod homes (Python's % floors already; Java uses Math.floorMod and Math.floorDiv; C# and C++ use ((k % c) + c) % c); the incremental probe step. Each table counts the slots it inspects, and every language runs one shared fixture that checks the returned values, size, capacity, number of tombstones, the final slot layout and the exact probe count, in all three modes. Each language also replays random put, get and remove sequences against its built-in map.

Common mistakes

  • Emptying a slot on delete. Later lookups stop early and lose keys stored past it.
  • Inserting into the first tombstone without checking further. The key may already exist further along, and you get two copies of one key.
  • Stopping a lookup at a tombstone. A tombstone means "keep going".
  • Ignoring tombstones in the load factor. After many removals and inserts, every unsuccessful search walks the whole table.
  • A probe sequence that skips slots, such as plain squares with a power-of-two capacity, or an even double-hashing step: inserts can fail while free slots remain.
  • Letting the load get close to 1. Probe counts grow like 1 / (1 − α)² with linear probing.

Edge cases

  • Lookup on an empty table: the home slot is empty, one probe, not found.
  • Wraparound: key 15 in a table of 8 has home 7; if slot 7 is taken it continues at slot 0.
  • Removing a missing key: probes to an empty slot, reports it, changes nothing.
  • put of an existing key never resizes, even when the table is at its load limit.
  • A new key that will reuse a tombstone does not raise the number of used slots, but the teaching table still checks the load first, so it may resize a little earlier than strictly necessary.
  • Negative keys: floorMod(−1, 8) = 7; floorDiv(−1, 8) = −1, giving double-hashing step 7.

Worked practice

1. Give the first four probe slots of key 25 in an 8-slot table under each rule.

Answer

Home is 25 mod 8 = 1. Linear: 1, 2, 3, 4. Quadratic: offsets 0, 1, 3, 6, so 1, 2, 4, 7. Double hashing: floorDiv(25, 8) = 3, floorMod(3, 4) = 3, step = 7, so 1, 0, 7, 6.

2. Slots 3, 4, 5 hold keys 3, 11, 19 (linear probing, capacity 8). You remove 11 and then call put(19, 0). What must happen, and what would go wrong with a careless implementation?

Answer

Slot 4 becomes a tombstone. put(19, 0) probes 3 (key 3), 4 (tombstone, remembered), 5 (key 19): it updates 19 in place. A careless version that inserts into the first tombstone would store a second 19 in slot 4; a later remove(19) would delete only one of them, and get(19) would return the stale copy.

3. Using Knuth's approximation, how many probes does inserting a new key cost on average with linear probing at α = 0.75, and at α = 0.5?

Answer

½(1 + 1/(1 − 0.75)²) = ½(1 + 16) = 8.5 probes at 0.75, and ½(1 + 4) = 2.5 at 0.5. Halving the spare room more than triples the cost, which is why the teaching table resizes at 0.5.

4. In CPython, a key with hash 33 is looked up in an index table of 8 slots. Which slots are probed first?

Answer

mask = 7, so the first slot is 33 & 7 = 1. Then perturb = 33 >> 5 = 1 and i = (1·5 + 1 + 1) & 7 = 7. Then perturb = 0 and i = (7·5 + 0 + 1) & 7 = 36 & 7 = 4. So 1, 7, 4, and from then on the plain 5i + 1 recurrence.

5. Why does the lab's double hashing compute the step from floorDiv(key, capacity) rather than from the key's home slot?

Answer

Keys that collide have the same home. A step derived from the home would be the same for all of them, so they would share one probe sequence, the secondary clustering double hashing is meant to avoid. The quotient carries the bits the home threw away, so colliding keys such as 1, 9 and 17 get steps 1, 3 and 5.

Summary

  • Open addressing keeps entries in the slot array and resolves collisions by probing a fixed, key-specific sequence of slots; a lookup ends at the key or at an empty slot.
  • Linear probing is cache friendly but forms primary clusters; quadratic probing avoids those but not secondary clustering; double hashing avoids both.
  • Deletion writes a tombstone; lookups skip it, inserts reuse it only after confirming the key is absent, and the load check counts it.
  • Expected probe counts grow sharply as α → 1, so these tables resize early (0.5 here, about 2/3 in CPython); with that, operations are expected O(1).
  • CPython's dict and set use open addressing (dict with the perturbation recurrence and DKIX_DUMMY tombstones); .NET's Dictionary, Java's HashMap and C++'s unordered_map use chaining.

Full implementation

The open-addressing table in four languages, each checked against one shared fixture (linear, quadratic and double hashing; collisions, wraparound, tombstones, reuse, resizes, negative keys) including the final slot layout and the exact number of probes, and 900 random put/get/remove sequences (300 per probing mode) compared with the language's built-in map (Dictionary, dict, HashMap, std::unordered_map).

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

References