Hash table
A structure that finds a value by its key in about constant time by hashing the key into a slot; fast lookups, no order.
A hash table runs the key through a hash function that picks a slot in an array and stores the value there. Lookups, inserts and deletes take about the same time whether there are ten entries or ten million, which is why it sits behind JavaScript Map and objects, Python dict, caches like Redis and the join step in many database queries. Two keys landing in the same slot (a collision) are handled by chaining or by probing the next slots, and the table grows when it gets too full.
The limitation is order. A hash table can answer “what is the value for this key” but not “all keys between A and C” or “the ten smallest”; that needs a sorted structure such as a B-tree. Postgres has hash indexes, but they support only equality, so a B-tree is usually the better default.
If attackers control the keys, they can pick ones that all collide and slow a server down. Languages defend against this with randomized hash functions such as SipHash, which Python adopted in PEP 456.
Sources
- Python: PEP 456, Secure and interchangeable hash algorithm peps.python.org
Related terms
- Cryptographic hash function (SHA-256): A function that turns any data into a short fixed-size fingerprint that is practically impossible to reverse or to match with different data.
- B-tree: A sorted, wide and shallow tree that stores keys in disk-sized pages; the default index in most relational databases.
- Bloom filter: A tiny bit array that answers “definitely not in the set” or “probably in the set”, used to skip expensive lookups.
- Consistent hashing: A way to spread keys across servers so that adding or removing a server moves only a small share of keys instead of nearly all of them.
- Big O notation: Shorthand for how the work an algorithm does grows as its input grows, such as O(1), O(log n), O(n) or O(n²).
