A hash table, or hash map, is a data structure that stores key-value pairs in an array of buckets. A hash function turns each key into a bucket index, so insert, search and delete take O(1) time on average. This page explains how it works, with step-by-step animations of separate chaining, searching a chain and linear probing from the VisiGrab app.
// how hash tables work
A hash table stores key-value pairs in an array of buckets. A hash function turns each key into the index of its bucket, so insert, search and delete take O(1) time on average. A hash map is the same thing. A map, or dictionary, is the abstract type that a hash table implements. A hash set stores keys only. As in the app, the table here is a phone book: names are the keys, phone numbers the values.
Hashing maps a key to an index in two stages. A hash function turns the key into an integer, the hash code. The index is the hash code mod m, the number of buckets. The animations here, like the app, use a teaching hash: the sum of the key's character codes. For Jim, J + i + m = 74 + 105 + 109 = 288, and 288 mod 17 = 16.
A good hash function is deterministic and fast, and it spreads keys evenly. A character sum does not: Sid and Kat also sum to 288, and anagrams always collide. Real tables, and the app's code, use the language's hash code: hash() in Python, hashCode() in Java and std::hash in C++. None of them is a cryptographic hash such as SHA-256, which is slower and built so that no one can find a collision.
For integer keys, the division method is h(k) = k mod m. It works best with a prime m not close to a power of 2, since a power of 2 keeps only the key's lowest bits. The 17 buckets here are just a small prime for the demo. The multiplication method is h(k) = ⌊m · (k · A mod 1)⌋, with A ≈ 0.618. The app's info dialog works through both.
A collision is two different keys hashing to the same bucket. There are far more possible keys than buckets, so collisions cannot be avoided. By the birthday paradox, 23 keys in 365 buckets collide more often than not. The two main ways to resolve collisions are separate chaining and open addressing.
In separate chaining, also called open hashing, each bucket holds a linked list of the entries that hash to it. A new entry goes in at the head, in O(1). The app's code first searches the chain, though: if the key is already there, only its value is updated.
Note
In C and C++ each link of a bucket's list is a pointer; in Java and Python it is a reference.
In the player, five names go into an empty table of 17 buckets. Jim, Sid and Kat all hash to 16, and each new entry is chained at the head, so bucket 16 ends as Kat → Sid → Jim.
Since Java 8, HashMap adds new entries at the tail of a chain, not the head. It also turns a bucket of more than eight entries into a red-black tree, once the table has at least 64 buckets.
A search hashes the key and compares keys along that bucket's chain, from the head. In the player, Jim hashes to 16 and is found third, after Kat and Sid.
A search misses when the chain ends with no match, or at once when the bucket is empty. Deletion finds the node the same way and unlinks it. The app shows misses and deletion step by step.
In open addressing, every entry lives in the array itself, one per slot. It is also called closed hashing, because entries stay inside the array; chaining, which keeps them outside, is open hashing. A key's home slot is the one it hashes to. If it is taken, the table probes other slots in a fixed order until one is free. Linear probing tries the next slot, then the next: (h(k) + i) mod m for i = 0, 1, 2 and so on. The mod wraps the probe from the last slot back to slot 0.
In the player, Cam, Mat, Tam and Lee already hold slots 1, 2, 5 and 6 of a 17-slot row. Bob hashes to the free slot 3; Rob hashes to 2, finds 2 and 3 taken and lands in slot 4.
Slots 1 to 6 now form one unbroken run. Any key that hashes into it lands just past its end and makes it longer. This is primary clustering, and it slows linear probing as the table fills.
Quadratic probing tries (h(k) + i2) mod m: home + 1, + 4, + 9 and so on. The growing jumps skip past clusters, but keys with the same home slot still share one path: secondary clustering. With a prime m and the table under half full, it always finds a free slot. Double hashing tries (h1(k) + i · h2(k)) mod m. A second hash sets each key's step, so keys with the same home slot usually take different paths. The app shows quadratic probing step by step, wrap-around included.
A search follows the same probes as insert and stops at an empty slot. So a delete cannot just empty its slot: a later search would stop there and miss keys further along. Instead it leaves a tombstone, a marker that means "a key was here; keep probing". This is also called lazy deletion. Searches step over tombstones, inserts reuse them and a rehash drops them. The app shows the broken search and the fix step by step.
The load factor α = n / m is the number of entries divided by the number of buckets. With chaining, α is the average chain length and can exceed 1. With open addressing, each entry needs its own slot, so α must stay below 1. Tables resize at a threshold: Java's HashMap at 0.75, Python's dict at about 2/3 and C++'s std::unordered_map at 1.0 by default.
To rehash, the table allocates about twice as many buckets and re-inserts every entry, because each index depends on m. One rehash costs O(n), but doubling keeps rehashes rare, so an insert is O(1) amortized. The app steps through a table filling up until it rehashes.
Separate chaining keeps all entries that hash to one bucket in a linked list there. Open addressing stores every entry in the array itself and, on a collision, probes for a free slot: linear probing tries the next slot, then the next; quadratic probing tries the slots 1, 4, then 9 past the home slot. Separate chaining vs open addressing compares them.
The hash function turns the key straight into an index, so a lookup goes to one bucket instead of scanning every key. With a good hash and a bounded load factor, it then compares only a few keys on average.
| Operation | Average | Worst case |
|---|---|---|
| Insert | O(1) | O(n) |
| Search | O(1) | O(n) |
| Delete | O(1) | O(n) |
The average assumes a good hash and a bounded load factor; with chaining, a search costs O(1 + α). The worst case puts every key in one bucket or one cluster. A bad hash causes it, and so does hash flooding, where an attacker sends keys chosen to collide. Java's tree buckets and Python's randomly seeded string hash both defend against it. Space is O(n + m).
| Property | Separate chaining | Open addressing |
|---|---|---|
| Entries | In a list per bucket | In the array, one per slot |
| Load factor | Can exceed 1 | Must stay below 1 |
| Delete | Unlink the node | Leave a tombstone |
| Memory | A node and a link per entry | One flat array |
Chaining copes better with a weak hash or a full table. Open addressing is usually faster while the table is well below full: it follows no links, and linear probing reads neighboring memory.
Python's dict and set use open addressing. Since Python 3.7, a dict also keeps insertion order. Java's HashMap and C++'s std::unordered_map use separate chaining. Java's older Hashtable class is synchronized and rejects null keys; HashMap is not synchronized and allows one null key. C++'s std::map is a sorted tree, not a hash table.
The full source code is on GitHub, in Python, Java and C++.
A hash table keeps no sorted order. A sorted listing, the smallest key or a range query all mean scanning every key. A balanced binary search tree keeps its keys sorted, with O(log n) insert, search and delete even in the worst case. For prefix queries such as autocomplete, a trie wins. An array indexed by the key itself is faster still, but only for small, dense integer keys.
// in the app
In VisiGrab the hash table is a slide show in two parts, separate chaining and open addressing, played one step at a time.
Both ways a search can miss and deletion from a chain. Then a load-factor meter climbs until the table rehashes.
Probes that jump by the squares and wrap around the end, search and delete by the same rule and why a delete leaves a tombstone.
Step through every slide and step back, or jump to any slide from the list. The show reopens where you left it.
Four tabs: the basics and complexity, hash functions with the division and multiplication methods, the load factor and tombstones. The first two have pictures.
Two implementations, chaining and open addressing, explained part by part.
Ten questions to check what you have learned before moving on.
// build your own
Download VisiGrab and step through chaining, probing, rehashing and tombstones yourself.
The hash table is one of 30+ topics. See them all