Hash Table — Separate Chaining
A hash table with separate chaining maps each key to a bucket via a hash function (here h(k) = k mod capacity) and resolves collisions by storing a linked list of every key that hashes to that bucket. Operations run in O(1) on average; a collision extends one bucket's chain while leaving every other bucket untouched.
Think of an apartment mailbox wall where apartment number mod number of boxes selects a box directly, and tenants who map to the same box share its stack of envelopes. Looking up a letter jumps straight to one box and scans only the envelopes inside it.
How Separate Chaining Works
The table is an array of capacity buckets, each holding a list of keys. Every operation starts by computing h(k) = k mod capacity, indexing directly into bucket h(k), and working only within that single chain.
insert(k) walks the chain comparing each node's key against k. If it finds a match, it stops without modifying the table because this implementation uses set semantics, where inserting an existing key is a no-op rather than an update. If the walk reaches the end without a match, the new key is prepended to the head of the chain. With a linked list, prepending takes O(1) time with no element shifting. (The displayed Python code calls chain.insert(0, ...) on a dynamic array, which shifts elements in O(chain length) time; this is acceptable for a short teaching chain, whereas a production table uses a true linked list with a head pointer.)
get(k) walks the same chain and returns the index of the match, or -1 if the key is absent. delete(k) walks until it matches, unlinks that node, reconnects the remaining chain, and returns True. Unlike open addressing, deletion requires no tombstones, no element shifting, and no changes to other buckets.
All three operations share the same structure: hash the key, walk one chain, and act on the match or miss. Separate chaining isolates collisions by turning a table-wide slot conflict into a short linear scan inside a single bucket.
Separate Chaining Step by Step
The default table starts with 5 empty buckets, so h(k) = k mod 5. This sequence walks through hashing, a collision chain forming, a hit, and a deletion; missing-key and duplicate-insert behavior follow below.
insert(7)→hash(7) = 7 % 5 = 2. Bucket 2 is empty, so the walk ends immediately and 7 is prepended: bucket 2 is now[7].insert(12)→hash(12) = 12 % 5 = 2, producing the first collision in bucket 2. The cursor checks[2][0] = 7(not 12), reaches the end of the chain, and prepends 12 at the head: bucket 2 is now[12, 7].insert(3)→hash(3) = 3 % 5 = 3. Bucket 3 is empty, so prepending gives[3], unaffected by the collision chain in bucket 2.insert(17)→hash(17) = 17 % 5 = 2. The walk checks[2][0] = 12 ≠ 17and[2][1] = 7 ≠ 17, reaches the end of the chain, and prepends 17: bucket 2 is[17, 12, 7].get(12)→hash(12) = 2. The cursor checks[2][0] = 17(miss) and[2][1] = 12(match), returning position 1 after two comparisons even though the table holds four keys.delete(12)→hash(12) = 2. Same walk: 17 misses, 12 matches at depth 1, and the node is spliced out. Bucket 2 closes up to[17, 7].
A get or delete for an absent key, such as get(22) (which also hashes to bucket 2), walks the entire chain before reporting not found. Because every miss pays the full chain length, performance depends on keeping chains short.
The player caps chain length at 6 nodes, reporting that an insert "would exceed visualization depth 6 (no real limit)." That limit keeps chains legible on the 1920×1080 canvas; a real separate-chaining table has no fixed maximum chain length and only slows down as chains grow.
In the animation, buckets stack vertically and each chain extends rightward as linked nodes. The cursor steps from node to node during comparison, highlights a matched node in green, and slides a newly prepended key into the chain's head, separating the hash, walk, and update into three distinct beats.
Time and Space Complexity
Let α = n / capacity be the load factor, which equals the average chain length under a well-distributed hash function.
| Operation | Average | Worst |
|---|---|---|
insert | O(1) | O(n) |
get | O(1) | O(n) |
delete | O(1) | O(n) |
More precisely, average time complexity is O(1 + α): one hash computation plus an expected walk of α nodes. Keeping α bounded by a small constant (chaining handles α around 1.0 well, whereas open addressing needs a lower load factor) keeps operations O(1). In the worst case, all keys hash to one bucket, the table degenerates into a single linked list, and every operation takes O(n). While unlikely by chance, hash-flooding attacks construct colliding keys on purpose, which is why many runtimes randomize the hash seed for attacker-supplied key types such as strings.
Space is O(n + m) for n entries and m buckets: the bucket array occupies m slots regardless of occupancy, and the n nodes are distributed across the chains.
Edge Cases
- Duplicate insert. The walk finds the existing key and returns without changing the table under set semantics; a key/value dictionary would update the associated value in place.
- Operating on an empty bucket.
insertprepends immediately, whilegetanddeletereach the end of a zero-length chain and report not found with no special-case branch. - Delete of an absent key. The walk traverses the entire chain, reaches the end, and returns
False, leaving the table unchanged. - All keys colliding. This remains valid and produces correct results, though every operation degrades to linear time because the bucket becomes a single linked list.
Common Mistakes
- Comparing
ntocapacityas in open addressing. A chaining table with 1000 buckets and 5000 entries averages 5 nodes per chain and still functions properly. Chaining allows α above 1; resize thresholds are performance policy choices (Java'sHashtableuses chaining with a default threshold of 0.75) rather than a hard capacity limit. - Never resizing. Keeping
capacityfixed asngrows makes chains longer and turns lookups into linear scans. Resize and rehash once α grows past a small constant. - Skipping the duplicate check on insert. Prepending without scanning the chain allows duplicate keys to coexist:
getreturns the first copy,deleteremoves only one copy, and set invariants break. - Trusting
k mod capacityin production. Simple modulo works for a teaching example, but keys sharing a common factor withcapacitycluster into a subset of buckets. Production tables mix bits first (such as MurmurHash or SipHash), and some seed string-like keys (Python seedsstrandbytes, while itsinthash stays fixed), depending on the language and key type. - Treating chaining and open addressing as interchangeable. Separate chaining is simpler to implement, handles deletion cleanly, and tolerates high load factors, at the cost of pointer chasing and cache misses. Open addressing keeps entries in one contiguous array with better cache locality at moderate load factors. Choose between them based on expected load factor and memory-access patterns.
Keep exploring
A few lessons that share the same technique or lead into the next idea.
Embed this lesson in a blog, docs, or course?
Found a mistake or something unclear?