Question presented to candidate: "Explain how a hash table works under the hood: what happens when you insert a key, how collisions are handled, and why lookups are fast. Then tell me how Python's built-in hash map behaves, and sketch a simple one in Python if we have time."
What a strong answer should cover:
- Hash function โ hash code โ bucket index (modulo the bucket count), and the rule that equal keys must have equal hashes.
- Collision handling: separate chaining versus open addressing (probing), and tombstones on deletion.
- Load factor and resizing with rehashing, giving amortized O(1) inserts.
- Average O(1) versus worst-case O(n), what causes the worst case (bad hash, adversarial keys) and the defences.
- No ordering guarantees from hashing itself; a tree map when order or ranges matter.
- Python specifics:
dictandsetare hash tables (CPython uses open addressing), keys must be hashable (alistis not),dictkeeps insertion order since Python 3.7, andstrhashes are randomised per process.
Code / implementation expected: Optional โ a small separate-chaining table with put, get, remove and resize in Python, or correct use of the built-in map.