Collision Resolution in Hash Tables: Chaining vs Open Addressing

Compare chaining vs open addressing for hash collisions: probing, tombstones, load factor, CPython dict and Java HashMap, with Python and Java code.

Executive Summary: Every hash table must decide what to do when two keys land in the same slot, and the choice is chaining vs open addressing. Chaining stores colliding keys in a small list per bucket. Open addressing keeps every key in the slot array and probes for a free slot. Chaining tolerates high load and easy deletes, while open addressing wins on memory and cache locality but needs tombstones and a low load factor.
Chaining vs open addressing shown as linked buckets beside a probed slot array

A hash table that works in testing starts timing out in production. The keys are fine and the table is not full. But deletes have turned half the slots into markers that every lookup must step over, and one lookup now walks a long run of them. Collisions are not a rare event to patch. They are guaranteed, and the strategy for handling them shapes performance, memory, and deletion.

A collision happens when two different keys map to the same slot index. By the pigeonhole principle, any table with more possible keys than slots must have them. Chaining resolves collisions by keeping a list of entries in each bucket. Open addressing resolves them by storing entries directly in the slot array and following a probe sequence, a deterministic list of alternative slots for each key. The load factor is the number of entries divided by the number of slots.

The code targets Python 3.12 and Java 21. Big-O notation describes how running time grows with input size, and every bound below names its case. For the basics of buckets and resizing, see the guide to how hash tables work, buckets and load factor.

My position: the interesting question is not which strategy is faster. It is which failure mode you can afford. Chaining fails gracefully as load grows. Open addressing fails sharply near full, and deletes quietly raise its load.

How to recognize when you need to choose between chaining vs open addressing

You rarely pick a strategy in an interview by name. You pick it when you build or tune a table, or when you explain a library’s behavior. These signals tell you which side to lean on.

  • Frequent deletes. Chaining removes a node and is done. Open addressing leaves a tombstone, which is a marker for a deleted slot.
  • Memory pressure with small entries. Open addressing avoids a pointer and an object header per entry.
  • Scan-heavy or cache-sensitive lookups. Probing neighboring slots touches adjacent memory.
  • Load that might exceed 1. Only chaining can hold more entries than slots.
  • Adversarial or unknown keys. A flood of colliding keys hurts both, but the damage differs.

Separate chaining

Each bucket holds a list of the entries that hashed to it. A lookup computes the bucket index, then scans that one list comparing keys with equality. The hash narrows the search, and equality finishes it.

index   bucket
  0     -> (16:"a")
  1     (empty)
  2     -> (10:"b") -> (18:"c") -> (2:"d")
  3     (empty)
  4     -> (12:"e")
  ...
(hash = key, index = key mod 8; keys 10, 18, and 2 collide at index 2)

Chaining has two nice properties. The load factor can pass 1 without breaking anything, only slowing chains. And a delete is just unlinking one node. The cost is extra memory per entry (a node, a pointer) and worse cache behavior, since list nodes can sit anywhere in memory.

In Python, a small chained map. The injectable hash_fn lets tests force collisions:

import random
from typing import Any, Callable


class ChainedHashMap:
    def __init__(self, capacity: int = 8, max_load: float = 0.75,
                 hash_fn: Callable[[Any], int] = hash) -> None:
        self._buckets: list[list[tuple[Any, Any]]] = [[] for _ in range(capacity)]
        self._size = 0
        self._max_load = max_load
        self._hash_fn = hash_fn

    def _index(self, key: Any, capacity: int) -> int:
        return self._hash_fn(key) % capacity

    def put(self, key: Any, value: Any) -> None:
        bucket = self._buckets[self._index(key, len(self._buckets))]
        for i, (k, _) in enumerate(bucket):
            if k == key:
                bucket[i] = (key, value)
                return
        bucket.append((key, value))
        self._size += 1
        if self._size / len(self._buckets) > self._max_load:
            self._resize(len(self._buckets) * 2)

    def get(self, key: Any, default: Any = None) -> Any:
        for k, v in self._buckets[self._index(key, len(self._buckets))]:
            if k == key:
                return v
        return default

    def remove(self, key: Any) -> bool:
        bucket = self._buckets[self._index(key, len(self._buckets))]
        for i, (k, _) in enumerate(bucket):
            if k == key:
                del bucket[i]
                self._size -= 1
                return True
        return False

    def __len__(self) -> int:
        return self._size

    def longest_chain(self) -> int:
        return max(len(b) for b in self._buckets)

    def _resize(self, new_capacity: int) -> None:
        old = self._buckets
        self._buckets = [[] for _ in range(new_capacity)]
        for bucket in old:
            for k, v in bucket:
                self._buckets[self._index(k, new_capacity)].append((k, v))


if __name__ == "__main__":
    m = ChainedHashMap()
    assert m.get("x") is None and len(m) == 0         # empty table
    m.put("x", 1)
    m.put("x", 2)                                      # duplicate key updates
    assert m.get("x") == 2 and len(m) == 1
    assert not m.remove("missing") and m.remove("x") and len(m) == 0
    worst = ChainedHashMap(hash_fn=lambda k: 0)        # every key collides
    for i in range(50):
        worst.put(i, i * 2)
    assert len(worst) == 50 and worst.longest_chain() == 50
    assert worst.get(37) == 74 and worst.remove(37) and worst.get(37) is None
    rng = random.Random(11)
    for fn in (hash, lambda k: 0, lambda k: k % 5):
        t = ChainedHashMap(hash_fn=fn)
        ref: dict[int, int] = {}
        for _ in range(1500):
            key = rng.randint(0, 60)
            op = rng.randint(0, 2)
            if op == 0:
                t.put(key, key + 1)
                ref[key] = key + 1
            elif op == 1:
                assert t.remove(key) == (ref.pop(key, None) is not None)
            else:
                assert t.get(key) == ref.get(key)
            assert len(t) == len(ref)
    print("chaining tests passed")

The same design in Java:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.function.ToIntFunction;

public class ChainingDemo {

    static class ChainingMap<K, V> {
        private static class Node<K, V> {
            final K key;
            V value;
            Node<K, V> next;

            Node(K key, V value, Node<K, V> next) {
                this.key = key;
                this.value = value;
                this.next = next;
            }
        }

        private List<Node<K, V>> table;
        private int size;
        private final double maxLoad;
        private final ToIntFunction<K> hashFn;

        ChainingMap(int capacity, double maxLoad, ToIntFunction<K> hashFn) {
            this.table = newTable(capacity);
            this.maxLoad = maxLoad;
            this.hashFn = hashFn;
        }

        private static <K, V> List<Node<K, V>> newTable(int n) {
            List<Node<K, V>> t = new ArrayList<>(n);
            for (int i = 0; i < n; i++) t.add(null);
            return t;
        }

        private int index(K key, int capacity) {
            return Math.floorMod(hashFn.applyAsInt(key), capacity);
        }

        void put(K key, V value) {
            int i = index(key, table.size());
            for (Node<K, V> n = table.get(i); n != null; n = n.next) {
                if (n.key.equals(key)) {
                    n.value = value;
                    return;
                }
            }
            table.set(i, new Node<>(key, value, table.get(i)));
            size++;
            if ((double) size / table.size() > maxLoad) resize(table.size() * 2);
        }

        V get(K key) {
            for (Node<K, V> n = table.get(index(key, table.size())); n != null; n = n.next) {
                if (n.key.equals(key)) return n.value;
            }
            return null;
        }

        boolean remove(K key) {
            int i = index(key, table.size());
            Node<K, V> prev = null;
            for (Node<K, V> n = table.get(i); n != null; prev = n, n = n.next) {
                if (n.key.equals(key)) {
                    if (prev == null) table.set(i, n.next);
                    else prev.next = n.next;
                    size--;
                    return true;
                }
            }
            return false;
        }

        int size() {
            return size;
        }

        private void resize(int newCapacity) {
            List<Node<K, V>> old = table;
            table = newTable(newCapacity);
            for (Node<K, V> head : old) {
                for (Node<K, V> n = head; n != null; n = n.next) {
                    int i = index(n.key, newCapacity);
                    table.set(i, new Node<>(n.key, n.value, table.get(i)));
                }
            }
        }
    }

    static void check(boolean condition, String message) {
        if (!condition) throw new AssertionError(message);
    }

    public static void main(String[] args) {
        ChainingMap<Integer, Integer> m = new ChainingMap<>(8, 0.75, k -> k);
        check(m.get(1) == null && m.size() == 0, "empty");
        m.put(1, 10);
        m.put(1, 20);
        check(m.get(1) == 20 && m.size() == 1, "duplicate key updates");
        check(!m.remove(2) && m.remove(1) && m.size() == 0, "remove");

        List<ToIntFunction<Integer>> hashes = List.of(k -> k, k -> 0, k -> k % 5);
        Random rng = new Random(11);
        for (ToIntFunction<Integer> fn : hashes) {
            ChainingMap<Integer, Integer> t = new ChainingMap<>(8, 0.75, fn);
            Map<Integer, Integer> ref = new HashMap<>();
            for (int step = 0; step < 1500; step++) {
                int key = rng.nextInt(61);
                int op = rng.nextInt(3);
                if (op == 0) {
                    t.put(key, key + 1);
                    ref.put(key, key + 1);
                } else if (op == 1) {
                    check(t.remove(key) == (ref.remove(key) != null), "remove agrees");
                } else {
                    check(java.util.Objects.equals(t.get(key), ref.get(key)), "get agrees");
                }
                check(t.size() == ref.size(), "size agrees");
            }
        }
        System.out.println("PASS");
    }
}

Open addressing and probe sequences

Open addressing keeps every entry in the slot array itself. If the home slot is taken, the table tries another slot, then another, following the key’s probe sequence. A lookup follows the same sequence and stops at the key or at an empty slot. The invariant that makes this correct: every key sits on its probe sequence with no empty slot before it.

Scheme Probe for attempt i Clustering Notes
Linear probing (h + i) mod m Primary: runs of full slots grow Best cache locality, simplest code
Quadratic probing (h + c1*i + c2*i^2) mod m Secondary: same start means same path Needs constants chosen so every slot is reachable
Double hashing (h1 + i*h2) mod m Little of either h2 must be coprime with m, for example odd when m is a power of two

Primary clustering is the main weakness of linear probing. A long run of full slots is hit by more keys, so it grows faster, which makes it hit by even more keys. Quadratic probing jumps farther each step and breaks up runs. But two keys with the same home slot still follow one path, which is secondary clustering. Double hashing gives each key its own step size, and costs a second hash and worse locality.

The tombstone problem

Deleting from an open-addressed table is the classic trap. If you simply empty a slot, you may cut a probe sequence in two.

# WRONG: delete by marking the slot empty
def remove_wrong(keys: list, key: int, hash_fn) -> None:
    i = hash_fn(key) % len(keys)
    while keys[i] is not None:
        if keys[i] == key:
            keys[i] = None      # later keys in this run become unreachable
            return
        i = (i + 1) % len(keys)

Suppose keys 1, 2, and 3 all hash to slot 0, so they fill slots 0, 1, and 2. Remove key 1 by emptying slot 0. A lookup for key 2 starts at slot 0, sees empty, and reports “not found” although key 2 is in slot 1. The fix is a tombstone: a special marker that lookups skip over and inserts may reuse.

# RIGHT: leave a tombstone so probe sequences stay unbroken
TOMBSTONE = object()
# ... on finding the key at slot i:
keys[i] = TOMBSTONE

Tombstones have a cost. They count toward the load that slows probing, because a lookup cannot stop at one. A table that is mostly tombstones behaves like a nearly full table. Good implementations count tombstones in the load factor and rebuild the table when the total gets high.

In Python, a linear-probing map with tombstones. As in the chained version, hash_fn is injectable:

import random
from typing import Any, Callable

_EMPTY = object()
_TOMBSTONE = object()


class ProbingHashMap:
    def __init__(self, capacity: int = 8, max_load: float = 0.75,
                 hash_fn: Callable[[Any], int] = hash) -> None:
        self._keys: list[Any] = [_EMPTY] * capacity
        self._vals: list[Any] = [None] * capacity
        self._live = 0      # real entries
        self._used = 0      # real entries plus tombstones
        self._max_load = max_load
        self._hash_fn = hash_fn

    def _start(self, key: Any) -> int:
        return self._hash_fn(key) % len(self._keys)

    def put(self, key: Any, value: Any) -> None:
        cap = len(self._keys)
        if (self._used + 1) / cap > self._max_load:
            grow = (self._live + 1) / cap > self._max_load
            self._rebuild(cap * 2 if grow else cap)
        cap = len(self._keys)
        start = self._start(key)
        first_free = -1
        for step in range(cap):
            i = (start + step) % cap
            k = self._keys[i]
            if k is _EMPTY:
                target = first_free if first_free != -1 else i
                if first_free == -1:
                    self._used += 1
                self._keys[target] = key
                self._vals[target] = value
                self._live += 1
                return
            if k is _TOMBSTONE:
                if first_free == -1:
                    first_free = i     # reuse the first tombstone seen
            elif k == key:
                self._vals[i] = value
                return
        raise RuntimeError("table full")

    def get(self, key: Any, default: Any = None) -> Any:
        cap = len(self._keys)
        start = self._start(key)
        for step in range(cap):
            i = (start + step) % cap
            k = self._keys[i]
            if k is _EMPTY:
                return default
            if k is not _TOMBSTONE and k == key:
                return self._vals[i]
        return default

    def remove(self, key: Any) -> bool:
        cap = len(self._keys)
        start = self._start(key)
        for step in range(cap):
            i = (start + step) % cap
            k = self._keys[i]
            if k is _EMPTY:
                return False
            if k is not _TOMBSTONE and k == key:
                self._keys[i] = _TOMBSTONE
                self._vals[i] = None
                self._live -= 1
                return True
        return False

    def __len__(self) -> int:
        return self._live

    def _rebuild(self, new_capacity: int) -> None:
        old_keys, old_vals = self._keys, self._vals
        self._keys = [_EMPTY] * new_capacity
        self._vals = [None] * new_capacity
        self._live = self._used = 0
        for k, v in zip(old_keys, old_vals):
            if k is _EMPTY or k is _TOMBSTONE:
                continue
            i = self._start(k)
            while self._keys[i] is not _EMPTY:
                i = (i + 1) % new_capacity
            self._keys[i] = k
            self._vals[i] = v
            self._live += 1
            self._used += 1


if __name__ == "__main__":
    m = ProbingHashMap()
    assert m.get(5) is None and len(m) == 0 and not m.remove(5)   # empty table
    m.put(5, "a")
    m.put(5, "b")                                                  # duplicate key
    assert m.get(5) == "b" and len(m) == 1
    c = ProbingHashMap(hash_fn=lambda k: 0)                        # all keys collide
    for k in (1, 2, 3):
        c.put(k, k * 10)
    assert c.remove(1)                                             # tombstone at slot 0
    assert c.get(2) == 20 and c.get(3) == 30 and c.get(1) is None  # the case the wrong delete breaks
    c.put(4, 40)                                                   # reuses the tombstone
    assert len(c) == 3 and c.get(4) == 40
    t = ProbingHashMap(capacity=8, hash_fn=lambda k: k)
    for k in (10, 18, 2, 5):
        t.put(k, k)
    assert t.remove(18) and t.get(2) == 2
    t.put(26, 26)
    assert t._keys[3] == 26                                       # landed on the tombstone
    rng = random.Random(5)
    for fn in (hash, lambda k: 0, lambda k: k % 5):
        p = ProbingHashMap(hash_fn=fn)
        ref: dict[int, int] = {}
        for _ in range(1500):
            key = rng.randint(0, 60)
            op = rng.randint(0, 2)
            if op == 0:
                p.put(key, key + 1)
                ref[key] = key + 1
            elif op == 1:
                assert p.remove(key) == (ref.pop(key, None) is not None)
            else:
                assert p.get(key) == ref.get(key)
            assert len(p) == len(ref)
    print("probing tests passed")

The same design in Java:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.function.ToIntFunction;

public class ProbingDemo {

    static class ProbingMap<K, V> {
        private static final byte EMPTY = 0;
        private static final byte FULL = 1;
        private static final byte DELETED = 2;

        private List<K> keys;
        private List<V> vals;
        private byte[] state;
        private int live;
        private int used;
        private final double maxLoad;
        private final ToIntFunction<K> hashFn;

        ProbingMap(int capacity, double maxLoad, ToIntFunction<K> hashFn) {
            this.maxLoad = maxLoad;
            this.hashFn = hashFn;
            allocate(capacity);
        }

        private void allocate(int capacity) {
            keys = new ArrayList<>(capacity);
            vals = new ArrayList<>(capacity);
            for (int i = 0; i < capacity; i++) {
                keys.add(null);
                vals.add(null);
            }
            state = new byte[capacity];
            live = 0;
            used = 0;
        }

        private int start(K key) {
            return Math.floorMod(hashFn.applyAsInt(key), state.length);
        }

        void put(K key, V value) {
            int cap = state.length;
            if ((used + 1.0) / cap > maxLoad) {
                boolean grow = (live + 1.0) / cap > maxLoad;
                rebuild(grow ? cap * 2 : cap);
            }
            cap = state.length;
            int start = start(key);
            int firstFree = -1;
            for (int step = 0; step < cap; step++) {
                int s = (start + step) % cap;
                if (state[s] == EMPTY) {
                    int target = firstFree != -1 ? firstFree : s;
                    if (firstFree == -1) used++;
                    keys.set(target, key);
                    vals.set(target, value);
                    state[target] = FULL;
                    live++;
                    return;
                }
                if (state[s] == DELETED) {
                    if (firstFree == -1) firstFree = s;
                } else if (keys.get(s).equals(key)) {
                    vals.set(s, value);
                    return;
                }
            }
            throw new IllegalStateException("table full");
        }

        V get(K key) {
            int cap = state.length;
            int start = start(key);
            for (int step = 0; step < cap; step++) {
                int s = (start + step) % cap;
                if (state[s] == EMPTY) return null;
                if (state[s] == FULL && keys.get(s).equals(key)) return vals.get(s);
            }
            return null;
        }

        boolean remove(K key) {
            int cap = state.length;
            int start = start(key);
            for (int step = 0; step < cap; step++) {
                int s = (start + step) % cap;
                if (state[s] == EMPTY) return false;
                if (state[s] == FULL && keys.get(s).equals(key)) {
                    state[s] = DELETED;
                    keys.set(s, null);
                    vals.set(s, null);
                    live--;
                    return true;
                }
            }
            return false;
        }

        int size() {
            return live;
        }

        private void rebuild(int newCapacity) {
            List<K> oldKeys = keys;
            List<V> oldVals = vals;
            byte[] oldState = state;
            allocate(newCapacity);
            for (int j = 0; j < oldState.length; j++) {
                if (oldState[j] != FULL) continue;
                int s = start(oldKeys.get(j));
                while (state[s] != EMPTY) s = (s + 1) % newCapacity;
                keys.set(s, oldKeys.get(j));
                vals.set(s, oldVals.get(j));
                state[s] = FULL;
                live++;
                used++;
            }
        }
    }

    static void check(boolean condition, String message) {
        if (!condition) throw new AssertionError(message);
    }

    public static void main(String[] args) {
        ProbingMap<Integer, Integer> m = new ProbingMap<>(8, 0.75, k -> k);
        check(m.get(5) == null && m.size() == 0 && !m.remove(5), "empty");
        m.put(5, 1);
        m.put(5, 2);
        check(m.get(5) == 2 && m.size() == 1, "duplicate key");

        ProbingMap<Integer, Integer> c = new ProbingMap<>(8, 0.75, k -> 0);
        for (int k = 1; k <= 3; k++) c.put(k, k * 10);
        check(c.remove(1), "remove first of the run");
        check(c.get(2) == 20 && c.get(3) == 30 && c.get(1) == null, "tombstone keeps run intact");
        c.put(4, 40);
        check(c.size() == 3 && c.get(4) == 40, "tombstone reuse");

        List<ToIntFunction<Integer>> hashes = List.of(k -> k, k -> 0, k -> k % 5);
        Random rng = new Random(5);
        for (ToIntFunction<Integer> fn : hashes) {
            ProbingMap<Integer, Integer> p = new ProbingMap<>(8, 0.75, fn);
            Map<Integer, Integer> ref = new HashMap<>();
            for (int step = 0; step < 1500; step++) {
                int key = rng.nextInt(61);
                int op = rng.nextInt(3);
                if (op == 0) {
                    p.put(key, key + 1);
                    ref.put(key, key + 1);
                } else if (op == 1) {
                    check(p.remove(key) == (ref.remove(key) != null), "remove agrees");
                } else {
                    check(Objects.equals(p.get(key), ref.get(key)), "get agrees");
                }
                check(p.size() == ref.size(), "size agrees");
            }
        }
        System.out.println("PASS");
    }
}

Dry-run trace

Linear probing, 8 slots, hash equal to the key, so the home slot is key mod 8. Slots are listed from 0 to 7, with a dot for empty and T for a tombstone.

Step Operation Probe path Table after
1 put 10 slot 2 empty . . 10 . . . . .
2 put 18 slot 2 taken, slot 3 empty . . 10 18 . . . .
3 put 2 slots 2, 3 taken, slot 4 empty . . 10 18 2 . . .
4 put 5 slot 5 empty . . 10 18 2 5 . .
5 remove 18 slot 2 no, slot 3 match . . 10 T 2 5 . .
6 get 2 slot 2 no, slot 3 tombstone skipped, slot 4 match unchanged
7 put 26 slot 2 no, slot 3 tombstone noted, slots 4 and 5 no, slot 6 empty, so reuse slot 3 . . 10 26 2 5 . .

Load factor and the cost of a probe

Both strategies are fast at low load and slow at high load, but the shape differs. With chaining, expected chain length grows in step with the load factor, so cost rises gently and the table works at any load. With open addressing, cost explodes as the load approaches 1, because the free slots that end a search become rare. That is why open-addressed tables resize early. The difference matters for the amortized cost too: resizing rehashes every entry, but as with dynamic arrays (see arrays and amortized resizing), doubling keeps the average cost per insert constant.

You can measure this yourself instead of trusting a table of numbers. This script fills a linear-probing table with random keys and reports the average probes for a miss at several loads:

import random


def average_miss_probes(capacity: int, load: float, trials: int = 20) -> float:
    rng = random.Random(1)
    total = 0
    for _ in range(trials):
        taken = [False] * capacity
        for _ in range(int(capacity * load)):
            i = rng.randrange(capacity)
            while taken[i]:
                i = (i + 1) % capacity
            taken[i] = True
        for _ in range(capacity):
            i = rng.randrange(capacity)
            probes = 1
            while taken[i]:
                i = (i + 1) % capacity
                probes += 1
            total += probes
    return total / (trials * capacity)


for load in (0.3, 0.5, 0.7, 0.9, 0.95):
    print(load, round(average_miss_probes(4096, load), 2))

Run it and watch the jump between 0.7 and 0.95. The growth is far steeper than linear.

Side-by-side comparison of chaining vs open addressing

Use this table when you need the trade-offs in one place.

Property Chaining Open addressing
Load factor limit Can exceed 1 Must stay below 1, usually well below
Delete Unlink a node Tombstone, or backward shifting in some designs
Memory per entry Entry plus a node and pointer Entry only, plus empty slots
Cache behavior Pointer chasing Contiguous probes (best with linear probing)
Expected lookup (uniform hashing) O(1 + load factor) Grows sharply as load nears 1
Worst-case lookup O(n), all keys in one bucket O(n), one long probe run
Clustering None across buckets Primary or secondary, by scheme
Iteration Over buckets and chains Over the slot array, skipping empties

CPython dict and Java HashMap: two real answers

The two languages you likely use made opposite choices, and both are documented in source code.

CPython uses open addressing. In the 3.12 dictobject.c source, the probe step is i = mask & (i*5 + perturb + 1), and perturb is shifted right by 5 bits each step. So the probe sequence depends on all bits of the hash, not only the low ones, which breaks up clusters. The same file defines usable space as two thirds of the slots (USABLE_FRACTION(n) is (n << 1)/3), so a dict resizes when it is about two thirds full. In 3.12 the growth rate is three times the number of used entries.

Java uses chaining, with a twist. In the Java 21 HashMap.java source, the default load factor is 0.75 and the default capacity is 16. A bin turns into a balanced tree when it reaches TREEIFY_THRESHOLD = 8 entries, but only if the table has at least MIN_TREEIFY_CAPACITY = 64 slots. In a smaller table the map resizes instead. A tree bin shrinks back to a list at UNTREEIFY_THRESHOLD = 6. Keys that implement Comparable can be ordered inside a tree bin, which caps the worst-case bin cost at O(log n) rather than O(n). The same source also spreads the hash with h ^ (h >>> 16) so high bits influence the index of a small table. For how a balanced-tree bin searches, see binary search tree insert, delete, and validation.

A myth worth correcting: “Open addressing is always faster because of cache locality.” Locality helps at moderate load. But CPython also keeps entries in a separate compact array. A lookup touches an index array and then an entry. Measure your own workload before deciding on chaining vs open addressing.

Robin Hood hashing and hash flooding

Robin Hood hashing is a refinement of linear probing. On insert, if the incoming key has traveled farther from its home slot than the resident key, they swap and the displaced key keeps probing. This evens out probe lengths. Deletion can then shift later entries back instead of leaving tombstones. It is worth knowing at this orientation level, not as an interview implementation.

Hash flooding is an attack where someone chooses keys that all collide, turning O(1) average lookups into O(n) and an input of n keys into O(n^2) work. Two defenses exist. Randomize the hash function: Python’s documentation says the hash values of str and bytes are salted with an unpredictable random value by default. Or bound the damage, as Java’s tree bins do for comparable keys.

A mistake I see often in design discussions is a candidate who proposes open addressing and then supports deletes by emptying the slot. The bug does not show in a happy-path test. It shows only when a deleted key sits earlier in a probe run than a key you look up afterwards. I now ask for that exact test, delete then look up a neighbor, before accepting any open-addressing design.

Complexity of both strategies

Operation Chaining Open addressing
Insert O(1) expected, O(n) worst; resize is O(n) but amortized O(1) expected at low load, O(n) worst; resize amortized
Lookup O(1 + load factor) expected, O(n) worst O(1) expected at low load, O(n) worst
Delete O(1 + load factor) expected, O(n) worst Same as lookup, plus a tombstone
Space O(n + m) for n entries and m buckets, plus nodes O(m) slots, with m at least n divided by the max load

The “expected” cases assume hash values spread keys evenly. The worst case is a bad hash function or hostile input. Neither strategy removes the worst case. Both rely on a good hash function and a bounded load factor.

Where this shows up in real systems

  • Python dictionaries. The CPython source shows open addressing with perturbed probing, so every dict and every object attribute table follows these rules.
  • Java HashMap and HashSet. Chaining with tree bins keeps lookups bounded for comparable keys, per the JDK source above.
  • Defense against hash flooding. Python’s salted string hashes and Java’s tree bins are two documented mitigations for hostile keys.
  • Language runtimes and database engines. Systems that build hash tables for joins or symbol tables face the same trade-off: probing for density and cache locality, chaining for simplicity and easy deletes.

How to explain it in an interview

  1. Define the collision. Two keys, one slot, unavoidable by the pigeonhole principle.
  2. Give both strategies in a sentence each. Chaining: a list per bucket. Open addressing: probe to another slot.
  3. Name the invariant. For probing: no empty slot between a key’s home and its position. This is why deletes need tombstones.
  4. State the load factor rule. Chaining can pass 1. Probing must stay below it, with tombstones counted.
  5. Give complexity with its case. Expected O(1), worst O(n), amortized O(1) resize.

Expect these follow-ups: “How does Java defend against many collisions?” (tree bins). “What happens when you delete?” (tombstones). “Why does linear probing cluster?” (runs attract keys). A weak answer says both are O(1). A strong answer says when each is O(1) and when it is O(n).

Chaining vs open addressing: a decision framework

  1. Will deletes be frequent? Prefer chaining, or open addressing with backward shifting or periodic rebuilds.
  2. Is memory or cache locality the constraint? Prefer open addressing with linear probing and a low load factor.
  3. Can the load factor go above 1, or vary a lot? Prefer chaining.
  4. Might keys be hostile? Randomize the hash, and prefer a design that bounds the worst case, such as tree bins.
  5. Are keys small and fixed in size? Open addressing stores them inline and saves the node overhead.

When not to use each strategy

  • Do not use plain linear probing with a poor hash. Sequential or patterned keys create long runs. Use a better hash or a different probe scheme.
  • Do not use open addressing for delete-heavy tables without a rebuild plan. Tombstones accumulate and slow every lookup. Chaining or periodic rebuilds fix that.
  • Do not use chaining with huge numbers of tiny entries when memory is tight. Each node adds a pointer and an object header. Open addressing stores the entries inline.
  • Do not hand-roll either when a library will do. The built-in dict and HashMap already handle resizing, hostile keys, and edge cases. See the guide to frequency counting and Two Sum with hash maps for using them well.

Common mistakes

  • Emptying a slot on delete. Keys later in the probe run become unreachable. Input: keys 1, 2, 3 all hash to slot 0, delete 1, look up 2.
  • Ignoring tombstones in the load factor. A table full of tombstones has no empty slot, so a miss can scan every slot. Count live entries plus tombstones.
  • Forgetting the equality check. A matching hash is not a matching key. Compare keys with equality before returning a value.
  • Using a probe step not coprime with the table size. Double hashing with a step that shares a factor with the capacity visits only some slots and can miss an empty one.
  • Stopping a lookup at a tombstone. A tombstone means “keep going”, while only an empty slot means “absent”.
  • Assuming the worst case cannot happen. Colliding keys turn O(1) into O(n). Input: every key hashes to 0.

Practice problems

Problem Difficulty The twist
Design HashSet Easy Pick chaining or probing and handle duplicate adds
Design HashMap Easy Update on a repeated key and delete from a chain
Two Sum Easy Rely on average O(1) lookups and explain the worst case
Longest Consecutive Sequence Medium Set membership must stay near O(1) to keep O(n)
Design a Linear Probing Table with Delete Medium Tombstones and the load factor including tombstones
Implement a Resizable Hash Map Medium Rehash every entry into the new capacity
Design an LRU Cache Medium A hash map with O(1) delete pairs with a linked list
Robin Hood Hash Table Hard Swap on probe distance and shift backward on delete

Key takeaways

  • Collisions are certain, so every hash table needs a strategy.
  • Chaining keeps a list per bucket, works at any load, and deletes easily.
  • Open addressing stores entries in the array, saves memory, and needs a low load factor.
  • Never empty a slot on delete in open addressing. Leave a tombstone.
  • Count tombstones in the load factor, and rebuild when they pile up.
  • CPython uses open addressing with perturbed probing, while Java uses chaining with tree bins at 8 entries and a 64-slot table.
  • Say expected O(1) and worst O(n), and name the defense against hostile keys.

Frequently Asked Questions

What is the difference between chaining and open addressing?

Chaining stores all keys that hash to the same bucket in a list inside that bucket. Open addressing stores every key in the slot array and probes other slots when the home slot is taken.

Does Python use chaining or open addressing for dict?

CPython dictionaries use open addressing with a perturbed probe sequence. Java HashMap, by contrast, uses chaining and converts long bins into trees.

Why do open addressing tables need tombstones?

A lookup stops at the first empty slot, so emptying a deleted slot can hide keys that were placed after it. A tombstone marks the slot as deleted but not empty, so lookups continue past it.

What load factor should a hash table use?

Chaining tables commonly resize near a load factor of 0.75, and Java HashMap defaults to that value. Open addressing tables need a lower limit because probe lengths grow quickly near full, and CPython resizes at about two thirds.

Match the strategy to the failure you can afford

Chaining degrades slowly and deletes cleanly. Open addressing packs tightly and probes fast, but it needs tombstones and an early resize. Settle chaining vs open addressing by asking what your workload does most: delete, scan, or run near capacity. More fundamentals like this are collected in the DSA guides hub.

Rule of thumb: chaining bends under load, open addressing breaks near full, so keep it well below full.

Originally posted on 2 December 2026 and post last modified on 2 December 2026

Coding Interviews Data Structures Hash Maps Hashing

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *