โ† CS Fundamentals
#9 most askedVery commonMediumComplexity

How does a hash table work?

New to Complexity? Learn it from scratch first
Big-O in Plain English โ†’
๐Ÿข Asked in real interviews
No reports yet. Were you asked this? Be the first to say where.
I was asked this

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.

    Try it ยท run and change it
    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 โ†’