Insert 12, 18, 13, 2, 3, 23, 5, 15 into an empty table of size 10 using h(k) = k mod 10 and linear probing. Show the final table.
Hashing computes a key's table position with a hash function, giving O(1) average search, insert and delete. Collisions — two keys at one slot — are resolved by separate chaining or by open addressing with linear probing, quadratic probing or double hashing.
Linear search costs O(n), binary search and balanced trees O(log n). Hashing aims for O(1) on average by computing where a key lives instead of searching for it. If keys were small integers 0 … U − 1, a direct-address table would do: store key k in slot k. But real keys come from a huge universe — 10-digit phone numbers would need 10¹⁰ slots for a few thousand entries.
A hash table has only m slots (also called buckets), and a hash function h maps every key to a slot number h(k) ∈ {0, 1, …, m − 1}, its home address. Because the universe is far larger than m, two different keys must sometimes map to the same slot — a collision, and such keys are called synonyms. Collisions are unavoidable (pigeonhole principle) and arrive sooner than intuition suggests: with just 23 people the chance that two share a birthday exceeds 50%.
| Term | Meaning |
|---|---|
| Hash function h(k) | maps a key to a slot index 0 … m − 1 |
| Home address / bucket | the slot h(k) where the key ‘should’ go |
| Collision, synonyms | h(k₁) = h(k₂) for k₁ ≠ k₂; such keys are synonyms |
| Load factor α | n/m — keys stored per slot; the main driver of performance |
| Probe | one inspection of a slot while searching or inserting |
| Open hashing | separate chaining — keys live outside the table array, in lists |
| Closed hashing | open addressing — every key lives inside the table array |
A good hash function is fast to compute, deterministic, uses every part of the key, and spreads keys as evenly as possible over the slots (the ideal, called simple uniform hashing, is that every key is equally likely to land in any slot). The standard methods for integer keys are:
| Method | Rule | Example |
|---|---|---|
| Division | h(k) = k mod m | m = 13: 1234 mod 13 = 12 |
| Multiplication (Knuth) | h(k) = ⌊m · (k·A mod 1)⌋, with A ≈ (√5 − 1)/2 = 0.6180339887 | m = 100, k = 123: 123A = 76.018…, fractional part 0.018…, h = 1 |
| Mid-square | square the key and take r digits from the middle | 3205² = 10272025 → middle two digits 72 |
| Folding (shift) | cut the key into equal parts and add them; drop the carry | 123|456|789 → 123 + 456 + 789 = 1368 → 368 (m = 1000) |
| Folding (boundary) | reverse the outer parts before adding | 321 + 456 + 987 = 1764 → 764 |
| Digit extraction | use selected digits of the key | digits 3, 5 and 7 of a 9-digit ID |
#include <stdio.h>
#include <math.h>
int divisionHash(int k, int m) { return k % m; }
int midSquare(long k, int digits) { /* middle 'digits' digits of k*k */
long sq = k * k;
int len = 0;
for (long t = sq; t > 0; t /= 10) len++;
for (int i = 0; i < (len - digits) / 2; i++) sq /= 10; /* drop right part */
long mod = 1;
for (int i = 0; i < digits; i++) mod *= 10;
return (int)(sq % mod);
}
int foldShift(long k, int partDigits, int m) { /* split into parts and add */
long p = 1, sum = 0;
for (int i = 0; i < partDigits; i++) p *= 10;
for (; k > 0; k /= p) sum += k % p;
return (int)(sum % m);
}
int multiplication(int k, int m) { /* A = (sqrt(5) - 1) / 2 */
double A = (sqrt(5.0) - 1) / 2;
double frac = k * A - floor(k * A);
return (int)floor(m * frac);
}
int main(void) {
printf("%d %d %d %d\n", divisionHash(1234, 13), midSquare(3205, 2),
foldShift(123456789, 3, 1000), multiplication(123, 100)); /* 12 72 368 1 */
return 0;
}String keys are first turned into numbers, usually with a polynomial evaluated by Horner's rule: h = (s₀·b^(L−1) + s₁·b^(L−2) + … + s_(L−1)) mod m. Java's String.hashCode() uses b = 31. Weak functions such as ‘sum of the character codes’ make anagrams (‘listen’, ‘silent’) collide.
In separate chaining each slot holds a pointer to a linked list (a chain) of all keys that hash there. Insertion adds the key at the head of its chain in O(1); search and deletion walk only that chain. Because the chains live outside the array, the table never fills up and α may exceed 1. With uniform hashing the average chain length is α, so an unsuccessful search examines about α nodes (Θ(1 + α) time including the hash computation) and a successful one about 1 + α/2. The worst case — every key in one chain — is O(n).
#include <stdio.h>
#include <stdlib.h>
#define M 7
struct Node { int key; struct Node *next; };
struct Node *table[M]; /* all NULL: empty chains */
int h(int k) { return k % M; }
void insert(int k) { /* O(1): add at the head of the chain */
struct Node *p = malloc(sizeof *p);
if (!p) exit(1);
p->key = k;
p->next = table[h(k)];
table[h(k)] = p;
}
struct Node *search(int k) { /* O(1 + alpha) on average */
for (struct Node *p = table[h(k)]; p != NULL; p = p->next)
if (p->key == k) return p;
return NULL;
}
int main(void) {
int keys[] = {76, 93, 40, 47, 10, 55};
for (int i = 0; i < 6; i++) insert(keys[i]);
for (int s = 0; s < M; s++) {
printf("%d:", s);
for (struct Node *p = table[s]; p; p = p->next) printf(" %d", p->key);
printf("\n"); /* 5: 47 40 and 6: 55 76 */
}
printf("47 %s\n", search(47) ? "found" : "missing");
return 0;
}Variants: Java 8's HashMap turns a chain into a red–black tree once it grows past 8 entries (in tables of at least 64 buckets), bounding the worst case at O(log n); coalesced chaining stores the chains inside the table array itself.
In open addressing (closed hashing) every key is stored in the table array. On a collision, the key follows a probe sequence h(k, 0), h(k, 1), h(k, 2), … until an empty slot appears. A search follows exactly the same sequence and stops when it finds the key (success) or a never-used empty slot (failure). Since keys cannot leave the array, α ≤ 1.
Linear probing simply tries the next slot. It is cache-friendly, but occupied slots coalesce into long runs: any key hashing anywhere into a run lands at its end and lengthens it, so a slot just after a run of L occupied slots is hit with probability (L + 1)/m instead of 1/m. This snowballing is primary clustering.
Quadratic probing jumps 1, 4, 9, 16, … slots away, breaking up runs. Keys with the same home slot still follow the same sequence — secondary clustering, which is milder. It may also fail to reach every slot: with m = 8 the offsets i² mod 8 are only 0, 1 and 4. If m is prime and the table is at most half full, the first ⌈m/2⌉ probes are all distinct, so an empty slot is guaranteed.
Double hashing makes the step size itself depend on the key, so even synonyms (same home slot) follow different paths. With m slots it generates about m² distinct probe sequences instead of m, and behaves almost like ideal uniform hashing. The second function must never return 0 — the sequence would then stay on the home slot forever — and must be coprime to m so that every slot can be reached (automatic when m is prime).
| Scheme | Step after the i-th collision | Clustering | Distinct probe sequences | Reaches every slot? |
|---|---|---|---|---|
| Linear | +1 each time | primary (long runs) | m | yes |
| Quadratic | offsets 1, 4, 9, … | secondary (same home ⇒ same path) | m | only guaranteed if m is prime and α ≤ ½ |
| Double hashing | +h₂(k) each time | practically none | ≈ m² | yes, if h₂(k) is coprime to m |
Use h(k) = k mod 7. The home slots are 76 → 6, 93 → 2, 40 → 5, 47 → 5, 10 → 3 and 55 → 6, so 47 collides with 40 and 55 collides with 76. For double hashing take h₂(k) = 5 − (k mod 5), which is always between 1 and 5.
| Key | Home | Linear (h + i) | Quadratic (h + i²) | Double (h₁ + i·h₂) |
|---|---|---|---|---|
| 76 | 6 | 6 | 6 | 6 |
| 93 | 2 | 2 | 2 | 2 |
| 40 | 5 | 5 | 5 | 5 |
| 47 | 5 | 5 → 6 → 0 | 5 → 6 → 2 → 0 (offsets 0, 1, 4, 9) | h₂ = 3: 5 → 1 |
| 10 | 3 | 3 | 3 | 3 |
| 55 | 6 | 6 → 0 → 1 | 6 → 0 → 3 → 1 (offsets 0, 1, 4, 9) | h₂ = 5: 6 → 4 |
| Total probes | 10 | 12 | 8 |
| Slot | Linear probing | Quadratic probing | Double hashing | Chaining (head insertion) |
|---|---|---|---|---|
| 0 | 47 | 47 | — | — |
| 1 | 55 | 55 | 47 | — |
| 2 | 93 | 93 | 93 | 93 |
| 3 | 10 | 10 | 10 | 10 |
| 4 | — | — | 55 | — |
| 5 | 40 | 40 | 40 | 47 → 40 |
| 6 | 76 | 76 | 76 | 55 → 76 |
#include <stdio.h>
#define M 7
int T[M];
int linear(int k, int i) { return (k % M + i) % M; }
int quadratic(int k, int i) { return (k % M + i * i) % M; }
int doubleHash(int k, int i) { int h2 = 5 - (k % 5); return (k % M + i * h2) % M; } /* h2 >= 1 */
void build(const char *name, int (*probe)(int, int), const int keys[], int n) {
int probes = 0;
for (int s = 0; s < M; s++) T[s] = -1; /* -1 marks an empty slot */
for (int j = 0; j < n; j++)
for (int i = 0; i < M; i++) {
int s = probe(keys[j], i);
probes++;
if (T[s] == -1) { T[s] = keys[j]; break; }
}
printf("%-10s", name);
for (int s = 0; s < M; s++) {
if (T[s] == -1) printf(" -");
else printf(" %2d", T[s]);
}
printf(" (%d probes)\n", probes);
}
int main(void) {
int keys[] = {76, 93, 40, 47, 10, 55};
build("linear", linear, keys, 6); /* 47 55 93 10 - 40 76 (10 probes) */
build("quadratic", quadratic, keys, 6); /* 47 55 93 10 - 40 76 (12 probes) */
build("double", doubleHash, keys, 6); /* - 47 93 10 55 40 76 (8 probes) */
return 0;
}Performance depends almost entirely on the load factor α = n/m, not on n itself — a table with a million keys and α = 0.5 is as fast as one with ten keys and α = 0.5. The classic expected-cost formulas (assuming a good hash function) are:
| α | Chaining: hit / miss | Uniform open addressing: hit / miss | Linear probing: hit / miss |
|---|---|---|---|
| 0.50 | 1.25 / 0.50 | 1.39 / 2.00 | 1.50 / 2.50 |
| 0.75 | 1.38 / 0.75 | 1.85 / 4.00 | 2.50 / 8.50 |
| 0.90 | 1.45 / 0.90 | 2.56 / 10.00 | 5.50 / 50.50 |
Open addressing degrades sharply as α approaches 1 — linear probing most of all — so practical tables keep α ≤ 0.5 for quadratic probing and around 0.7 for linear probing, while chaining is comfortable near α = 1 (Java's HashMap, a chained table, resizes at 0.75).
Rehashing. When α crosses the threshold, allocate a new table about twice as large (rounded up to a prime), recompute every key's hash with the new m, and insert all keys again. One rehash costs O(n), but because the size doubles each time the cost is O(1) amortised per insertion — the same argument as for dynamic arrays. Example: m = 13 with n = 10 keys has α ≈ 0.77; rehashing into m = 29 gives α ≈ 0.34. Every home slot changes: key 40 moves from 40 mod 13 = 1 to 40 mod 29 = 11.
In chaining, deleting a key is an ordinary linked-list unlink. In open addressing it is subtle. A search stops at the first EMPTY slot, so emptying a slot can cut a probe chain in two. In the linear-probing table above, 55 lives in slot 1 because slots 6 and 0 were busy when it arrived. If 47 is deleted by emptying slot 0, a later search for 55 probes 6, then finds slot 0 EMPTY and wrongly reports that 55 is absent.
The fix is lazy deletion: mark the slot DELETED — a tombstone. Searches treat a tombstone as occupied and keep probing; insertions may reuse it (a careful insert first checks that the key is not already present further along the sequence). Tombstones lengthen probe sequences, so a table that has seen many deletions is periodically rebuilt, which clears them.
#include <stdio.h>
#define M 7
#define EMPTY -1
#define DELETED -2 /* tombstone */
int T[M];
void init(void) { for (int i = 0; i < M; i++) T[i] = EMPTY; }
int probe(int k, int i) { return (k % M + i) % M; }
int insert(int k) { /* returns the slot, or -1 if full */
for (int i = 0; i < M; i++) {
int s = probe(k, i);
if (T[s] == EMPTY || T[s] == DELETED) { T[s] = k; return s; }
}
return -1;
}
int search(int k) { /* returns the slot, or -1 */
for (int i = 0; i < M; i++) {
int s = probe(k, i);
if (T[s] == EMPTY) return -1; /* only a never-used slot ends a search */
if (T[s] == k) return s; /* tombstones are skipped over */
}
return -1;
}
void erase(int k) { int s = search(k); if (s != -1) T[s] = DELETED; }
int main(void) {
int keys[] = {76, 93, 40, 47, 10, 55};
init();
for (int i = 0; i < 6; i++) printf("%d->%d ", keys[i], insert(keys[i]));
printf("\n"); /* 76->6 93->2 40->5 47->0 10->3 55->1 */
erase(47); /* slot 0 becomes a tombstone */
printf("search 55 -> slot %d\n", search(55)); /* still found in slot 1 */
return 0;
}When the set of keys is fixed in advance — the reserved words of a programming language, say — we can search for a perfect hash function, one with no collisions at all for that set; a minimal perfect hash function maps n keys onto exactly n slots. Tools such as GNU gperf generate them for compiler keyword tables. The FKS scheme (Fredman, Komlós and Szemerédi, 1984) achieves perfect hashing for any static set with two levels: n keys are hashed into n buckets, and a bucket holding nⱼ keys gets its own collision-free secondary table of size nⱼ². Lookup is O(1) in the worst case and the expected total space is O(n).
Universal hashing (Carter and Wegman, 1979) defends against adversarial inputs: instead of one fixed function, choose h at random from a family such that any two distinct keys collide with probability at most 1/m — for example h(k) = ((a·k + b) mod p) mod m with a prime p and random a ≠ 0, b. No input can then be bad for every choice of h.
dict, Java HashMap, C++ unordered_map; duplicate detection and frequency counting.| Structure | Search (average) | Search (worst) | Sorted order / range queries |
|---|---|---|---|
| Hash table | O(1) | O(n) | not supported |
| Balanced BST (AVL, red–black) | O(log n) | O(log n) | yes — inorder traversal |
| Sorted array | O(log n) binary search | O(log n) | yes, but insertion is O(n) |
Try the problem first, then reveal the working one step at a time.
Insert 12, 18, 13, 2, 3, 23, 5, 15 into an empty table of size 10 using h(k) = k mod 10 and linear probing. Show the final table.
Insert 20, 34, 45, 70, 56, 122 into a table of size 11 with h₁(k) = k mod 11 and h₂(k) = 7 − (k mod 7), probing h₁ + i·h₂ (mod 11).
A table has α = 0.8. Estimate the expected probes for successful and unsuccessful searches with (a) linear probing, (b) ideal uniform open addressing, (c) separate chaining.
Compute (a) the mid-square address (middle two digits) of key 4567, (b) the shift-folding and boundary-folding addresses of 987654321 using 3-digit parts and m = 1000.
Insert 22, 33, 44, 55 into a table of size 11 with h(k) = k mod 11, first with linear probing and then with quadratic probing (h + i²). What kind of clustering does each show?
In the table of the first worked example (12, 18, 13, 2, 3, 23, 5, 15 with linear probing, m = 10), key 3 in slot 5 is deleted. A search for 23 follows. What happens if slot 5 is set to EMPTY, and what if it is marked DELETED?
A table of size 13 holds 10 keys. Compute α, and the new α after rehashing into the next prime at least twice the size. Where does key 40 go before and after the rehash (division method)?
A chained hash table has 500 slots and stores 2,000 keys. How many keys does an unsuccessful search examine on average, and about how many comparisons does a successful search make?
12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.