Software Engineer
mediumhow-hash-map-works
How does a hash map (hash table) work internally?
Answer
A hash map stores key-value pairs using a hash function to map keys to bucket indices.
**Core ideas:**
- Compute `hash(key)` then `index = hash % capacity`.
- Store entries in a bucket.
**Collisions:** multiple keys can map to the same bucket.
- **Chaining:** bucket holds a list/tree of entries.
- **Open addressing:** probe for the next free slot (linear/quadratic probing).
**Resizing:** When load factor is high, rehash into a bigger table.
**Complexity:** Average O(1) for get/put; worst-case can degrade to O(n) if collisions are extreme or hash is poor.
Related Topics
Data StructuresAlgorithms