Hash Table, step by step.

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 a hash table works

What is a hash table (hash map)?

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.

The name Jim with an arrow into a box labeled Hash Function. A line from the box points to bucket 16 in a column of buckets 13 to 16, and bucket 16 holds Jim's entry: Jim, 555-0147.
The hash function turns a key into an index, and the index picks one bucket: Jim goes to bucket 16.

Hash function: from key to index

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.

Hash collisions and collision resolution

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.

Separate chaining

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.

Two boxes, h("Jim") = 16 and h("Sid") = 16, each with a line to bucket 16 in a column of buckets 14 to 16. Bucket 16 holds a linked list of two entries: Sid, 555-0155, at the head, then Jim, 555-0147.
Jim and Sid both hash to 16, so bucket 16 keeps both entries in a linked list, Sid at the head.

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.

Insert with chaining

All steps as text
  1. This is a hash table: an array of 17 buckets, numbered 0 to 16, all empty. Step forward to fill it.
  2. A hash function turns a key into a number that picks the bucket for its entry.
  3. We'll use this table as a phone book - names (the keys) to phone numbers. We hash Jim's name to find his bucket.
  4. The bucket is empty, so we store Jim's entry - it holds his name (key) and number (value).
  5. Ben hashes to an empty bucket as well.
  6. And Sam to another.
  7. Sid hashes to an occupied bucket - a collision.
  8. Each bucket is a linked list, so chain Sid at the head.
  9. Kat collides too; the chain now holds three.
  10. Five entries in 17 buckets: Kat, Sid and Jim share bucket 16 in one chain, and Sam and Ben sit alone further up, in buckets 0 and 5.
Hash Table — Insert with chaining. Last step: Buckets 10 to 16 of the 17: Kat, Sid and Jim share bucket 16 in one chain, and buckets 10 to 15 are empty.

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.

Search with chaining

All steps as text
  1. To find Jim, run his name through the hash function.
  2. The hash gives 16 - look in bucket 16.
  3. Check the first node: does its key equal Jim?
  4. Kat is not Jim - we follow the next link.
  5. Check the next node: does its key equal Jim?
  6. Sid is not Jim - we follow the next link.
  7. Check the next node: does its key equal Jim?
  8. Jim matches - his number is 555-0147.
  9. One hash and three key comparisons found Jim. A longer chain means more comparisons.
Hash Table — Search with chaining. Step 8: Jim is the third node in bucket 16, after Kat and Sid: his number is 555-0147.

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.

Open addressing and linear probing

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.

A row of slots 0 to 5 with Cam in slot 1 and Mat in slot 2. Below the row a box reads h("Mat") = 1, and an arrow arcs from slot 1 to slot 2: Mat's home slot is Cam's, so Mat was stored in the next slot.
Mat hashes to slot 1, which Cam already holds, so the probe moves on to slot 2.

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.

Insert with linear probing

All steps as text
  1. In open addressing, every entry lives inside the array, one per slot. Here Cam, Mat, Tam and Lee already hold slots 1, 2, 5 and 6 of a 17-slot row. Step forward to insert Bob and Rob.
  2. To insert Bob, run his name through the hash function to find his home slot.
  3. For Bob, the hash returns 3 - his home slot.
  4. This slot is free.
  5. So we store Bob's entry there.
  6. Next, insert Rob.
  7. The hash returns 2 for Rob, but that slot is occupied. How do we solve this?
  8. This is linear probing: we check the next slot, then the next, until a free one appears.
  9. Slot 4 is free - store Rob there.
  10. Every entry has a slot of its own. Slots 1 to 6 now form one run, a cluster that makes later probes longer.
Hash Table — Insert with linear probing. Last step: Every entry has a slot of its own. Slots 1 to 6 now form one run, a cluster that makes later probes longer.

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 and double hashing

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.

Deletion in open addressing: tombstones and lazy deletion

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.

Hash table load factor and rehashing

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.

What is the difference between separate chaining and open addressing?

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.

Why is a hash table lookup O(1) on average?

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.

Hash table time and space complexity

OperationAverageWorst case
InsertO(1)O(n)
SearchO(1)O(n)
DeleteO(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).

Separate chaining vs open addressing

PropertySeparate chainingOpen addressing
EntriesIn a list per bucketIn the array, one per slot
Load factorCan exceed 1Must stay below 1
DeleteUnlink the nodeLeave a tombstone
MemoryA node and a link per entryOne 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.

Hash tables in Python, Java and C++

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++.

Hash table vs binary search tree, trie and array

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.

Where hash tables are used

  • Dictionaries and sets in almost every programming language.
  • Caches and memoization: a result is stored under its input.
  • Databases: hash indexes for equality lookups, and hash joins. Range queries need an ordered index, usually a B-tree.
  • Counting, removing duplicates and interview problems such as two-sum.

Three walkthroughs here.
The whole topic 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.

Misses, deletion, rehashing

Both ways a search can miss and deletion from a chain. Then a load-factor meter climbs until the table rehashes.

Quadratic probing and tombstones

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.

Forward and back

Step through every slide and step back, or jump to any slide from the list. The show reopens where you left it.

Theory and complexity

Four tabs: the basics and complexity, hash functions with the division and multiplication methods, the load factor and tombstones. The first two have pictures.

Python, Java and C++

Two implementations, chaining and open addressing, explained part by part.

Quiz

Ten questions to check what you have learned before moving on.

Fill a hash table
bucket by bucket.

Download VisiGrab and step through chaining, probing, rehashing and tombstones yourself.

The hash table is one of 30+ topics. See them all