TExcelTAD
Home › Data Structures: Hashing, Search Trees, B-Trees & Union-Find › Open Addressing: Linear, Quadratic and Double Hashing

Open Addressing: Linear, Quadratic and Double Hashing

Chaining stores colliding keys outside the table, in lists. Open addressing stores every key in the table itself: there are no lists and no pointers, each slot holds one key or is empty. When a key's slot is taken, the table tries another slot, then another, following a fixed probe sequence for that key until it finds the key or an empty slot. The table can never hold more than mm keys, so the load factor α=n/m\alpha = n/m is at most 1.

Open addressing saves the memory of the pointers and keeps everything in one contiguous array, which modern caches love. Python's dict and set, Rust's HashMap and many C++ libraries (abseil's flat_hash_map, for example) use it.

Probe sequences

The hash function now takes a second argument, the probe number i=0,1,2,…i = 0, 1, 2, \ldots:

h:U×{0,1,…,m−1}→{0,1,…,m−1}h : U \times \{0, 1, \ldots, m - 1\} \to \{0, 1, \ldots, m - 1\}

and the probe sequence of key kk is h(k,0),h(k,1),…,h(k,m−1)h(k, 0), h(k, 1), \ldots, h(k, m - 1). It should be a permutation of all mm slots, so that an insertion succeeds whenever there is room. The three classic choices build h(k,i)h(k, i) from ordinary hash functions h1h_1 and h2h_2:

Method h(k,i)h(k, i) Distinct probe sequences
linear probing (h1(k)+i) mod m(h_1(k) + i) \bmod m mm
quadratic probing (h1(k)+c1i+c2i2) mod m(h_1(k) + c_1 i + c_2 i^2) \bmod m mm
double hashing (h1(k)+i⋅h2(k)) mod m(h_1(k) + i \cdot h_2(k)) \bmod m up to m2m^2

For double hashing, h2(k)h_2(k) must be relatively prime to mm, or the sequence only visits part of the table; with mm prime, any h2(k)∈{1,…,m−1}h_2(k) \in \{1, \ldots, m - 1\} works. The animations use h1(k)=k mod mh_1(k) = k \bmod m, quadratic probing with c1=0c_1 = 0, c2=1c_2 = 1, and h2(k)=1+(k mod (m−1))h_2(k) = 1 + (k \bmod (m - 1)).

text
OA-INSERT(T, k)                          OA-SEARCH(T, k)
1  for i = 0 to m - 1                    1  for i = 0 to m - 1
2      j = h(k, i)                       2      j = h(k, i)
3      if T[j] == NIL or T[j] == DEL     3      if T[j] == k
4          T[j] = k                      4          return j
5          return j                      5      if T[j] == NIL
6  error "table overflow"                6          return NIL           // an empty slot ends the search
                                         7  return NIL

This OA-INSERT assumes kk is not yet in the table. The search stops at the first truly empty slot: if kk were stored, its insertion would have used that slot or an earlier one.

Deletion needs tombstones

Deleting a key by emptying its slot would break every search that once probed past it: the empty slot would end the search too early. So deletion writes a special marker DEL (a tombstone). Searches treat DEL as occupied and keep probing; insertions may reuse it. The animation, like the Python code below, inserts with a full search first (so that a key is never stored twice) and then reuses the first tombstone it passed.

The Python table prints the probe sequence of each operation, the same probes as the animation's frames.

python · try it yourself
EMPTY, DEL = None, "DEL"

class OpenTable:
    def __init__(self, m, probe):
        self.m, self.slots, self.probe = m, [EMPTY] * m, probe
    def h(self, k, i):
        m = self.m
        if self.probe == "linear":    return (k + i) % m
        if self.probe == "quadratic": return (k + i * i) % m
        return (k + i * (1 + k % (m - 1))) % m          # double hashing
    def _find(self, k):
        """probe until k or an empty slot; returns (slot of k or None, first DEL seen, probes)"""
        first_del, probes = None, []
        for i in range(self.m):
            j = self.h(k, i)
            probes.append(j)
            if self.slots[j] == k:
                return j, first_del, probes
            if self.slots[j] is EMPTY:
                return None, first_del, probes
            if self.slots[j] == DEL and first_del is None:
                first_del = j
        return None, first_del, probes
    def put(self, k):
        j, first_del, probes = self._find(k)
        if j is None:
            j = first_del if first_del is not None else probes[-1]
            assert self.slots[j] in (EMPTY, DEL), "table overflow"
            self.slots[j] = k
        return probes, j
    def get(self, k):
        j, _, probes = self._find(k)
        return probes, j
    def remove(self, k):
        j, _, probes = self._find(k)
        if j is not None:
            self.slots[j] = DEL
        return probes, j

def run(probe):
    t = OpenTable(11, probe)
    print(f"--- {probe} probing")
    for op in ["put 22", "put 1", "put 13", "put 11", "put 24", "put 33", "get 33", "remove 13", "get 24", "put 2"]:
        name, k = op.split()
        probes, j = getattr(t, name)(int(k))
        print(f"{op:9}: probes {probes} -> slot {j}")
    print("table:", ["." if s is None else s for s in t.slots])

run("linear")
run("double")
--- linear probing
put 22   : probes [0] -> slot 0
put 1    : probes [1] -> slot 1
put 13   : probes [2] -> slot 2
put 11   : probes [0, 1, 2, 3] -> slot 3
put 24   : probes [2, 3, 4] -> slot 4
put 33   : probes [0, 1, 2, 3, 4, 5] -> slot 5
get 33   : probes [0, 1, 2, 3, 4, 5] -> slot 5
remove 13: probes [2] -> slot 2
get 24   : probes [2, 3, 4] -> slot 4
put 2    : probes [2, 3, 4, 5, 6] -> slot 2
table: [22, 1, 2, 11, 24, 33, '.', '.', '.', '.', '.']
--- double probing
put 22   : probes [0] -> slot 0
put 1    : probes [1] -> slot 1
put 13   : probes [2] -> slot 2
put 11   : probes [0, 2, 4] -> slot 4
put 24   : probes [2, 7] -> slot 7
put 33   : probes [0, 4, 8] -> slot 8
get 33   : probes [0, 4, 8] -> slot 8
remove 13: probes [2] -> slot 2
get 24   : probes [2, 7] -> slot 7
put 2    : probes [2, 5] -> slot 2
table: [22, 1, 2, '.', 11, '.', '.', 24, 33, '.', '.']

With double hashing the same keys spread out: keys 11 and 33, which both hash to slot 0, step by 2 and by 4, so they leave the crowded start of the table at once, and no operation needs more than three probes. The second animation shows this run.

Primary clustering

Linear probing has a serious flaw, visible in the first run. Occupied slots form runs (clusters), and a key that hashes anywhere into a run must walk to its end and then makes the run longer. An empty slot just after a run of length ℓ\ell is filled next with probability (ℓ+1)/m(\ell + 1)/m, not 1/m1/m, so long runs grow faster than short ones. That is primary clustering. put 33 walked through a run of five occupied slots (six probes), although only two of the keys in that run, 22 and 11, share its home slot 0.

Quadratic probing avoids runs of consecutive slots, but two keys with the same h1h_1 still have the same probe sequence: secondary clustering. It has another catch: with c1=0c_1 = 0, c2=1c_2 = 1 and mm prime, the sequence k+i2k + i^2 visits only (m+1)/2(m + 1)/2 distinct slots, so an insertion can fail when the table is more than half full. Double hashing gives each key its own step size, and comes close to the ideal analysed in the next lesson.

python · try it yourself
import random

def avg_insert_probes(probe, m, n, rng):
    slots = [None] * m
    total = 0
    for k in rng.sample(range(10 ** 6), n):
        step = 1 + k % (m - 1)
        for i in range(m):
            j = (k + i) % m if probe == "linear" else (k + i * step) % m
            total += 1
            if slots[j] is None:
                slots[j] = k
                break
    return total / n, slots

rng = random.Random(1)
m = 1009                                          # a prime
for alpha in [0.5, 0.75, 0.9]:
    n = int(alpha * m)
    lin, slots = avg_insert_probes("linear", m, n, rng)
    dbl, _ = avg_insert_probes("double", m, n, rng)
    runs, run = [], 0
    for s in slots + slots[:1]:                    # longest run of occupied slots (linear)
        run = run + 1 if s is not None else 0
        runs.append(run)
    print(f"alpha {alpha:.2f}: avg probes per insert, linear {lin:5.2f}, double {dbl:5.2f}; longest linear run {max(runs)}")
alpha 0.50: avg probes per insert, linear  1.50, double  1.41; longest linear run 14
alpha 0.75: avg probes per insert, linear  2.39, double  1.77; longest linear run 98
alpha 0.90: avg probes per insert, linear  4.30, double  2.65; longest linear run 103

The gap widens with the load: at α=0.9\alpha = 0.9 linear probing needs about 60% more probes per insert than double hashing, and its occupied slots have merged into runs of about a hundred. Linear probing is still popular, because consecutive probes touch the same cache line, which often makes it faster in practice at moderate load factors. The practice problem Linear Probing Table asks for the final table after a sequence of insertions.

In C++

The C++ version uses linear probing with tombstones, in a std::vector of slots with a state byte. It runs 20,000 seeded random inserts, deletes and searches against std::unordered_set twice: once letting tombstones accumulate, and once rebuilding the table (reinserting the live keys into a clean array) whenever live keys plus tombstones fill three quarters of it.

cpp · try it yourself
#include <cstdio>
#include <random>
#include <unordered_set>
#include <vector>

class LinearProbingSet {
    enum State : unsigned char { Empty, Full, Deleted };
    struct Slot { State state = Empty; int key = 0; };
    std::vector<Slot> t_;
    std::size_t live_ = 0, tombs_ = 0;
    bool rebuild_;
    // slot of k, or where it would go (the first tombstone passed, else the empty slot)
    std::pair<std::size_t, bool> find(int k) {
        std::size_t m = t_.size(), j = static_cast<std::size_t>(k) % m, tomb = m;
        for (std::size_t i = 0; i < m; ++i, j = (j + 1) % m) {
            ++probes;
            if (t_[j].state == Empty) return {tomb < m ? tomb : j, false};
            if (t_[j].state == Full && t_[j].key == k) return {j, true};
            if (t_[j].state == Deleted && tomb == m) tomb = j;
        }
        return {tomb, false};                          // tomb == m: no free slot at all
    }
    void rebuild() {
        std::vector<Slot> old(t_.size());
        old.swap(t_);
        live_ = tombs_ = 0;
        for (const Slot& s : old)
            if (s.state == Full) insert(s.key);
        ++rebuilds;
    }
public:
    long probes = 0, rebuilds = 0;
    LinearProbingSet(std::size_t m, bool rebuild) : t_(m), rebuild_(rebuild) {}
    bool insert(int k) {
        auto [j, found] = find(k);
        if (found || j == t_.size()) return false;
        if (t_[j].state == Deleted) --tombs_;
        t_[j] = {Full, k};
        ++live_;
        if (rebuild_ && 4 * (live_ + tombs_) > 3 * t_.size()) rebuild();
        return true;
    }
    bool erase(int k) {
        auto [j, found] = find(k);
        if (found) { t_[j].state = Deleted; --live_; ++tombs_; }
        return found;
    }
    bool contains(int k) { return find(k).second; }
    std::size_t tombstones() const { return tombs_; }
};

int main() {
    for (bool rebuild : {false, true}) {
        LinearProbingSet s(1009, rebuild);
        std::unordered_set<int> ref;
        std::mt19937 rng(9);
        int mismatches = 0;
        for (int step = 0; step < 20000; ++step) {
            int k = static_cast<int>(rng() % 2000), op = static_cast<int>(rng() % 3);
            if (op == 0 && ref.size() < 500) { s.insert(k); ref.insert(k); }
            else if (op == 1) { s.erase(k); ref.erase(k); }
            else mismatches += s.contains(k) != (ref.count(k) == 1);
        }
        std::printf("%-15s size %zu, tombstones %4zu, mismatches %d, rebuilds %3ld, probes per operation %6.2f\n",
                    rebuild ? "with rebuilds:" : "no rebuilds:", ref.size(), s.tombstones(), mismatches,
                    s.rebuilds, s.probes / 20000.0);
    }
}
no rebuilds:    size 499, tombstones  486, mismatches 0, rebuilds   0, probes per operation  11.72
with rebuilds:  size 499, tombstones   67, mismatches 0, rebuilds   4, probes per operation   2.57

Both versions answer every query correctly; the difference is the cost. Without rebuilds the tombstones take over the table, and searches for absent keys must probe until they find a truly empty slot. Real implementations count tombstones and rebuild, as the second version does. For linear probing there is also a way to delete without tombstones: move later keys of the run backwards into the hole, as long as that does not put a key before its home slot.

Test yourself

With linear probing, m=11m = 11 and h1(k)=k mod 11h_1(k) = k \bmod 11, slots 3, 4 and 5 are occupied and all others empty. Where does key 14 go?

  1. slot 3
  2. slot 6
  3. slot 7
  4. slot 0

Why can't deletion in open addressing simply empty the slot?

  1. Emptying is slower than marking
  2. A later search for a key that probed past that slot would stop at the new hole and wrongly report the key missing
  3. The load factor would exceed 1
  4. Because keys are stored in lists

What is primary clustering?

  1. Keys with the same hash value following the same probe sequence
  2. Runs of occupied consecutive slots that grow faster the longer they get, under linear probing
  3. Two keys landing in the same chain
  4. The table filling up at load factor 1

For double hashing with m=12m = 12, which choice of h2(k)h_2(k) is safe for every key?

  1. h2(k)=2h_2(k) = 2
  2. h2(k)=1+(k mod 11)h_2(k) = 1 + (k \bmod 11)
  3. any odd value relatively prime to 12, such as 1, 5, 7 or 11
  4. h2(k)=6h_2(k) = 6