Skip to the solution
MediumDSA14 min read

How does a hash table work?

849 views

The problem

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: dict and set are hash tables (CPython uses open addressing), keys must be hashable (a list is not), dict keeps insertion order since Python 3.7, and str hashes 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.

  • hash-table

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

14 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonA hash table from scratch: chaining, load factor, resize
PythonThe built-in hash map: word counts
PythonGood hash vs bad hash, counted

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 60 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you validate that a binary tree is a BST?

Continue