Skip to content
Visual explainer 4h to learn 4 steps

Hash tables: chaining, open addressing & resizing

Implement a hash map with collision handling and resizing.

By Invicly Tech, , in Data Structures & Algorithms. About 13 minutes to read.

Topic 16 of 54

In short

A hash table stores key-value pairs in an array of buckets chosen by the key's hash. Collisions are handled either by chaining, where each bucket holds a small list, or by open addressing, where you probe for the next free slot. Keeping the load factor low through resizing keeps operations O(1) on average.

Explained simply

A hash table is the structure behind Python's dict and set. It is an array of slots called buckets. To store a key, you hash it, pick a bucket, and put the key and its value there. To find it again, you hash the key and jump straight to that bucket. No searching through the whole array.

The hard part is collisions: two keys that want the same bucket. There are two main fixes. Chaining keeps a small list in each bucket, so colliding keys just share the list. Open addressing keeps one entry per slot, and when a slot is taken you try the next one, and the next, until you find room.

The table must not get too full. The load factor is the number of stored keys divided by the number of buckets. When it gets high, collisions pile up and everything slows down. So the table grows, usually to double its size, and moves every key to its new bucket. That move is called rehashing.

Rehashing is slow when it happens, but it happens rarely. Spread over all the inserts, each insert still costs O(1) on average. That is why a dict feels instant even with millions of keys.

Press Play on a diagram to walk through it one step at a time.

CompareCollision strategies
Separate chaining
  • Bucket holds a list of entries
  • Simple deletes
  • Extra pointers per entry
  • Degrades gracefully when full
Open addressing
  • All entries in one array
  • Probe linear, quadratic or double hash
  • Deletes need tombstones
  • Cache friendly; used by Python dict
LayersCPython dict memory layout (3.6 and later)
  1. 1
    Index table

    Small ints per slot: entry number, EMPTY or DUMMY.

  2. 2
    Entries array

    (hash, key, value) rows in insertion order.

  3. 3
    Key objects

    str caches its hash, so it is computed once.

  4. 4
    Value objects

    Any Python object, referenced by pointer.

CompareCost per operation
Average case
  • Insert O(1) amortised
  • Lookup O(1)
  • Delete O(1)
  • Needs good hash and bounded load
Worst case
  • Insert O(n)
  • Lookup O(n)
  • Delete O(n)
  • All keys in one bucket or cluster

In depth

Separate chaining in practice

Each bucket holds a list (or linked list) of key-value pairs. Insert hashes the key, scans that bucket for the key, and either updates the value or appends a new pair. Lookup and delete scan the same bucket.

With a uniform hash and load factor a = n / m, a bucket holds a keys on average. An unsuccessful search checks about 1 + a entries, and a successful one about 1 + a/2. Keep a bounded, for example below 1, and every operation is O(1) on average.

Chaining is forgiving: it still works above a load factor of 1, and delete is simply removing an item from a list. The costs are extra memory for list objects or pointers, and poor cache use because entries are scattered. Java's HashMap uses chaining with a default load factor of 0.75, and turns a bucket into a small red-black tree once it grows past 8 entries (when the table has at least 64 buckets), so a bad bucket costs O(log n), not O(n).

  • Average O(1 + a) per operation
  • Delete is easy: remove from the bucket list
  • Java HashMap: chaining, 0.75 load factor, trees for long chains

Open addressing and linear probing

All entries live directly in the array. To insert, start at index h % m. If that slot is taken by another key, try the next slot (h + 1) % m, then (h + 2) % m, until you find an empty one. Lookup follows the same path and stops when it finds the key or reaches an empty slot.

Linear probing is very cache friendly, because the probes touch neighbouring memory. Its weakness is primary clustering: occupied slots form long runs, and any key landing inside a run must walk to its end, making the run longer still. Knuth's analysis gives about (1 + 1/(1 - a)) / 2 probes for a hit and (1 + 1/(1 - a)^2) / 2 for a miss. At a = 0.5 that is 1.5 and 2.5 probes. At a = 0.9 it is 5.5 and 50.5. So open-addressing tables stay well below full.

Quadratic probing and double hashing jump further to break up clusters.

FlowLinear probing insert of key K with h % 8 = 3
  1. 1
    Slot 3

    Taken by another key: move on.

  2. 2
    Slot 4

    Taken: move on.

  3. 3
    Slot 5

    Tombstone: remember it, keep checking for K.

  4. 4
    Slot 6

    Empty: K is not in the table.

  5. 5
    Store

    Put K in slot 5, the first reusable slot.

Deleting with tombstones

In open addressing you cannot just empty a slot on delete. Suppose keys A and B both hash to slot 3, so B was pushed to slot 4. If you delete A by clearing slot 3, a later lookup for B stops at the empty slot 3 and wrongly reports that B is missing.

The fix is a tombstone: a special marker meaning "deleted, but keep probing". Lookups skip over tombstones. Inserts may reuse a tombstone slot, but only after confirming the key is not further along the chain, otherwise you create a duplicate.

Tombstones still count as used slots for probing, so a table with many deletes gets slow even with few live keys. Implementations track live keys plus tombstones and rebuild the table when the total gets too high. CPython's dict does exactly this: deleted entries become dummy markers that are cleared on the next resize.

  • Lookup: skip tombstones, stop at empty
  • Insert: reuse the first tombstone after checking the key is absent
  • Rebuild when live + tombstones passes the threshold

Load factor, resizing and amortised cost

When the load factor passes a threshold, allocate a bigger array (usually double) and reinsert every key, because each key's index depends on the capacity. This rehash costs O(n).

Why is insert still O(1)? With doubling, a table that ends with n keys has rehashed at sizes about n/2, n/4, n/8 and so on. Those add up to less than n moves in total, so the cost per insert is a constant on average. This is amortised O(1): any one insert may be slow, but a long run of inserts is fast overall.

Thresholds differ by design. Java HashMap resizes at 0.75. CPython's dict resizes when it is 2/3 full, starts with 8 slots, and keeps power-of-two sizes. Linear probing tables often stop at 0.5 to 0.7. Some tables also shrink after many deletes to save memory, which needs a lower threshold (like 0.25) to avoid resizing back and forth.

  • Rehash cost: O(n), amortised O(1) per insert
  • Grow by a factor (2x), not by a fixed amount
  • Shrink threshold must be well below the grow threshold

Average versus worst case, and what CPython does

With a good hash and bounded load factor, insert, lookup and delete are O(1) on average. In the worst case, every key collides and each operation is O(n). That happens with a broken __hash__ (for example one that returns a constant) or with deliberate hash flooding.

CPython's dict is an open-addressing table with a clever probe order. Instead of stepping +1, each step shifts perturb right by 5 bits and computes j = (5*j + 1 + perturb) % size. This brings in the high bits of the hash and eventually visits every slot. Since Python 3.6 the dict also keeps a compact array of entries in insertion order, with the hash table holding only small indexes into it. That saves memory and is why dicts remember insertion order, which the language guarantees since 3.7.

Other designs worth knowing: Robin Hood hashing, cuckoo hashing (O(1) worst-case lookup) and Swiss tables, used by Rust's standard HashMap.

Learn it in 4 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Implement separate chaining~1h
  2. 2
    Implement linear probing with tombstones~1h
  3. 3
    Track load factor and rehash~1h
  4. 4
    Compare average and worst-case costs~1h

Key points

  • Insert, lookup and delete: O(1) average, O(n) worst case if all keys collide.
  • Load factor = entries / buckets; resize when it passes about 0.7.
  • Resizing rehashes every key, O(n), but is amortised O(1) per insert.
  • Linear probing suffers from clustering as the table fills.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
class ChainedMap:
    def __init__(self, cap=8):
        self.buckets = [[] for _ in range(cap)]
        self.n = 0

    def put(self, key, val):
        b = self.buckets[hash(key) % len(self.buckets)]
        for pair in b:
            if pair[0] == key:
                pair[1] = val; return
        b.append([key, val]); self.n += 1

    def get(self, key):
        b = self.buckets[hash(key) % len(self.buckets)]
        return next((v for k, v in b if k == key), None)

Add a resize step when n / len(buckets) exceeds 0.75.

Why deletes need tombstones, traced

Capacity 8. Keys 3, 11 and 19 all have 3 as their index (x % 8 = 3), so with linear probing they land in slots 3, 4 and 5. Now delete 11 from slot 4. If we make slot 4 empty, searching for 19 starts at slot 3 (holds 3, not 19), moves to slot 4, sees empty and stops: 19 looks missing. If we mark slot 4 as a tombstone, the search skips it, reaches slot 5 and finds 19. A new insert of 27 also starts at 3; it checks 3, skips the tombstone at 4 while remembering it, checks 5, hits empty slot 6, and then stores 27 in slot 4.

A linear probing map with tombstones and resizing

This compact map stores (key, value) pairs in one list. DEL is the tombstone. put first walks the probe chain to find the key or an empty slot, remembering the first tombstone, so keys are never duplicated. The table doubles when live keys plus tombstones exceed half the capacity, which also clears the tombstones.

python
DEL = object()
class ProbeMap:
    def __init__(self, cap=8): self.t, self.used = [None] * cap, 0  # live + tombstones
    def _find(self, k):
        i, first_del = hash(k) % len(self.t), None
        while self.t[i] is not None:
            if self.t[i] is DEL: first_del = i if first_del is None else first_del
            elif self.t[i][0] == k: return i, True
            i = (i + 1) % len(self.t)
        return (i if first_del is None else first_del), False
    def put(self, k, v):
        i, found = self._find(k)
        if not found and self.t[i] is None: self.used += 1
        self.t[i] = (k, v)
        if self.used * 2 > len(self.t): self._grow()

Quick reference

  • Load factor a = n / m; keep it below about 0.7 for probing, around 1 for chaining
  • Chaining: average O(1 + a) per operation, delete by removing from the bucket list
  • Linear probing misses cost about (1 + 1/(1 - a)^2) / 2 probes: 2.5 at 0.5, 50.5 at 0.9
  • Open addressing delete: leave a tombstone, never an empty slot
  • Doubling on resize makes insert amortised O(1); rehash itself is O(n)
  • CPython dict: open addressing, power-of-two size, grows at 2/3 full, insertion ordered
  • Java HashMap: chaining, initial capacity 16, load factor 0.75, buckets over 8 entries become trees

Common mistakes

  • Deleting from an open-addressing table by emptying the slot, which breaks later lookups.
  • Never resizing, so chains grow and operations become O(n).

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1In linear probing, why can't delete simply set the slot back to empty?

Question 2

2A hash table doubles its capacity whenever it gets too full. What is the amortised cost of an insert?

Question 3

3What is primary clustering?

Question 4

4Your custom class's __hash__ returns 7 for every object. What happens to a set of n such objects?

Question 5

5Which statement about Java's HashMap is correct?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Add a resize step to a chaining map: when n / len(buckets) exceeds 0.75, double the bucket count and reinsert every pair. Show that 100 inserts end with 256 buckets when starting from 8.

  2. Exercise 2medium

    Complete the ProbeMap from the example: write get(k) and delete(k). get returns None for a missing key; delete marks the slot with DEL and returns True if the key existed.

  3. Exercise 3hard

    Write _grow for ProbeMap: double the capacity, reinsert only live entries, and reset used. Explain why tombstones disappear and why used must be recomputed.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is a Python dict lookup really O(1)?
On average, yes, with ordinary keys. The worst case is O(n) if many keys collide, which is rare with built-in types and randomised string hashes.
What is the difference between a dict and a set in Python?
Both are hash tables. A set stores only keys, while a dict stores a value with each key; set and dict use separate implementations but the same hashing ideas.
Why do dicts keep insertion order?
Since Python 3.6, CPython stores entries in a compact array in the order they were added, and the hash table points into it. Python 3.7 made that order part of the language.
When should I use chaining instead of open addressing?
Chaining is simpler, tolerates high load and makes deletes easy. Open addressing uses less memory and is faster due to cache locality, so most high-performance tables use it.

Go deeper

ShareXLinkedInWhatsApp