Sub topic 13
Quadratic probing and double hashing
This chapter assumes you have read the chapters on linear probing, tombstones, and load factor. You should know why a probing table stores entries in the slot array, and why deleting an entry needs a marker. You should also be comfortable with the modulo operator and with the idea of two numbers being coprime (sharing no factor except 1).
The problem with linear probing
Linear probing checks slots h, h+1, h+2, and so on. Its weakness is primary clustering. Once a few occupied slots sit next to each other, any key that hashes into that run walks to its end and extends it. Long runs make later insertions and lookups slower, and they attract even more keys.
The fix is to change the step between probes. A probe sequence is the ordered list of slots a key tries. Linear probing uses a fixed step of 1. This chapter covers two ways to make the sequence jump around:
- Quadratic probing grows the step with each attempt.
- Double hashing uses a second hash function to choose a step that differs per key.
Quadratic probing
In quadratic probing, attempt i looks at slot (h + c1*i + c2*i²) % n. The simplest form is (h + i²) % n. The offsets are 0, 1, 4, 9, 16, and so on, so a key that lands inside a cluster quickly jumps out of it.
Two keys with different home slots now follow different paths. Two keys with the same home slot h still follow the same path, because the sequence depends only on h. This weaker problem is called secondary clustering.
Will the sequence find an empty slot?
A probe sequence is only useful if it eventually reaches every slot, or at least enough of them. Quadratic sequences can repeat slots, so the table size matters.
- With a prime
n, the first(n + 1) / 2probes of(h + i²) % nare all distinct. If the table is less than half full, an empty slot is guaranteed to appear among them. - With a power-of-two
n, plaini²is a poor choice, because squares modulo a power of two hit very few residues. The triangular-number variant(h + i*(i+1)/2) % nvisits every slot exactly once innprobes.
The following code prints the sequences for a table of 8 slots and a prime table of 7 slots:
def linear_probes(h, n):
return [(h + i) % n for i in range(n)]
def square_probes(h, n):
return [(h + i * i) % n for i in range(n)]
def triangular_probes(h, n):
return [(h + i * (i + 1) // 2) % n for i in range(n)]
def double_probes(h1, h2, n):
return [(h1 + i * h2) % n for i in range(n)]
print("linear ", linear_probes(3, 8))
print("squares n=8 ", square_probes(3, 8))
print("triangular ", triangular_probes(3, 8))
print("double ", double_probes(3, 5, 8))
print("squares n=7 ", square_probes(3, 7))The output is:
linear [3, 4, 5, 6, 7, 0, 1, 2]
squares n=8 [3, 4, 7, 4, 3, 4, 7, 4]
triangular [3, 4, 6, 1, 5, 2, 0, 7]
double [3, 0, 5, 2, 7, 4, 1, 6]
squares n=7 [3, 4, 0, 5, 5, 0, 4]Plain squares on 8 slots touch only slots 3, 4, and 7. If those three are full, the insertion loops forever even though the table has empty slots. The triangular and double sequences visit all 8 slots.
Double hashing
Double hashing removes secondary clustering. It computes two hash values for each key:
h1(key)gives the home slot.h2(key)gives the step size.
Attempt i looks at slot (h1 + i * h2) % n. Two keys that share a home slot will usually have different steps, so their paths diverge immediately.
The step must be valid. It can never be 0, or the key probes the same slot forever. It must also be coprime with n, or the sequence only reaches a fraction of the slots. There are two standard ways to guarantee this:
| Table size | Step rule | Why it works |
|---|---|---|
| Prime | `1 + h2 % (n - 1)`, which gives 1 to n-1 | Every number from 1 to n-1 is coprime with a prime |
| Power of two | `2 * (h2 % (n // 2)) + 1`, which is always odd | An odd number shares no factor with a power of two |
The following diagram shows a lookup with double hashing:
A working double-hashing table
This table keeps a prime capacity. It uses tombstones for deletion as in the earlier chapter, and a load limit of 0.5. A tombstone counts toward the load, because it lengthens probe sequences just like a live entry.
_EMPTY = object()
_DELETED = object()
def _is_prime(n):
if n < 2:
return False
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
def _next_prime(n):
n += 1
while not _is_prime(n):
n += 1
return n
class DoubleHashTable:
def __init__(self, capacity=7, max_load=0.5):
self._slots = [_EMPTY] * capacity
self._used = 0 # live entries plus tombstones
self._live = 0
self._max_load = max_load
def __len__(self):
return self._live
def _probe(self, key):
n = len(self._slots)
h = hash(key)
start = h % n
step = 1 + (h // n) % (n - 1) # 1 .. n-1, coprime with prime n
for i in range(n):
yield (start + i * step) % n
def get(self, key, default=None):
for i in self._probe(key):
slot = self._slots[i]
if slot is _EMPTY:
return default
if slot is not _DELETED and slot[0] == key:
return slot[1]
return default
def put(self, key, value):
first_free = None
for i in self._probe(key):
slot = self._slots[i]
if slot is _EMPTY:
if first_free is None:
first_free = i
break
if slot is _DELETED:
if first_free is None:
first_free = i
elif slot[0] == key:
self._slots[i] = (key, value)
return
if self._slots[first_free] is _EMPTY:
if (self._used + 1) / len(self._slots) > self._max_load:
self._resize(_next_prime(len(self._slots) * 2))
self.put(key, value)
return
self._used += 1
self._slots[first_free] = (key, value)
self._live += 1
def remove(self, key):
for i in self._probe(key):
slot = self._slots[i]
if slot is _EMPTY:
return False
if slot is not _DELETED and slot[0] == key:
self._slots[i] = _DELETED
self._live -= 1
return True
return False
def _resize(self, new_capacity):
old = self._slots
self._slots = [_EMPTY] * new_capacity
self._used = 0
self._live = 0
for slot in old:
if slot is not _EMPTY and slot is not _DELETED:
self.put(slot[0], slot[1])
t = DoubleHashTable()
for i in range(20):
t.put(i, i * i)
print(t.remove(5), t.get(5), t.get(6), len(t))This prints True None 36 19.
Two details are easy to get wrong. First, put reuses the first tombstone it passed, but only after confirming the key is not further along the sequence. Otherwise you could store a duplicate. Second, reusing a tombstone does not change _used, since that slot was already counted. Only filling a truly empty slot does.
Comparing the three strategies empirically
Theory says the average number of probes for an insertion at load factor α is about (1 + 1/(1-α)²) / 2 for linear probing and about 1/(1-α) for double hashing. At α = 0.8 that is roughly 13 versus 5. This experiment measures it on a table of 1024 slots. The triangular and double-hashing versions both visit every slot, so the loop always ends.
import random
def linear(h1, h2, i, n):
return (h1 + i) % n
def triangular(h1, h2, i, n):
return (h1 + i * (i + 1) // 2) % n
def double(h1, h2, i, n):
return (h1 + i * h2) % n
def average_probes(step_fn, n=1024, load=0.8, seed=1):
rng = random.Random(seed)
keys = rng.sample(range(10**9), int(n * load))
taken = [False] * n
total = 0
for key in keys:
h1 = key % n
h2 = 2 * ((key // n) % (n // 2)) + 1 # always odd
i = 0
while True:
idx = step_fn(h1, h2, i, n)
total += 1
if not taken[idx]:
taken[idx] = True
break
i += 1
return total / len(keys)
for name, fn in [("linear", linear), ("triangular", triangular), ("double", double)]:
print(name, round(average_probes(fn), 2))The exact numbers depend on the seed. Linear probing should come out clearly the worst, and the other two close to each other and far lower.
Trade-offs and common errors
Fewer probes does not always mean faster. Linear probing reads adjacent slots, which sit in the same cache line, so each extra probe is cheap. Double hashing jumps across memory, so each probe may be a cache miss. For small entries, linear probing with a good hash and a low load factor often wins in practice. Double hashing also costs a second hash computation per operation.
| Property | Linear | Quadratic | Double hashing |
|---|---|---|---|
| Primary clustering | Yes | No | No |
| Secondary clustering | Yes | Yes | No |
| Cache behavior | Best | Moderate | Worst |
| Extra requirement | None | Size and load rules | Step coprime with size |
Common errors:
- A step of 0. Computing the step as
h2 % ncan give 0. Add 1 or force the value to be odd. - Ignoring tombstones in the load factor. A table full of tombstones makes every unsuccessful lookup walk the full probe sequence. Count them, and rebuild the table when they pile up.
- Wrong size after resize. Doubling a prime size gives an even number. Move to the next prime instead.
- Stopping at a tombstone. A lookup must continue past a tombstone, and stop only at an empty slot.
Exercise
A quadratic-probing table uses the formula (h + i*i) % n with n = 16. The key hashes to home slot 2, and slots 2, 3, 6, and 11 are occupied. Can the insertion always succeed, and what should the designer change?
Show answer
No. For n = 16, ii mod 16 takes only the values 0, 1, 4, and 9, so the key can only reach slots 2, 3, 6, and 11. All four are occupied, so the insertion loops forever even if the other 12 slots are empty. The designer should use a prime table size and keep the load factor below 0.5, or switch to the triangular-number formula (h + i(i+1)/2) % n, which visits every slot when n is a power of two.
Exercise
In a double-hashing table of size 12, a key has home slot 5 and step 4. Which slots does it visit, and why is this a bad design?
Show answer
It visits 5, 9, 1, 5, and then repeats, so only slots 1, 5, and 9. The step 4 and the size 12 share the factor 4, so the sequence covers only 12/4 = 3 slots. The fix is a prime size, or a power-of-two size with an odd step.