Simple Algorithm
Algorithms & Data Structures · Optimized · 22 min

Hash Tables

Hash functions, collisions, chaining and open addressing.

Python's dict, Java's HashMap and C++'s unordered_map all promise constant time on average, yet no two are built alike: one probes for free slots, one keeps chains that turn into trees, one keeps plain chains. This lesson derives what each design costs at a given load factor, proves the bound for chaining, explains tombstones and resizing, and shows how to spot a hash-table problem in a statement.

What you’ll learn

  • Design hash functions for integers (division, multiplicative, multiply-shift) and strings (polynomial), and choose the table size mm.
  • Prove that a chained table compares α\alpha keys per unsuccessful search and 1+α/2−α/(2n)1 + \alpha/2 - \alpha/(2n) per successful search in expectation, under simple uniform hashing.
  • Compare linear probing, quadratic probing and double hashing; prove the 1/(1−α)1/(1-\alpha) bound for uniform hashing and use Knuth's formulas for linear probing.
  • Implement deletion with tombstones and resizing with O(1)O(1) amortized insertions.
  • Recognize hash-table problems (counting, deduplication, two sum, grouping, memoization) and the look-alikes that need ordered structures instead.

Hash functions: from keys to slots

A hash function maps keys from a huge universe UU to the slots {0,1,…,m−1}\{0, 1, \dots, m-1\} of a hash table. It must be deterministic (the same key always gets the same slot), fast, and it should spread the keys evenly. The analyses below assume simple uniform hashing: every key lands in a uniformly random slot, independently of the other keys.

No fixed function satisfies that assumption for every possible input; the Optimized lesson Universal Hashing & Sketches shows how randomizing the function recovers it as a guarantee. On ordinary data, the standard functions behave close enough to it:

Methodh(k)h(k)Choice of mm
Divisionk mod mk \bmod mA prime not close to a power of 2. With m=2pm = 2^p it keeps only the lowest pp bits of kk.
Multiplicative (Knuth)⌊m⋅frac⁡(kA)⌋\lfloor m \cdot \operatorname{frac}(kA) \rfloor, with A=(5−1)/2≈0.618A = (\sqrt5 - 1)/2 \approx 0.618Any mm, powers of 2 included.
Multiply-shift((s⋅k) mod 2w)≫(w−p)\big((s \cdot k) \bmod 2^w\big) \gg (w - p), with s=⌊A⋅2w⌋s = \lfloor A \cdot 2^w \rfloorm=2pm = 2^p: one multiplication and one shift on a ww-bit word.
Polynomial (strings)(c0bL−1+c1bL−2+⋯+cL−1) mod m\big(c_0 b^{L-1} + c_1 b^{L-2} + \dots + c_{L-1}\big) \bmod m for characters cic_iA prime mm; Java's String.hashCode uses b=31b = 31 and arithmetic modulo 2322^{32}.
Multiply-shift is the multiplicative method in integer arithmetic. For w=64w = 64, s=⌊A⋅264⌋s = \lfloor A \cdot 2^{64} \rfloor is 0x9E3779B97F4A7C15, a constant you will meet again in the Optimal lesson Hash Flooding & Anti-Hash Tests.
python
import math

A = (math.sqrt(5) - 1) / 2                 # Knuth's suggestion, about 0.618

def h_division(k, m):                      # m prime, not close to a power of 2
    return k % m

def h_multiplicative(k, m):                # any m, powers of 2 included
    return math.floor(m * ((k * A) % 1))

def h_multiply_shift(k, p, w=64):          # the same idea in integer arithmetic, m = 2**p
    s = 0x9E3779B97F4A7C15                 # floor(A * 2**64)
    return ((s * k) % (1 << w)) >> (w - p)

def h_string(s, m, b=31):                  # polynomial hash, evaluated by Horner's rule
    h = 0
    for ch in s:
        h = (h * b + ord(ch)) % m
    return h

The consecutive keys 1000, 1001, 1002 and 1003 go to slots 0, 10, 4 and 14 of a 16-slot table under both h_multiplicative and h_multiply_shift: the golden ratio scatters neighbors. (The floating-point version loses precision for very large keys; the integer one is exact.)

Chaining, analyzed

In chaining, slot jj holds a list of the keys with h(k)=jh(k) = j. An insertion scans the chain to rule out a duplicate, then appends; a search scans the chain; a deletion unlinks the key, in O(1)O(1) once it has been found if the lists are doubly linked. In the worst case every key shares one chain and each operation takes Θ(n)\Theta(n). The expected case depends only on the load factor α=n/m\alpha = n/m, which for chaining may exceed 1.

DerivationProof
  1. E[keys compared]=∑i=1nPr⁡[h(xi)=h(k)]=nm=α\E[\text{keys compared}] = \sum_{i=1}^{n} \Pr\big[h(x_i) = h(k)\big] = \frac{n}{m} = \alpha

    Unsuccessful search. The searched key's slot is uniform and independent of the stored keys, and each stored key lands in that slot with probability 1/m1/m. By linearity of expectation, the chain it scans has expected length

  2. E[cost]=1n∑i=1n(1+∑j<iE[Xij])=1+1nm∑i=1n(i−1)\E[\text{cost}] = \frac1n \sum_{i=1}^{n} \Big(1 + \sum_{j < i} \E[X_{ij}]\Big) = 1 + \frac{1}{nm} \sum_{i=1}^{n} (i - 1)

    Successful search. Let x1,…,xnx_1, \dots, x_n be the keys in insertion order. Since keys are appended, a search for xix_i compares xix_i itself plus every earlier key in its chain. With indicators Xij=[h(xj)=h(xi)]X_{ij} = [h(x_j) = h(x_i)] and E[Xij]=1/m\E[X_{ij}] = 1/m for j≠ij \ne i:

  3. 1+1nm⋅n(n−1)2=1+n−12m=1+α2−α2n1 + \frac{1}{nm} \cdot \frac{n(n-1)}{2} = 1 + \frac{n-1}{2m} = 1 + \frac{\alpha}{2} - \frac{\alpha}{2n}

    Sum the arithmetic series:

  4. Θ(1+α)=Θ(1)whenevern=O(m)\Theta(1 + \alpha) = \Theta(1) \quad \text{whenever} \quad n = O(m)

    Inserting at the head of the chain instead, as CLRS does, makes a search for xix_i scan the keys inserted after it; by symmetry the count is the same. If mm grows with nn so that α=O(1)\alpha = O(1), every operation takes O(1)O(1) expected time:

Check your understanding

A chained table has m=1,000m = 1{,}000 slots and holds n=3,000n = 3{,}000 keys under simple uniform hashing. In expectation, how many keys does an unsuccessful search compare, and how many does a successful search compare?

  1. 3 and 3
  2. 3 and about 2.5
  3. 1.5 and about 2.5
  4. 3,000 and 1,500
Show the answer

B. 3 and about 2.5

An unsuccessful search scans a whole chain of expected length α=3\alpha = 3. A successful search scans, on average, the key itself plus half of the others in its chain: 1+3/2−3/6000≈2.49951 + 3/2 - 3/6000 \approx 2.4995.

Open addressing: probe sequences

Open addressing stores the keys in the array itself, one per slot, so α≤1\alpha \le 1. Each key kk has a probe sequence h(k,0),h(k,1),h(k,2),…h(k, 0), h(k, 1), h(k, 2), \dots of slots. An insertion takes the first free slot on it; a search follows it until it finds the key or an empty slot. Three classic sequences, for a home slot h1(k)h_1(k):

  • Linear probing: h1(k)+i(modm)h_1(k) + i \pmod m. Cache-friendly, but runs of occupied slots merge and grow: primary clustering.
  • Quadratic probing: h1(k)+i2(modm)h_1(k) + i^2 \pmod m. Keys with different home slots spread apart, but keys with the same home slot share a sequence (secondary clustering). With a prime mm it visits only (m+1)/2(m+1)/2 different slots, which is enough to always find a free one while α≤1/2\alpha \le 1/2.
  • Double hashing: h1(k)+i⋅h2(k)(modm)h_1(k) + i \cdot h_2(k) \pmod m, with h2(k)h_2(k) never 0 and coprime to mm, for example h2(k)=1+(k mod (m−1))h_2(k) = 1 + (k \bmod (m-1)) with a prime mm. The step depends on the key, so a prime mm gives m(m−1)m(m-1) different sequences.
DerivationProof
  1. Pr⁡[X≥i]=nm⋅n−1m−1⋯n−i+2m−i+2 ≤ α i−1\Pr[X \ge i] = \frac{n}{m} \cdot \frac{n-1}{m-1} \cdots \frac{n-i+2}{m-i+2} \ \le\ \alpha^{\,i-1}

    Unsuccessful. Let XX be the number of probes. The first i−1i - 1 probes all hit occupied slots only if each successive probe, at a slot not yet seen, finds one of the remaining keys:

  2. E[X] ≤ ∑i≥1α i−1=11−α\E[X] \ \le\ \sum_{i \ge 1} \alpha^{\,i-1} = \frac{1}{1-\alpha}

    A nonnegative integer variable has E[X]=∑i≥1Pr⁡[X≥i]\E[X] = \sum_{i \ge 1} \Pr[X \ge i], so a geometric series bounds it:

  3. 1n∑i=0n−1mm−i=mn∑j=m−n+1m1j ≤ 1α∫m−nmdxx=1αln⁡11−α\frac1n \sum_{i=0}^{n-1} \frac{m}{m-i} = \frac{m}{n} \sum_{j=m-n+1}^{m} \frac1j \ \le\ \frac1\alpha \int_{m-n}^{m} \frac{dx}{x} = \frac1\alpha \ln\frac{1}{1-\alpha}

    Successful. Without deletions, a search for the key inserted (i+1)(i+1)-st retraces that key's insertion, which was an unsuccessful search when the table held ii keys. Averaging over the nn keys:

Linear probing violates uniform hashing badly: a run of occupied slots attracts every key that hashes into it. Knuth's analysis (1963) gives its exact expected costs with a random hash function, about 12(1+11−α)\tfrac12\big(1 + \tfrac{1}{1-\alpha}\big) probes for a successful search and 12(1+1(1−α)2)\tfrac12\big(1 + \tfrac{1}{(1-\alpha)^2}\big) for an unsuccessful one. The square is the price of clustering:

α\alphaUniform hashing: absent / presentLinear probing: absent / presentChaining: keys compared, absent / present
0.52 / 1.392.5 / 1.50.5 / 1.25
0.754 / 1.858.5 / 2.50.75 / 1.375
0.910 / 2.5650.5 / 5.50.9 / 1.45
Expected probes. Double hashing behaves almost like uniform hashing. Open-addressing counts include the probe that ends the search, while chaining counts keys compared, so for a fair comparison add about one to chaining's numbers. Linear probing still wins in practice at moderate α\alpha, because its probes read consecutive memory, often within one cache line.

Deletion, resizing and the table size

Deleting from a chained table just unlinks the key. In open addressing you may not simply empty the slot: a search for any key whose probe sequence passed through that slot would now stop there and report a false "absent". Instead the slot gets a tombstone:

  • searches step over tombstones as if they were occupied;
  • an insertion first confirms that the key is absent (which means probing to an empty slot), then stores it in the first tombstone it passed, if any;
  • tombstones lengthen searches exactly as keys do, so they count toward the load that triggers a rebuild, and a rebuild drops them all.

For linear probing there is an alternative without tombstones, Knuth's Algorithm R: after emptying a slot, walk forward through the rest of the cluster and move back every key whose probe path crosses the hole.

Resizing. When an insertion would push the load factor past a threshold αmax⁡\alpha_{\max} (with chaining often 1, with open addressing 0.5 to 0.875), the table allocates about twice as many slots and rehashes: it reinserts every live key, because hh depends on mm and every key's slot changes. One resize costs Θ(n)\Theta(n); the doubling makes it cheap on average.

DerivationDoubling gives O(1) amortized insertions
  1. n+n2+n4+⋯ < 2nn + \frac n2 + \frac n4 + \cdots \ <\ 2n

    Start with m0m_0 slots and double whenever an insertion would exceed αmax⁡\alpha_{\max}. The resizes happen at sizes that double each time, and the last one before the nn-th insertion moves at most nn keys. So the total number of keys ever moved is

  2. E[T(n insertions)]=O(n)+O(2n)=O(n)\E\big[T(n \text{ insertions})\big] = O(n) + O(2n) = O(n)

    Each insertion also costs O(1)O(1) expected probes for itself (the load factor stays below αmax⁡<1\alpha_{\max} < 1), so nn insertions cost O(n)O(n) expected time: O(1)O(1) expected, amortized, per insertion.

  3. ∑j=1n/cjc ≈ n22c=Θ(n2)for constant c\sum_{j=1}^{n/c} jc \ \approx\ \frac{n^2}{2c} = \Theta(n^2) \quad \text{for constant } c

    Growing by a fixed number cc of slots instead resizes after every Θ(c)\Theta(c) insertions, and the jj-th resize moves about jcjc keys:

  4. grow at α>αmax⁡,shrink at α<14αmax⁡\text{grow at } \alpha > \alpha_{\max}, \qquad \text{shrink at } \alpha < \tfrac14\alpha_{\max}

    Shrinking follows the dynamic-array rule: halve when α\alpha falls below αmax⁡/4\alpha_{\max}/4, not αmax⁡/2\alpha_{\max}/2, so that after any resize Θ(m)\Theta(m) operations must happen before the next one. Halving at αmax⁡/2\alpha_{\max}/2 would let alternating insertions and deletions at the boundary resize every time.

Prime or power of two? A prime mm makes the division method robust to patterns in the keys and makes every step h2(k)h_2(k) of double hashing coprime to mm. A power of two replaces the division by a bit mask, which is much faster, but then the hash function itself must mix the high bits of the key into the low ones: Java's HashMap folds the hash with h⊕(h≫16)h \oplus (h \gg 16), multiply-shift takes the top bits of a product, and CPython's probe sequence shifts in more of the hash at every step.

python
EMPTY, TOMB = object(), object()             # TOMB marks a deleted slot (a tombstone)

class LinearProbingSet:
    def __init__(self, m=8):
        self.slots, self.used = [EMPTY] * m, 0   # used = live keys + tombstones

    def _find(self, key):                    # -> (slot holding key or None, slot to insert into)
        m = len(self.slots)
        i, free = hash(key) % m, None
        while self.slots[i] is not EMPTY:    # an EMPTY slot exists, since used <= 3m/4
            if self.slots[i] is TOMB:
                free = i if free is None else free
            elif self.slots[i] == key:
                return i, None
            i = (i + 1) % m
        return None, (i if free is None else free)

    def __contains__(self, key):
        return self._find(key)[0] is not None

    def add(self, key):
        if self.used + 1 > 0.75 * len(self.slots):     # rebuild without tombstones
            live = [k for k in self.slots if k is not EMPTY and k is not TOMB]
            m = len(self.slots) * (2 if 2 * len(live) >= len(self.slots) else 1)
            self.slots, self.used = [EMPTY] * m, 0
            for k in live:
                self.add(k)
        found, j = self._find(key)
        if found is None:
            self.used += self.slots[j] is EMPTY        # reusing a tombstone uses no new slot
            self.slots[j] = key

    def remove(self, key):
        found, _ = self._find(key)
        if found is not None:
            self.slots[found] = TOMB         # not EMPTY: that would cut other keys' probe paths

A set with linear probing, tombstones and resizing. The rebuild doubles the table only when live keys fill at least half of it; when the used slots are mostly tombstones it rebuilds at the same size, so a long run of insertions and deletions cannot inflate the table. Tested against Python's own set on random operation sequences.

What your language actually does

LibraryCollisionsSize and growthWorth knowing
CPython dictOpen addressing. From slot jj the next probe is 5j+1+perturb5j + 1 + \text{perturb} modulo the size; perturb starts as the full hash and is shifted right by 5 bits each step, so every bit of the hash eventually matters.A power of 2, at least 8 slots; grows when 2/3 full. Deleted slots are marked as dummies, CPython's tombstones.The entries live in a dense array in insertion order (since 3.6; guaranteed by the language since 3.7), indexed by the hash table.
C++ std::unordered_mapSeparate chaining: bucket iterators, and references that stay valid across rehashing, effectively require it.max_load_factor() defaults to 1.0. GCC's libstdc++ takes prime bucket counts from a fixed table.std::hash of an integer is the integer itself, in both libstdc++ and LLVM's libc++.
Java HashMapChaining; the hash is spread as h⊕(h≫16)h \oplus (h \gg 16) before masking.A power of 2, 16 by default; grows at load factor 0.75.Adding a key to a bin that already holds 8 entries turns the bin into a red-black tree, once the table has at least 64 bins (a smaller table grows instead). Colliding keys then cost O(log⁡n)O(\log n) if their hashes differ or they are Comparable.
Abseil flat_hash_map, Rust's HashMap, Go's maps (since Go 1.24)"Swiss tables": open addressing over groups of slots, one control byte per slot holding 7 bits of the hash; a whole group is compared at once with SIMD instructions.Abseil grows at load 7/8.Rust's default hasher is SipHash-1-3 with a random key per map.
As of 2025. The Optimal lesson Open Addressing in Depth looks inside Swiss tables.

Two more facts about Python matter in practice. Strings and bytes are hashed with a keyed function (SipHash-1-3 since Python 3.11) whose secret key is drawn at random when the process starts, so hash("abc") changes from run to run unless PYTHONHASHSEED is set. Integers are not randomized: on 64-bit builds a non-negative int hashes to its value modulo the prime 261−12^{61} - 1, so small integers hash to themselves.

cpp
#include <unordered_map>
#include <vector>

long long count_equal_pairs(const std::vector<long long>& a) {
    std::unordered_map<long long, long long> cnt;
    cnt.reserve(a.size());                    // allocate the buckets once: no rehash in the loop
    long long pairs = 0;
    for (long long x : a) pairs += cnt[x]++;  // operator[] inserts x with count 0 if it is new
    return pairs;
}
// To test membership without inserting, use cnt.count(x) or cnt.find(x) != cnt.end(), never cnt[x].

The contest idiom for counting: on {3,1,3,3,2,1}\{3, 1, 3, 3, 2, 1\} it returns 4 (three pairs of 3s and one pair of 1s). reserve avoids the intermediate rehashes, and the comment marks the most common unordered_map bug.

Recognizing it

A hash table is the answer whenever the question is about exact matches: "have I seen this?", "how many times?", "where was it?", "which group does it belong to?". Statement signals: count, frequency, distinct, duplicate, first repeated, pair or complement, group by, anagram, cache, visited. Constraints such as n≤105n \le 10^5 to 10610^6 with values up to 10910^9 rule out both an O(n2)O(n^2) comparison of all pairs and a direct-address array indexed by value; O(n)O(n) expected time with a hash map fits easily.

ProblemKey ideaCost
Two sum on unsorted data: two positions whose values add up to TTScan once with a map from value to position; before storing xx, look up T−xT - xO(n)O(n) expected
Group anagramsCanonical key: the word's letters in sorted order, or its tuple of 26 letter countsO(∑Llog⁡L)O(\sum L \log L), or O(∑L)O(\sum L) with counts
Longest run of consecutive integers in an unsorted arrayHash set of the values; walk upward only from an xx whose x−1x - 1 is absent, so each value is visited O(1)O(1) timesO(n)O(n) expected
Number of subarrays with sum kkPrefix sums PP; count how many earlier prefixes equal P−kP - k with a map of countsO(n)O(n) expected
LRU cache with O(1)O(1) get and putA map from key to a node of a doubly linked list kept in order of recent useO(1)O(1) expected per operation
The subarray-sum trick is developed in the Optimal lesson Subarray Sums: Hash Maps & Kadane’s Algorithm of the prefix-sums topic.
python
from collections import defaultdict

def two_sum(a, target):                      # indices i < j with a[i] + a[j] == target
    seen = {}                                # value -> index where it was first seen
    for j, x in enumerate(a):
        if target - x in seen:
            return seen[target - x], j
        seen.setdefault(x, j)
    return None

def group_anagrams(words):
    groups = defaultdict(list)
    for w in words:
        groups[''.join(sorted(w))].append(w) # canonical key: the letters in sorted order
    return list(groups.values())

def longest_consecutive(a):                  # longest run x, x+1, x+2, ... present in a
    s, best = set(a), 0
    for x in s:
        if x - 1 not in s:                   # x starts a run: walk it once
            y = x
            while y + 1 in s:
                y += 1
            best = max(best, y - x + 1)
    return best

two_sum([8, 3, 5, 9, 2], 11) returns (0, 1); longest_consecutive([100, 4, 200, 1, 3, 2]) returns 4. Looking up T−xT - x before storing xx is what stops a value from pairing with itself.

Common bugs:

  • Mutable keys. Python refuses to hash a list (use a tuple); in Java, mutating an object after using it as a key strands it in the wrong bin. Overriding equals without hashCode breaks lookups.
  • cnt[x] to test membership in C++, which inserts xx. Use count or find.
  • Unhashable composite keys in C++: std::unordered_map<std::pair<int, int>, int> has no default hash. Encode the pair as one 64-bit integer, or write a hash.
  • Floating-point keys: 0.1 + 0.2 != 0.3, and NaN is not equal to itself, so lookups miss. Round or scale to integers first.
  • Trusting the average under attack: a hash function that is fixed and public turns O(n)O(n) expected into Θ(n2)\Theta(n^2) on hacking tests. See the Optimal lesson Hash Flooding & Anti-Hash Tests.
Check your understanding

A program must process 2×1052 \times 10^5 operations on a set of integers up to 10910^9: insert xx, delete xx, and "report the smallest stored value greater than xx". Which structure fits?

  1. A hash set, scanning all stored values for the third query
  2. A balanced binary search tree, such as C++'s std::set with upper_bound
  3. An array indexed by value
  4. A hash map from each value to its successor, updated on every insertion and deletion
Show the answer

B. A balanced binary search tree, such as C++'s std::set with upper_bound

The third query is about order, which hashing destroys. A balanced search tree keeps the keys sorted and answers insert, delete and successor in O(log⁡n)O(\log n) each: about 2×105⋅182 \times 10^5 \cdot 18 steps in total.

Key takeaways

  • Good hash functions spread keys like random numbers: the division method with a prime mm, the multiplicative method or multiply-shift for m=2pm = 2^p, and polynomial hashing for strings.
  • Under simple uniform hashing, chaining compares α\alpha keys per unsuccessful search and 1+α/2−α/(2n)1 + \alpha/2 - \alpha/(2n) per successful one in expectation, so O(1)O(1) when α=O(1)\alpha = O(1); the worst case is Θ(n)\Theta(n).
  • Open addressing under uniform hashing needs at most 1/(1−α)1/(1-\alpha) expected probes per unsuccessful search; linear probing pays about 12(1+1/(1−α)2)\tfrac12(1 + 1/(1-\alpha)^2) because of primary clustering, so open-addressing tables keep α\alpha well below 1.
  • Deletion in open addressing needs tombstones (or Knuth's backward shift for linear probing), and doubling on resize keeps insertions O(1)O(1) amortized, where growing by a constant costs Θ(n2)\Theta(n^2) in total.
  • Reach for a hash table on exact-match questions (counting, deduplication, two sum, grouping, memoization) and for a sorted structure on order questions (successor, ranges); every library promises only expected O(1)O(1).

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Under uniform hashing, an open-addressing table is 80% full. What does the theorem guarantee about the expected number of probes in an unsuccessful search?

  1. At most 1.25
  2. At most about 2.01
  3. At most 5
  4. At most 13
Show the answer

C. At most 5

1/(1−α)=1/0.2=51/(1-\alpha) = 1/0.2 = 5: each probe finds an occupied slot with probability at most 0.80.8, so the number of probes is dominated by a geometric variable with mean 5.

Question 2

Keys are memory addresses, all multiples of 16, stored in a table of m=1024m = 1024 slots with h(k)=k mod mh(k) = k \bmod m. What goes wrong?

  1. Nothing: the remainder spreads any keys evenly
  2. Only 64 of the 1,024 slots can ever be used, so chains are about 16 times longer than they should be
  3. Large addresses overflow the remainder
  4. Every key lands in slot 0
Show the answer

B. Only 64 of the 1,024 slots can ever be used, so chains are about 16 times longer than they should be

k mod 1024k \bmod 1024 keeps the lowest 10 bits of kk, and the lowest 4 are always 0, so only the 26=642^6 = 64 slots that are multiples of 16 can be hit. A prime mm, or a multiplicative hash that mixes high bits into the index, uses all 1,024.

Question 3

Which of these tasks is the poorest fit for a hash table?

  1. Count how often each word occurs in a book
  2. Remove duplicate records from a list
  3. List all stored keys between aa and bb in increasing order
  4. Cache the results of an expensive function of two integers
Show the answer

C. List all stored keys between aa and bb in increasing order

A hash function scatters keys on purpose, so keys near each other in value land far apart, and a range query must examine every key. A balanced search tree or a sorted array answers it in O(log⁡n+k)O(\log n + k) for kk reported keys.

Question 4

A linear-probing table has 1,000 slots, 400 live keys and 450 tombstones, so its load factor counting live keys only is 0.4. Why should it be rebuilt?

  1. It should not: at α=0.4\alpha = 0.4 linear probing is fast
  2. Tombstones make some successful searches return the wrong key
  3. Searches stop only at empty slots, so they behave as if 850 slots were full: Knuth's estimate for an unsuccessful search rises from about 1.9 probes to about 23
  4. New keys can no longer be inserted into tombstones
Show the answer

C. Searches stop only at empty slots, so they behave as if 850 slots were full: Knuth's estimate for an unsuccessful search rises from about 1.9 probes to about 23

For probing, a tombstone is as good as a key: 12(1+1/0.62)≈1.9\tfrac12\big(1 + 1/0.6^2\big) \approx 1.9 probes at α=0.4\alpha = 0.4 becomes 12(1+1/0.152)≈22.7\tfrac12\big(1 + 1/0.15^2\big) \approx 22.7 when 85% of the slots are in use. A rebuild reinserts the 400 live keys and drops all 450 tombstones.

Question 5

A table grows by a fixed 1,000 slots each time it becomes full, instead of doubling. About how many keys do all the rehashes move during 10610^6 insertions?

  1. Fewer than 2×1062 \times 10^6
  2. About 2×1072 \times 10^7
  3. About 5×1085 \times 10^8
  4. About 101210^{12}
Show the answer

C. About 5×1085 \times 10^8

Resizes happen at 1,000, 2,000, 3,000, … keys, and the jj-th moves 1000j1000j keys: 1000⋅(1+2+⋯+999)=499,500,0001000 \cdot (1 + 2 + \dots + 999) = 499{,}500{,}000. That is Θ(n2/c)\Theta(n^2/c) for growth by cc slots, against fewer than 2n=2×1062n = 2 \times 10^6 for doubling.

Go deeper

Further reading

  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 11.
  • D. E. Knuth, The Art of Computer Programming, vol. 3, Sorting and Searching, 2nd ed. (Addison-Wesley, 1998), section 6.4.
  • R. Sedgewick & K. Wayne, Algorithms, 4th ed. (Addison-Wesley, 2011), section 3.4.