Explain buckets, collisions, load factor and resizing.
Use it when you must test "have I seen this?", count items by key, or find a key's value. The order of the keys must not matter. Signal words: seen before, look up by id, count by key, constant time.
Start an array of buckets. Choose a hash function that gives the same bucket for the same key and spreads different keys evenly.
Step compute the bucket of the key. Search only that bucket (a chain, or the probe run). Add the key if it is absent.
Stop a search stops when it finds the key, or reaches the end of the chain, or an empty slot.
It does not keep keys in order. Range questions, such as "the next larger id", need a sorted structure instead.
Cost: about one step on average when the load factor is kept below a limit and the hash spreads keys evenly. In the worst case, when every key shares one bucket, a lookup costs O(n).
In this lesson you learn how a hash table finds a key in one step. A key points to a bucket, and a search looks in that one bucket.
At a payments app, every payment request carries an id. Clients retry when a network fails, so the same id can arrive again, and a payment must never be charged twice. Your team lead sets the requirement.
Your team lead says: For every request, the service must answer one question: have we stored this payment id before?
The service stores a million ids and answers 20,000 requests a second, and each answer must be quick.
Here is a short test. The service has stored the ids [14, 9, 21, 4, 19, 6]. A request with id 19 must be recognised. A request with id 8 must be reported as new.
So the task is this: store ids, and answer "stored or not?" in a few steps, however many ids there are.
Picture a post office with five numbered pigeonholes behind the counter. A letter with a number goes into the pigeonhole whose number is the remainder when you divide the letter's number by five. Letter 14 goes into pigeonhole 4, and letter 21 into pigeonhole 1.
To find letter 19, you do not search the whole wall. You work out 19 divided by 5, leave remainder 4, and look in pigeonhole 4 only. If two letters belong in one pigeonhole, they sit in a small pile there.
The rule that turns a letter number into a pigeonhole is the hash function. The pigeonholes are the buckets of this lesson.
A hash table is a wall of pigeonholes: the remainder of a key's number says which hole to look in.
Before you write code, store the test ids by hand. It shows you how much work one answer takes.
Solve it by hand: Payment ids into five pigeonholes by hand. The hand-solve sheet loads in your browser.
You work at the whiteboard. You write the ids in a line. For each new request, you read the line from the start, and you stop when you find the id or reaches the end.
Stored ids, in the order they arrived: [14, 9, 21, 4, 19, 6]. Four requests come in.
| Request | Where You find it | Comparisons | Answer |
|---|---|---|---|
| 19 | position 5 | 5 | stored |
| 14 | position 1 | 1 | stored |
| 8 | not in the line | 6 | new |
| 6 | position 6 | 6 | stored |
The table shows that finding a stored id costs its position, and a new id costs the whole line. On average, a search reads about half of the line, and a miss reads all of it.
Look at what grows. With six ids, a miss costs 6 comparisons. With a million ids, a miss costs a million.
Remember this. You will use it soon.
You turn the hand method into code.
Start with a correct version. Keep the ids in a list, and scan it for every request.
def seen_before(stored_ids, payment_id):
for stored in stored_ids: # scan the whole list
if stored == payment_id:
return True
return FalseThis is correct. It compares the id with every stored id until it finds a match, so one lookup costs up to n comparisons: O(n). The team keeps it as the reference.
Now check real traffic.
At peak, the service stores a million ids, and 20,000 requests a second each need an answer.
Here is the count for one second of traffic:
So the service falls behind at once. It would need about a hundred machines for this one check.
Predict the cost
Q A service stores 1,000,000 ids in a list and scans it for each lookup. Each lookup makes about 500,000 comparisons, and 20,000 lookups arrive each second. About how much work arrives each second at 10^8 operations a second?
Answer: C
20,000 × 500,000 is 10^10 comparisons. At 10^8 a second, that is 100 seconds of computing for each second of traffic, so one machine falls behind immediately.
The first attempt is correct, but a lookup grows with the number of stored ids. Now the team looks for a way to search a small part of the list.
Look at the pigeonholes drawn on the whiteboard.
The id already tells us where it lives. Why read the whole list? Can we do better by looking in one place?
The idea is to use the id to choose where to look. Make an array of m buckets. Compute the bucket of a key from the key itself, with a rule that always gives the same answer. For integer keys, a common rule is the remainder after dividing by m:
key % m. The same key always gives the same bucket.Two different keys can reach the same bucket. Keys 14 and 9 both leave remainder 4 when divided by 5. That is a collision, and it is normal, because there are far more possible keys than buckets. The table needs a plan for it.
How full the table is matters. The load factor is the number of stored keys divided by the number of buckets. With a low load factor, chains and probe runs are short.
When the table gets too full, it doubles its buckets and moves every key to its new bucket. Doubling costs a lot once, but it is rare, so the average cost of an insert stays constant.
| Step | Key | Bucket (key mod 5) | What happens | Buckets after |
|---|---|---|---|---|
| 1 | 14 | 4 | new key: joins the chain of bucket 4 | 4: [14] |
| 2 | 9 | 4 | new key: joins the chain of bucket 4, behind 14 | 4: [14, 9] |
| 3 | 21 | 1 | new key: joins bucket 1 | 1: [21], 4: [14, 9] |
| 4 | 14 | 4 | search bucket 4: 14 is there, so skip it | no change |
| 5 | 4 | 4 | new key: joins the chain of bucket 4 | 4: [14, 9, 4] |
| 6 | 19 | 4 | new key: joins the chain of bucket 4 | 4: [14, 9, 4, 19] |
| 7 | 6 | 1 | new key: joins bucket 1, behind 21 | 1: [21, 6] |
Now a lookup for id 19 computes 19 mod 5 = 4, and compares with at most 4 ids in one chain. A lookup for id 8 computes 3, finds bucket 3 empty, and answers "new" without comparing at all. The list needed 5 and 6 comparisons.
Exercise · Predict the output: Where do the keys land?. A table has 6 slots and uses linear probing, and -1 marks an empty slot. What does this print?
keys = [11, 5, 17, 6, 11]
size = 6
table = [-1] * size
for key in keys:
slot = key % size
while table[slot] != -1 and table[slot] != key:
slot = (slot + 1) % size
if table[slot] == -1:
table[slot] = key
print(*table)Race: Scan a list, against look in one bucket. The operation counter loads in your browser.
The race counts comparisons for n lookups of stored ids, with as many buckets as ids. At 10,000 ids and 10,000 lookups, the list scan makes 50,269,168 comparisons. The table makes 14,566. That is about 3,500 times fewer, and the gap grows with n.
Lookup and store touch one bucket only: find the id in its chain, or add it to the end.
A small table with 8 slots uses linear probing. The keys arrive as [10, 3, 18, 26, 11, 3, 2, 15]. The player stops at five steps and asks you to predict.
Dry run: Predict each step: a table of eight slots. The step-by-step player loads in your browser.
Reading without the player? Cover the last column and predict it row by row.
| Key | Hash (key mod 8) | Slots passed | Ends up in | Table after |
|---|---|---|---|---|
| 10 | 2 | none | slot 2 | slot 2: 10 |
| 3 | 3 | none | slot 3 | slots 2, 3: 10, 3 |
| 18 | 2 | slots 2, 3 are taken | slot 4 | slots 2, 3, 4: 10, 3, 18 |
| 26 | 2 | slots 2, 3, 4 are taken | slot 5 | slot 5: 26 |
| 11 | 3 | slots 3, 4, 5 are taken | slot 6 | slot 6: 11 |
| 3 | 3 | slot 3 holds 3 | already stored | no change |
| 2 | 2 | slots 2 to 6 are taken | slot 7 | slot 7: 2 |
| 15 | 7 | slot 7 is taken, then wraps | slot 0 | slot 0: 15 |
Look at keys 18, 26 and 11. They hash to 2 or 3, but they sit in slots 4, 5 and 6, because a run of taken slots pushes them along. That run is called a cluster, and long clusters make a lookup slow. Key 15 shows the wrap: it hashes to slot 7, finds it taken, and continues at slot 0.
Here is the rule that keeps the table correct. Every line of the templates below exists to protect it.
Every key is stored once, in the bucket its hash points to, so a search of that bucket finds the key or proves it absent.
At the start the table is empty, so the rule holds. To store a key, the template computes its bucket, searches there for the key, and adds the key only if it is not there. So the key is in its bucket, once.
A search then follows the same path. It computes the same bucket, because the hash function is fixed, and the key can be nowhere else. If the search finishes without a match, the key is absent.
Use it when you must test "have I seen this?", count items by key, or find a key's value. The order of the keys must not matter. Signal words: seen before, look up by id, count by key, constant time.
Start: an array of buckets. Choose a hash function that gives the same bucket for the same key and spreads different keys evenly.
Step: compute the bucket of the key. Search only that bucket (a chain, or the probe run). Add the key if it is absent.
Stop: a search stops when it finds the key, or reaches the end of the chain, or an empty slot.
It does not keep keys in order. Range questions, such as "the next larger id", need a sorted structure instead.
Cost: about one step on average when the load factor is kept below a limit and the hash spreads keys evenly. In the worst case, when every key shares one bucket, a lookup costs O(n).
def build_chains(keys, buckets):
# [1] An empty chain for every bucket.
chains = [[] for _ in range(buckets)]
for key in keys:
# [2] The bucket of a key is its remainder after dividing by the bucket count.
bucket = key % buckets
# [3] Search only that chain: a key already in it is stored once, so skip it.
found = False
for stored in chains[bucket]:
if stored == key:
found = True
if found:
continue
# [4] A new key joins the end of its chain.
chains[bucket].append(key)
# [5] Report the chains.
return chainspublic int[][] buildChains(int[] keys, int buckets) {
// [1] An empty chain for every bucket.
java.util.List<java.util.List<Integer>> chains = new java.util.ArrayList<>();
for (int b = 0; b < buckets; b++) {
chains.add(new java.util.ArrayList<>());
}
for (int key : keys) {
// [2] The bucket of a key is its remainder after dividing by the bucket count.
int bucket = key % buckets;
// [3] Search only that chain: a key already in it is stored once, so skip it.
boolean found = false;
for (int stored : chains.get(bucket)) {
if (stored == key) {
found = true;
}
}
if (found) {
continue;
}
// [4] A new key joins the end of its chain.
chains.get(bucket).add(key);
}
// [5] Report the chains.
int[][] result = new int[buckets][];
for (int b = 0; b < buckets; b++) {
result[b] = chains.get(b).stream().mapToInt(Integer::intValue).toArray();
}
return result;
}vector<vector<int>> buildChains(vector<int>& keys, int buckets) {
// [1] An empty chain for every bucket.
vector<vector<int>> chains(buckets);
for (int key : keys) {
// [2] The bucket of a key is its remainder after dividing by the bucket count.
int bucket = key % buckets;
// [3] Search only that chain: a key already in it is stored once, so skip it.
bool found = false;
for (int stored : chains[bucket]) {
if (stored == key) {
found = true;
}
}
if (found) {
continue;
}
// [4] A new key joins the end of its chain.
chains[bucket].push_back(key);
}
// [5] Report the chains.
return chains;
}function buildChains(keys, buckets) {
// [1] An empty chain for every bucket.
const chains = Array.from({ length: buckets }, () => []);
for (const key of keys) {
// [2] The bucket of a key is its remainder after dividing by the bucket count.
const bucket = key % buckets;
// [3] Search only that chain: a key already in it is stored once, so skip it.
let found = false;
for (const stored of chains[bucket]) {
if (stored === key) {
found = true;
}
}
if (found) {
continue;
}
// [4] A new key joins the end of its chain.
chains[bucket].push(key);
}
// [5] Report the chains.
return chains;
}Rebuild the template: put its lines back in order. Loads in your browser.
Linear probing: on a collision, step to the next slot, and wrap round from the last slot to slot zero.
Here each slot holds at most one key. A key that finds its slot taken moves on to the next slot, and wraps around to slot 0 after the last one. This template assumes the table has room for every distinct key, so an empty slot always exists. Empty slots are marked -1, which is why keys must not be negative here.
def probe_slots(keys, size):
# [1] A table of empty slots, marked -1.
table = [-1] * size
for key in keys:
# [2] Start at the slot the key hashes to.
slot = key % size
# [3] Walk forward, wrapping around, while the slot holds a different key.
while table[slot] != -1 and table[slot] != key:
slot = (slot + 1) % size
# [4] The slot already holds this key: it is stored once, so there is nothing to add.
if table[slot] == key:
continue
# [5] An empty slot: the key goes here.
table[slot] = key
# [6] Report the table.
return tablepublic int[] probeSlots(int[] keys, int size) {
// [1] A table of empty slots, marked -1.
int[] table = new int[size];
java.util.Arrays.fill(table, -1);
for (int key : keys) {
// [2] Start at the slot the key hashes to.
int slot = key % size;
// [3] Walk forward, wrapping around, while the slot holds a different key.
while (table[slot] != -1 && table[slot] != key) {
slot = (slot + 1) % size;
}
// [4] The slot already holds this key: it is stored once, so there is nothing to add.
if (table[slot] == key) {
continue;
}
// [5] An empty slot: the key goes here.
table[slot] = key;
}
// [6] Report the table.
return table;
}vector<int> probeSlots(vector<int>& keys, int size) {
// [1] A table of empty slots, marked -1.
vector<int> table(size, -1);
for (int key : keys) {
// [2] Start at the slot the key hashes to.
int slot = key % size;
// [3] Walk forward, wrapping around, while the slot holds a different key.
while (table[slot] != -1 && table[slot] != key) {
slot = (slot + 1) % size;
}
// [4] The slot already holds this key: it is stored once, so there is nothing to add.
if (table[slot] == key) {
continue;
}
// [5] An empty slot: the key goes here.
table[slot] = key;
}
// [6] Report the table.
return table;
}function probeSlots(keys, size) {
// [1] A table of empty slots, marked -1.
const table = new Array(size).fill(-1);
for (const key of keys) {
// [2] Start at the slot the key hashes to.
let slot = key % size;
// [3] Walk forward, wrapping around, while the slot holds a different key.
while (table[slot] !== -1 && table[slot] !== key) {
slot = (slot + 1) % size;
}
// [4] The slot already holds this key: it is stored once, so there is nothing to add.
if (table[slot] === key) {
continue;
}
// [5] An empty slot: the key goes here.
table[slot] = key;
}
// [6] Report the table.
return table;
}Exercise · Put it in order: Look a key up in the table. Arrange the lines into a lookup for a table built with linear probing. It returns true when the key is stored. The table always has at least one empty slot, marked -1.
def contains_key(table, key):
slot = key % len(table)
while table[slot] != -1:
if table[slot] == key:
return True
slot = (slot + 1) % len(table)
return False
slot = slot + 1A search engine keeps the numeric ids of recent search terms in a chained table with 5 buckets. The terms arrive as [30, 25, 12, 7, 2, 12]. Where does each id go?
This is Template 1 with buckets = 5.
| Key | Bucket | Already in the chain | What happens | Chains after |
|---|---|---|---|---|
| 30 | 0 | no | joins bucket 0 | 0: [30] |
| 25 | 0 | no | joins bucket 0, behind 30 | 0: [30, 25] |
| 12 | 2 | no | joins bucket 2 | 2: [12] |
| 7 | 2 | no | joins bucket 2, behind 12 | 2: [12, 7] |
| 2 | 2 | no | joins bucket 2, behind 7 | 2: [12, 7, 2] |
| 12 | 2 | yes | skipped | no change |
The result is [[30, 25], [], [12, 7, 2], [], []]. Buckets 1, 3 and 4 are empty, and bucket 2 holds three keys. A lookup for 2 compares with 12, 7 and 2, and a lookup for 8 looks in empty bucket 3 and compares with nothing.
Keep the table roomy: when the load factor passes three quarters, double the buckets and move every key once.
Exercise · Find the bug: The id that is stored twice. This table skips a payment id it has already stored, but the same id appears twice in the table on some inputs. Which line is wrong?
def probe_slots(keys, size):
table = [-1] * size
for key in keys:
slot = key % size
while table[slot] != -1:
slot = (slot + 1) % size
if table[slot] == -1:
table[slot] = key
return tableReal production data brings edge cases.
Before any payment arrives, the table is empty: keys = []. The chain template returns one empty chain for each bucket, and the probe template returns a table of -1 values.
A search in an empty bucket compares nothing and answers "new".
When all the ids are multiples of the bucket count, such as [5, 10, 15] with 5 buckets, they all share bucket 0. The chain holds [5, 10, 15], and the other buckets are empty.
The table still works, but a lookup now walks a chain of 3, and with a million keys it would walk a million. This is the worst case of a hash table.
For [7, 7] with one bucket, the answer is [[7]]. The second 7 finds itself in the chain and is skipped. A hash table keeps one copy of each key.
In a table of 5 slots, the keys [4, 9, 14] all hash to slot 4. The first goes to slot 4, the second wraps to slot 0, and the third goes to slot 1. The answer is [9, 14, -1, -1, 4].
A walk that did not wrap would run past the end of the array.
Exercise · Break it: Find the id this lookup misses. This lookup builds chains for the stored ids, then checks only the first id in the chain of the query. Find ids, buckets and a query where it gives the wrong answer. Use ids of zero or more and at least 1 bucket.
def is_stored(ids, buckets, query):
chains = [[] for _ in range(buckets)]
for key in ids:
if key not in chains[key % buckets]:
chains[key % buckets].append(key)
chain = chains[query % buckets]
return len(chain) > 0 and chain[0] == queryThis version computes key % buckets for every key, including negative ones.
Counterexample: key = -7, buckets = 5. In Python, -7 % 5 is 3. In Java, C++ and JavaScript, -7 % 5 is −2, and an array index of −2 fails or reads the wrong slot.
When keys can be negative, fix the remainder: ((key % buckets) + buckets) % buckets. Templates here use keys that are zero or larger.
This version moves on with slot += 1, and never returns to slot 0.
Counterexample: keys = [4, 9, 14] with 5 slots. Key 4 takes slot 4. Key 9 hashes to slot 4, which is taken, so the bug moves to slot 5 and fails, because the table has slots 0 to 4. The correct answer is [9, 14, -1, -1, 4].
Use (slot + 1) % size so the walk returns to slot 0.
A tempting lookup checks only the key's own slot. If the slot holds a different key, it answers "not stored".
Counterexample: the table [15, -1, 10, 3, 18, 26, 11, 2] from the dry run. Key 18 hashes to slot 2, which holds 10, so the bug answers "not stored". Key 18 is stored in slot 4.
A search must follow the same walk as a store: move on, with wrap-around, until it finds the key or an empty slot.
The classic probing bug: a search that checks only the key's own slot says 'not stored' for a key that sits further on.
Your team lead asks for the smallest stored payment id above 1,000, or for all ids between two values. A hash table spreads keys over buckets with no regard to their size, so neighbouring ids are far apart in the table.
You would have to read every bucket. For questions about order, keep a sorted array and use binary search, or a balanced tree. A hash table is for "is this key here" and "what is the value of this key".
Your team lead brings four product changes. Each one uses the same idea: the key chooses the bucket.
A payments app wants to know if a batch of ids contains a repeat. For [14, 9, 21, 14], the answer is yes. Store each id in a set as it arrives, and stop at the first id that is already there. That is O(n) instead of comparing every pair (LeetCode 217: Contains Duplicate).
An interviewer asks you to implement add, remove and contains without a library set. Use an array of buckets, each holding a small list, and compute the bucket with a remainder. Keep the load factor below about 0.75 by doubling (LeetCode 705: Design HashSet).
A chat app stores a profile for every session token. Each bucket entry holds the key and its value. A lookup finds the key in the chain and returns the value, and a repeated key replaces the value (LeetCode 706: Design HashMap).
A payments app spreads payment records over shards by id mod shards and wants the shard with the most distinct ids. For ids [14, 9, 14, 21, 6, 9, 30] and 5 shards, shards 1 and 4 hold two ids each, and 1 wins the tie. It is the first practice problem.
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate why a hash table lookup looks in only one bucket. Then explain what happens when two keys land in the same bucket. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have built it.
A hash function turns the key into a bucket number, so a lookup goes straight to one bucket.
Two keys can share a bucket. Chaining keeps them in a chain, and probing moves to the next free slot.
If the table gets too full, it doubles. That is costly once, but cheap on average: amortised constant time.
A hash table answers "have I seen this key?" in constant time on average, where a list scan costs O(n).
It keeps an array of buckets. A hash function turns a key into a bucket number, and I store or search only in that bucket. For an integer key, the hash can be the remainder after dividing by the bucket count.
Two keys can land in the same bucket. That is a collision. With chaining, each bucket holds a short list. With linear probing, a key moves on to the next free slot, wrapping around at the end.
I keep the load factor, keys divided by buckets, below about three quarters. When it passes that, the table doubles and moves every key once. That is amortised O(1) for each insert.
In the worst case, when every key lands in one bucket, a lookup is O(n). So I want a hash that spreads keys evenly.
Checkpoint · Buckets and hashes
Q1/4 Why does a hash table find a key faster than a list scan?
Answer: B
The hash points to one bucket. A list scan has no such pointer, so it must read the keys one by one.
Q2/4 Which request is a job for a hash table?
Answer: C
A hash table answers "is this key here?" in constant time on average. It keeps no order, so the other three questions need a sorted structure.
Q3/4 A table has 5 buckets, and the hash is key mod 5. Which bucket holds key 23?
Answer: B
23 divided by 5 leaves remainder 3. Buckets are numbered from 0 to 4, so there is no bucket 5.
Q4/4 Keys 14 and 9 both go to bucket 4 of a 5-bucket table. What is this called?
Answer: B
Two different keys with the same bucket are a collision. They are normal, because there are far more possible keys than buckets.
Checkpoint · Chains, probes and growth
Q1/6 With separate chaining, key 19 is searched in a 5-bucket table that holds the chain [14, 9, 4] in bucket 4. What does the search compare?
Answer: B
The search computes bucket 4 and walks only that chain. It stops at the end of the chain, so 19 is reported as absent after 3 comparisons.
Q2/6 A probe table with 5 slots holds key 4 in slot 4. Key 9 hashes to slot 4. Where does it go?
Answer: B
The walk moves to the next slot and wraps to 0 after the last one. A walk that goes to slot 5 runs past the end of the array.
Q3/6 The load factor of a table is 6 keys in 8 buckets. What is it, and what does a table do when it passes its limit?
Answer: B
The load factor is keys divided by buckets: 6 / 8 is 0.75. Past its limit the table grows, and each key moves to a bucket of the new table.
Q4/6 One insert makes the table double and move 1,000 keys. Why is an insert still called amortised O(1)?
Answer: C
The table doubles only after the load passes its limit. Spread over all inserts, the moves add up to a constant for each insert.
Q5/6 A hash function sends every key to bucket 0. What happens to a lookup?
Answer: B
The table still gives right answers, but with every key in one chain, a lookup is as slow as a list scan.
Q6/6 In Java, -7 % 5 is -2. What goes wrong if a table uses it as a bucket number?
Answer: B
A negative index is out of range. Use ((key % buckets) + buckets) % buckets for keys that can be negative.
Ten questions on this lesson. Pass with 80% or more, and solve the checkpoint's two mixed problems, to open the gate to the next stretch on the Academy map. The two problems are "How long are the chains?" and "Lookup cost in a chained table".
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | The busiest payment shard | Pay | Easy | A set to count each id once, and the remainder as the hash |
| 2 | Growing a session table | Chat | Medium | The load factor, doubling, and the moves it costs |
| 3 | Order codes that land in the same bucket | Shop | Medium | Hashing a string, and counting collisions by bucket |
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.