Hash tables with separate chaining
With separate chaining, each bucket holds a small list of the keys that hash there. Insert, search and delete walk one short chain.
Before you start: Hash functions: from key to bucket index.
The idea
A coat check hands you a numbered ticket. The number tells staff which hook to open, with no searching.
A hash table does the same for keys. A hash function turns a key into a bucket number, so the lookup jumps straight to one bucket.
Intuition
Key 12 goes to bucket 12 mod 5 = 2. The table has 5 buckets, numbered 0 to 4.
7 mod 5 is also 2. Both keys wait in chain 2, in arrival order.
Many keys share few buckets, so collisions are normal. Chaining keeps colliding keys in a short list inside the bucket.
Complexity
A search walks about 1 + n ÷ m keys. Resizing keeps n ÷ m below a constant, so the cost stays flat.
With m fixed, the chain length grows with n and each operation drifts toward O(n). With m growing along with n, the average operation is O(1).
Pitfalls
All keys are multiples of 5, so key mod 5 is always 0. One chain holds everything, and each operation takes O(n).
Variations
Open addressing stores keys in the array itself. It has no chains and probes nearby slots on a collision.
Code
Pseudocode
put(key)
i ← hash(key) mod m
if key not in bucket[i]: append key to bucket[i]
get(key)
i ← hash(key) mod m
for each k in bucket[i]
if k = key: return found
return not found
remove(key)
i ← hash(key) mod m
for each k in bucket[i]
if k = key: unlink k; return
Python
def put(table, key):
i = hash(key) % len(table)
if key not in table[i]:
table[i].append(key)
def get(table, key):
i = hash(key) % len(table)
for k in table[i]:
if k == key:
return True
return False
def remove(table, key):
i = hash(key) % len(table)
for k in table[i]:
if k == key:
table[i].remove(k)
return
JavaScript
function put(table, key) {
const i = hash(key) % table.length;
if (!table[i].includes(key)) table[i].push(key);
}
function get(table, key) {
const i = hash(key) % table.length;
for (const k of table[i]) {
if (k === key) return true;
}
return false;
}
function remove(table, key) {
const i = hash(key) % table.length;
for (let j = 0; j < table[i].length; j++) {
if (table[i][j] === key) { table[i].splice(j, 1); return; }
}
}
Cost at a glance
| Access | n/a |
|---|---|
| Search | O(1) / O(n) |
| Insert | O(1) / O(n) |
| Delete | O(1) / O(n) |
| Space | O(n) |
Practice problems (6)
Insert a sequence Warm-up
A table has 5 buckets and uses key mod 5 as its hash. New keys join the end of their chain. Insert 12, 7, 3, 22, 9 in this order and answer each question before the step plays.
Average chain length Warm-up
A table has 4 buckets and uses key mod 4. Insert 5, 9, 2, 6, 11, 14, then read the load factor and the chains.
Implement get and put Standard
Build a hash table with separate chaining and run a list of commands on it. Use 8 buckets, each a list of [key, value] pairs, and hash a key with key mod 8. Do not use a built-in map or dictionary.
put K V stores value V under key K. If K already exists, replace its value. get K returns the value of K, or "-1" if K is missing.
Return the results of the get commands in order. put produces no output.
Count collisions Standard
A hash table has size buckets and hashes a key with key mod size. Insert the distinct keys in keys in order. A collision happens when a key lands in a bucket that already holds at least one key.
Return the number of collisions.
Longest chain Standard
A hash table has size buckets and hashes a key with key mod size. Insert all distinct keys in keys.
Return the length of the longest chain, which is the worst case for one search. Return 0 when there are no keys.
Implement remove and iteration Challenge
Extend the chained hash table with deletion and iteration. Use 8 buckets of [key, value] pairs and hash with key mod 8. New keys go to the end of their chain. Do not use a built-in map.
Commands: put K V stores or replaces a value and prints nothing. get K prints the value, or "-1" if missing. remove K unlinks K and prints "true", or "false" if missing. keys prints every key separated by single spaces, in bucket order 0 to 7 and in chain order inside each bucket (empty text when the table is empty).
Return the printed lines in order.
Related topics
Next on the path: Open addressing: linear, quadratic probing, double hashing