Mental model
Suppose you store a thousand phone numbers in an array and want the one for "Ada". Without order you scan everything: O(n). Sorted, binary search finds it in about ten steps. A hash table does better on average: it computes where Ada's entry must be and looks only there.
It has two parts:
- A bucket array of
capacityslots. - A hash function that turns a key into an integer. Reducing that integer to the range
0 … capacity − 1picks the key's bucket.
To store a key, put it in its bucket. To find a key, compute the same bucket and look only there. If every key had its own bucket, every operation would be one hash and one comparison.
The lab uses integer keys and the simplest possible rule:
bucket = floorMod(key, capacity)
floorMod is the remainder that is never negative, so key -3 in a 4-bucket table goes to bucket 1.
Real runtimes first compute a hash code from the key and mix its bits; the
runtime section covers that.
Collisions
There are many more possible keys than buckets, so different keys will share a bucket. That is a
collision, and it is normal, not an error. Run the Collisions preset: in a 4-bucket table, keys
1, 5 and 9 all give floorMod(k, 4) = 1.
With separate chaining, each bucket holds a small list (a chain) of the entries that hashed there:
put(key, value):
chain = buckets[bucketOf(key)]
for each entry in chain:
if entry.key == key: entry.value = value; return # keys are unique: update
if (size + 1) / capacity > 0.75: resize()
buckets[bucketOf(key)].append((key, value)) # recompute: capacity may have changed
size += 1
get(key):
for each entry in buckets[bucketOf(key)]:
if entry.key == key: return entry.value
return not found
The hash narrows the search to one bucket; the equality check decides which entry, if any, is the
right one. Both are needed. The hash alone cannot distinguish 1 from 5 here, and comparing with ==
against every key in the table would be a linear scan.
Removal finds the entry the same way and takes it out of its chain. With chaining that is all it takes. Open addressing (below) cannot simply empty a slot.
Load factor
The load factor is
α = size / capacity
the average number of entries per bucket. Under the usual modelling assumption that the hash spreads keys uniformly and independently over the buckets, a chain has α entries on average. Then:
- an unsuccessful lookup compares against a whole chain: about α comparisons, plus the hash;
- a successful lookup stops halfway on average: about 1 + α/2 comparisons.
Both are O(1 + α). Keep α below a constant and every operation is expected O(1). "Expected" depends on the hash behaving well for your keys; it is not a guarantee about every input.
The teaching table starts with 4 buckets and doubles when an insert would push α above 0.75. Run Load factor and resize: keys 3, 7 and 12 give α = 3/4 = 0.75, which is allowed; the fourth key would make it 4/4 = 1.0, so the table grows to 8 buckets first.
Resizing means rehashing
A key's bucket depends on the capacity, so after a resize every key must be placed again. Key 7 sits in bucket 3 of a 4-bucket table but in bucket 7 of an 8-bucket table. The lab shows the new bucket array next to the old one while each key moves.
One resize costs O(n). Because the capacity doubles, resizes get rarer as the table grows, and the same argument as for dynamic arrays applies: n insertions cause fewer than 2n key moves in total, so insertion is amortized O(1) (and expected, because of hashing).
The teaching version never shrinks. Neither do most built-ins unless asked, which is why a table that once held a million entries keeps its large bucket array after you remove them.
Costs
| Operation | Expected (good hash, bounded α) | Worst case (all keys in one bucket) |
|---|---|---|
get, contains |
O(1) | O(n) with list chains |
put (new key) |
amortized O(1) | O(n) |
put (existing key) |
O(1) | O(n) |
remove |
O(1) | O(n) |
| iterate all entries | O(n + capacity) | O(n + capacity) |
| space | O(n + capacity) |
The worst case is real. A poor hash function, or an attacker who chooses keys that collide, can make
every operation linear. Python and .NET randomize string hashing per process, and Java's HashMap
turns crowded buckets into balanced trees, both to limit that damage.
Why the bucket rule matters
The teaching table's capacities are powers of two, so floorMod(key, capacity) keeps only the lowest
bits of the key. Keys that differ only in higher bits collide. Insert 0, 4, 8 and 12: at capacity 4
they all land in bucket 0; after growing to 8 they still share two buckets (0 and 4). Real tables
avoid this by mixing the hash first. Java's HashMap XORs the high 16 bits of hashCode() into the
low ones before masking; .NET's Dictionary and libstdc++'s unordered_map use prime bucket counts.
Open addressing, briefly
The other main family stores entries directly in the slot array. On a collision, it probes other slots in a fixed sequence until it finds the key or an empty slot: the next slot (linear probing), slots at growing distances (quadratic probing), or steps from a second hash (double hashing). There are no chains and better cache behaviour, but it degrades sharply as the table fills, so the load factor must stay well below 1. Deletion cannot just empty a slot, because that would cut a probe sequence in half and hide keys stored further along; the slot gets a tombstone marker instead. A later lesson in this module covers it in detail.
What real runtimes do
The lab is a conceptual model. The built-ins share its ideas but not its details, and the details below are implementation choices, not language guarantees, unless noted.
C# Dictionary<K,V> |
Python dict |
Java HashMap<K,V> |
C++ std::unordered_map<K,V> |
|
|---|---|---|---|---|
| Collision strategy | chaining, with chains as index links inside one entries array | open addressing with a pseudo-random probe sequence | chaining; a crowded bin becomes a red-black tree | chaining (the standard's bucket interface requires it in practice) |
| Bucket count | prime | power of two | power of two, default 16 | prime in libstdc++ |
| Grows when | the entries array is full (load ≈ 1.0) | about two thirds of the slots are used | size exceeds 0.75 × capacity (documented default) | size exceeds max_load_factor() × bucket_count(); default 1.0 (standard) |
| Iteration order | unspecified | insertion order (language guarantee since 3.7) | unspecified | unspecified |
Missing key with [] |
KeyNotFoundException |
KeyError |
get returns null |
operator[] inserts a default value |
| Safe lookup | TryGetValue |
get(k, default), in |
getOrDefault, containsKey |
find, contains (C++20) |
| Set type | HashSet<T> |
set |
HashSet<E> (backed by a HashMap) |
std::unordered_set<T> |
More precisely:
- .NET
Dictionarykeeps anint[]of buckets and an array of entries, each with anextindex. A bucket points at the first entry of its chain, so chaining happens without allocating a node per entry. Removed entries go on a free list for reuse. It grows to a prime of at least twice the count. Lookups useGetHashCodeandEquals, or anIEqualityComparer<TKey>you pass in. - CPython
dicthas, since 3.6, a compact layout: a dense array of entries in insertion order plus a sparse index table that is probed with open addressing. Deleted slots are marked with a dummy value (a tombstone). The hash of an integer is the integer itself for small values, except thathash(-1)is -2, because -1 signals an error inside CPython.sethas its own, separate open-addressing implementation. - Java
HashMapspreads the hash (h ^ (h >>> 16)) and masks it withcapacity − 1. When one bin reaches 8 entries and the table has at least 64 buckets, that bin becomes a red-black tree, so a bin full of colliding keys costs O(log n) to search instead of O(n), best when the keys areComparable. Smaller tables resize instead.LinkedHashMapkeeps insertion order. - C++
unordered_mapexposes buckets directly (bucket_count(),bucket(key),load_factor(),rehash(n),reserve(n)). A rehash invalidates iterators but not pointers or references to elements, which the node-per-element design makes possible.std::hash<int>is the identity function in libstdc++.
The equality and hash contract
Every hash table relies on one rule: if two keys are equal, their hashes must be equal. The reverse need not hold (that is a collision). Break the rule and a key you just stored becomes unfindable, because the lookup computes a different bucket.
- C#: override
EqualsandGetHashCodetogether (or implementIEquatable<T>); records and tuples do it for you. - Python:
__eq__and__hash__go together. Defining__eq__alone sets__hash__toNone, making instances unhashable. Mutable built-ins such aslistare unhashable for this reason. - Java: override
equalsandhashCodetogether; records generate both. - C++: provide
operator==and a hash (astd::hashspecialization or a hasher type passed as a template argument).
Never mutate a key in a way that changes its hash while it is inside a table: the entry stays in the old bucket and lookups go to the new one.
The teaching implementation
The four listings implement the lab's model exactly: integer keys, floorMod bucket selection
(Python's % already floors; C# and C++ use ((k % c) + c) % c; Java uses Math.floorMod), 4 initial
buckets, doubling when (size + 1) / capacity > 0.75, checked in integers as
4 × (size + 1) > 3 × capacity. Each chain is the language's dynamic array of key–value pairs rather
than a linked list; that keeps the code short and changes no bound. All four recompute the bucket after
a resize, because the capacity changed; in C++ the old chain reference would also dangle, since the
resize replaced the bucket vector it pointed into. The listings are checked against one shared fixture
of put, get and remove sequences, including collisions, overwrites and resizing.
Common mistakes
- Calling hash tables "O(1)" without the conditions: it is expected O(1) with a good hash and a bounded load factor, amortized for inserts, and O(n) in the worst case.
- A negative bucket index from
%on a negative hash in C#, Java or C++. - Not rehashing on resize, or reusing the old bucket index after it.
- Overriding equality without hashing (or the reverse) in a key type.
- Mutable keys whose hash changes after insertion.
- Relying on iteration order of
Dictionary,HashMaporunordered_map. Only Python'sdictpromises one. - Using C++
map[key]to test membership: it inserts the key if it is missing.
Edge cases
- A missing key:
getscans one bucket and reports not found; it is not an error in the teaching table. puton an existing key updates the value; the size and load factor do not change, and no resize happens.- Removing a missing key: reported, nothing changes (Update and remove preset).
- Negative keys:
floorModmaps them into range (−3 → bucket 1 of 4). - Every key in one bucket: correct, just slow.
Worked practice
1. Starting from the empty teaching table (4 buckets), insert keys 0, 4, 8, 12. When does it resize, and where does each key end up?
Answer
0, 4 and 8 all go to bucket 0 (α = 0.75 after the third, allowed). Inserting 12 would make α = 1.0, so the table doubles to 8 and rehashes, in old bucket order: 0 → 0, 4 → 4, 8 → 0. Then 12 → bucket 4. Result: bucket 0 holds 0 and 8, bucket 4 holds 4 and 12, the other six are empty. The keys share low bits, so a bigger table does not separate them.
2. A chained table has 1,000 keys in 512 buckets. Roughly how many comparisons does a lookup of a missing key need, assuming a good hash?
Answer
α = 1000 / 512 ≈ 1.95, so about two key comparisons on average (plus the hash). A linear scan would need 1,000. The teaching table would never be this full: it doubles before α passes 0.75.
3. Why can open addressing not delete by simply emptying the slot?
Answer
A lookup probes until it finds the key or an empty slot. If a key B was placed after probing past key A's slot, emptying A's slot makes later lookups for B stop there and wrongly report B missing. A tombstone says "keep probing, but this slot can be reused for inserts".
4. In Python, d = {}; d[1] = 'a'; d[True] = 'b'. How many entries does d have?
Answer
One: {1: 'b'}. True == 1 and hash(True) == hash(1), so they are the same key; the second assignment
updates the value and keeps the original key object 1. It is the equality contract at work.
Summary
- A hash table hashes a key to a bucket and searches only that bucket; equality picks the entry.
- Collisions are unavoidable; chaining stores colliding entries in a per-bucket list.
- Load factor α = size / capacity; with a good hash, operations cost expected O(1 + α).
- Resizing rehashes every key; doubling makes insertion amortized O(1).
- Real tables differ: chaining in .NET, Java and C++, open addressing in CPython, tree bins in Java, insertion order only in Python. Every key type must keep equal keys' hashes equal.