Hash tables
Store key–value pairs with average O(1) lookup by computing an index from a hash of the key.
Edited by Alex C, EduAlx · Sources cited below
Explanation
Collisions are handled by chaining or open addressing. Load factor controls performance; tables resize when it gets too high. Hashing was described by Hans Peter Luhn at IBM (1953). Python dict, Java HashMap and database indexes use it.
Example
Code
counts = {}
for w in text.split():
counts[w] = counts.get(w, 0) + 1
How it works, step by step
- Compute hash(key)
- Map hash to a bucket index
- Store or look up in the bucket
- Resolve collisions; resize when load is high
Open the interactive page with diagrams →
People behind it
- Hans Peter Luhn
References
- W. W. Peterson, IBM J. Res. Dev. 1957, 1, 130–146.
Textbooks
- Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein (MIT Press, 4th ed. 2022). 'CLRS', the standard algorithms text.
- The Art of Computer Programming (Vols. 1–4B), Donald E. Knuth (Addison-Wesley, 1968–2023). Monumental work on algorithms.
Related topics
Trees and binary search treesData structures: arrays, linked lists, stacks, queuesHeaps and priority queuesGraph algorithms: BFS, DFS and Dijkstra's shortest pathSorting algorithms (quicksort, mergesort, heapsort)Dynamic programmingAlgorithms and Big-O complexityTuring machines and computabilityError-detecting and error-correcting codesP versus NP