Unit 5 of 8 · about 4 hours · explain, implement
Hash tables: collisions, load factor, resizing and tombstones
Hash maps are the default index, counter and cache. Their average is excellent and their worst case is a security incident; both follow from the load factor.
You'll be able to
- Explain chaining and open-addressing costs in the load factor, including the blowup.
- Implement a hash table that resizes at a stated load factor, with deletion that preserves lookup.
- Predict adversarial degradation and name the defense (randomized hashing).
Covers
Read
In this order, only the parts listed
0 of 4 done
- Hash maps and hash setsDSA Handbook - Foundations and linear patterns
What invariant the average-case bound depends on (); LC 1 value-to-index; LC 49 signature keys; LC 242 counters; What it actually costs (the double-plus-rehash resize contract)
- Hash collisions and the load factorDSA Handbook - Foundations and linear patterns
Two strategies, one contract; What it costs to grow; When the contract breaks: LC 128 in two complexities; How the 28C3 attack worked, and what fixed it (SipHash, PEP 456); A second example: LC 380's pointer-redirection trick
Treat the CPython probing recurrence as a reading guide for the source item below, not as a substitute for it.
- Lecture 5: Hash Tables, Sections 5.1 to 5.5 and 5.8 to 5.10Algorithms lecture notes - amortized analysis and hashing
5.2 The Importance of Being Random; 5.3 universal and near-universal definitions; 5.4 Chaining (expected ); 5.5 multiplicative hashing with Theorems 1 and 2; 5.8 Open Addressing (expected at most ); 5.9 Linear and Binary Probing
Read the statements of 5.6 Balls and Bins and 5.7 Perfect Hashing; skip their proofs.
- CPython dict internalsCPython source - list and dict objects
USABLE_FRACTION(currently two-thirds) with its definition comment; the perturbation-probing comment (j = (5*j) + 1 + perturb);dummy(tombstone) entries on deletionFind the three definitions; do not read the whole file.
Focus on
- governs everything: chaining , open addressing ; CPython resizes past .
- Resize doubles and rehashes every entry: an event, amortized by the unit-2 argument.
- Deletion must leave a tombstone: marking the slot empty would cut probe chains and lose keys.
- Deterministic string hashing is attackable (the 2011 HashDoS); Python seeds SipHash per interpreter (PEP 456).
Common mistakes · 3
- Reading insertion order as sorted order; dicts remember arrival, not rank.
- Checking the map after storing on Two Sum style lookup: store-then-check matches an element with itself on inputs like
[3, 3]. - Assuming worst-case : adversarial keys drive any fixed hash to chains.
Try it yourself
Closed-book, before checking anything
dict on Python 3.13.14, recording sys.getsizeof after each insert. The first insert allocates the 8-slot table; assert the later size steps at = 6, 11, 22 and 43, confirming the two-thirds rule. Then delete two keys and assert the byte size and the remaining key order are unchanged.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Derive the expected cost of a chained lookup.Answer
The key hashes to a uniform bucket plus a scan of its chain of expected length : .
2.Why does CPython resize at the 6th insert into an 8-slot table?Answer
The usable fraction is : , so the 6th insert exceeds it and doubles the table.
3.What breaks if deletion marks the slot empty instead of dummy?Answer
Later keys that probed past the deleted slot become unreachable: their chain is cut and lookup wrongly reports absent.
4.State universal hashing in one line and why it helps.Answer
Draw the hash function at random from a family where each colliding pair has probability at most . The adversary cannot fix a bad input set in advance.
Practice
- LeetCode 706: Design HashMap
Attempt cold with hidden tags. Implement
put,getandremovewith chaining or open addressing plus a load-factor resize. Add randomizedput/get/removehistories checked against adictoracle. Judge with the Example operation sequence.After submitting, read the AlgoMaster Design HashMap write-up (https://algomaster.io/learn/dsa/design-hashmap) and the handbook hash-collisions chapter for the resize contract.
You're done when
Your resize script asserts the 6/11/22/43 steps, and your HashMap passes 200 randomized histories against the dict oracle.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 5 more in the section
- DSA Handbook - Foundations and linear patternsHandbook Academy · primary
Study Part 0, Part 1, Part 3 and Part 4 in order, plus the Part 5 Linked-list fundamentals chapter. Use the routing-rule pages for arrays versus lists, map choice, stack versus queue, two pointers, sliding windows and prefix methods before seeing solved code.
- Algorithms lecture notes - amortized analysis and hashingJeff Erickson · support
Use note 9 Amortized Analysis for the summation, taxation, charging and potential-function proofs, and note 5 Hashing for chaining, universal hashing and open-addressing analysis, when the handbook treatment is too brief for a proof.
- CPython source - list and dict objectsPython Software Foundation · reference
Read
list_resizeinObjects/listobject.cfor the growth formula and pattern comment, and theUSABLE_FRACTIONdefinition, perturbation-probing comment and dummy-entry handling inObjects/dictobject.c. Read the cited functions and comments only.
Also in this section
- AlgoMaster DSA - linear structures sliceAlgoMaster · required
Attempt Design HashMap, Longest Substring Without Repeating Characters and Sliding Window Maximum cold. Hide tags, state the invariant first, and add randomized operation histories to Design HashMap.
- MIT 6.042J - asymptotics and invariantsMIT OpenCourseWare · support
Use the asymptotics, state-machine invariants and proof-method readings when a cost or correctness argument is weak. Solve only the matching problems.
- Algorithmica - memory and data layoutSergey Slotin · support
Read the memory hierarchy, cache and complexity-model chapters, then measure one contiguous-versus-linked and one hash-versus-ordered workload crossover.
- NeetCode - unseen linear problemsNeetCode · optional
Use only for two tag-hidden transfer problems after the AlgoMaster slice. Do not start another full roadmap or watch a solution before the attempt is complete.
- Hypothesis documentation - Quickstart and stateful testingHypothesis · support
Follow Quickstart for
@givenstrategies and the pytest combination, Configuring test settings formax_examplesandderandomize, then Rule-based state machines (rule,precondition,invariant,run_state_machine_as_test) for randomized operation histories againstdictanddequeoracles.