#9 most askedVery commonMediumComplexity
How does a hash table work?
New to Complexity? Learn it from scratch firstBig-O in Plain English β
π’ Asked in real interviews
No reports yet. Were you asked this? Be the first to say where.Explain how a hash table (Python dict, JS Map) gives O(1) average lookups, and what happens on collisions.
π€ Answer it out loud, then check yourself
Say your answer as if the interviewer is listening (30β90 seconds). Then reveal what a strong answer covers and tick what you said.
class TinyHashMap:
def __init__(self, size=4):
self.buckets = [[] for _ in range(size)]
def put(self, key, value):
bucket = self.buckets[hash(key) % len(self.buckets)]
for pair in bucket:
if pair[0] == key:
pair[1] = value
return
bucket.append([key, value])
def get(self, key):
for k, v in self.buckets[hash(key) % len(self.buckets)]:
if k == key:
return v
m = TinyHashMap()
for i, word in enumerate(["ada", "bo", "cy", "dev", "eli"]):
m.put(word, i)
print(m.get("dev"), [len(b) for b in m.buckets])
Answer out loud first, then compare.
Want to rehearse it?Answer this to the AI interviewer and get a verdict β