A hash table maps keys to values via a hash function , giving average-case lookup, insert, and delete.
How it works:
- Compute to get an array index
- Store the value at that index
- Handle collisions (two keys mapping to the same index) via chaining (linked lists) or open addressing (probing)
Performance:
- Average: for all operations
- Worst case: if all keys collide (pathological hash function)
- Load factor (items / buckets) — resize when exceeds threshold (typically 0.7)
Where hash tables are critical in ML:
- Python dicts and sets — the backbone of all data processing code
- Deduplication — removing duplicate training examples (hash the content)
- Feature hashing (hashing trick) — map high-dimensional sparse features to fixed-size vector without a dictionary. Used in large-scale linear models and NLP
- Caching — memoizing expensive computations (e.g., tokenized sequences, preprocessed batches)
- Counting / frequency estimation — token frequencies, vocabulary building
- Locality-Sensitive Hashing (LSH) — approximate nearest neighbors by hashing similar items to the same bucket → Approximate Nearest Neighbor Search
Consistent hashing — used in distributed data sharding: when a node joins/leaves, only keys need remapping. Relevant for distributed dataset storage.
See also: Approximate Nearest Neighbor Search, Big-O and Complexity Analysis