Essential Data Structures home
Hash Table
A table that finds a value by its key, not by searching. A hash function turns the key into a bucket number, and the value waits in that bucket.
What it is
A hash table stores key-value pairs: a name and the thing that belongs to it. To find a value, it hashes the key, turning it into a number, takes that number modulo the number of buckets, and looks in that one bucket. It never scans the whole table.
The hash function is the whole design. A good one spreads keys evenly across buckets, so most buckets hold zero or one item. A bad one piles keys into a few buckets, and the table slows down to a list. The function must also be deterministic: the same key must always hash to the same bucket, or the value can never be found again.
Collisions, two keys landing in the same bucket, are expected, not a bug. The usual fix is chaining: each bucket holds a small list of the pairs that landed there, and lookup checks only that short list. The other fix is open addressing, where a colliding key probes nearby buckets until it finds an empty one.
How it works
Insert hashes the key, goes to its bucket, and adds or replaces the pair. Lookup hashes the key and checks only that bucket. Delete does the same, then removes the pair. When the table gets crowded, measured by the load factor (items divided by buckets), it grows: a bigger array is allocated, every pair is rehashed into its new bucket, and the old array is dropped. That resize is expensive once, then cheap again, like a dynamic array growing.
Python dictionaries, Java HashMaps, and JavaScript objects and Maps are all hash tables. A hash set is the same idea without values, just keys, used to answer "have I seen this before?" in constant time.
Complexity
| Operation | Average | Worst case |
|---|---|---|
| Insert | O(1) | O(n) |
| Lookup by key | O(1) | O(n) |
| Delete by key | O(1) | O(n) |
| Search by value | O(n) | O(n) |
The worst case happens when many keys collide into one bucket, so lookup degrades to scanning that bucket. A good hash function and timely resizing keep that rare.
When to use it, and when not to
Use a hash table when you need to find things by name or by ID: user accounts, word counts, caches, indexes, and deduplication. If the question is "what goes with this key?", a hash table is usually the answer, and it is the fastest one.
Do not use it when order matters. A hash table does not keep keys sorted, and it does not remember insertion order unless the implementation promises it (Python dicts do, as a guarantee since Python 3.7, but that is a feature of that implementation, not of hash tables in general). For sorted order, use a balanced tree. For "find the smallest key" or "list keys in range", a hash table is the wrong tool. It also needs a good hash function for the key type, and hashing is a poor fit when keys are large and mostly compared by equality in a tiny set, where a plain list is simpler.
Where you meet it
Almost every program uses one. A dictionary in Python, a cache that maps a URL to a saved page, a database index, a spell checker that asks "is this word in the dictionary?", and a compiler's symbol table that maps a variable name to its type are all hash tables.
In Python
phone_book = {"ada": "555-0101", "bob": "555-0102"}
phone_book["cy"] = "555-0103" # insert, O(1) on average
print(phone_book["ada"]) # lookup by key, O(1) on average
print("bob" in phone_book) # membership test, O(1) on average
del phone_book["bob"] # delete by key
seen = {"ada", "cy"} # a set is a hash table without values
print("cy" in seen) # True
In short: a hash table trades order for speed. Give up sorting, and finding anything by its key becomes nearly instant.
Sources
- Hash table, Wikipedia
- Python tutorial, Data Structures (dictionaries)
- Cormen, Leiserson, Rivest, and Stein, Introduction to Algorithms, chapter 11