Explain buckets, collisions, load factor and resizing.
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.
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;
}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;
}This version computes key % buckets for every key, including negative ones.
This version moves on with slot += 1, and never 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".
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.
systemdesignmastery.dev/dsa/cheatsheets/hash-table-internals