Patterns: hash tables
This hash table review covers working out the average search length (ASL) by hand for linear probing and chaining, two sum, which looks up target - x before inserting x to turn O(n²) into O(n), and counting and deduplicating with an array or a hash table.
Hash tables show two faces in exams and interviews. Written exams test working by hand: given a hash function and a collision method, fill in the table and compute the average search length, ASL, and it comes up every year. Interviews test using one: plenty of O(n²) problems become O(n) once a hash table remembers "what I've seen". Three patterns in this lesson: the first is calculation, the other two are use.
Pattern one: computing the ASL
A classic exam question: keys (7, 8, 30, 11, 18, 9, 14), hash function H(k) = (3k) % 7, table length 10 (indexes 0 to 9), linear probing. First insert them one by one in order:
Successful search ASL: finding each key takes as many comparisons as inserting it took probes; add them up and divide by the number of keys n:
| Key | 7 | 8 | 30 | 11 | 18 | 9 | 14 |
|---|---|---|---|---|---|---|---|
| Comparisons | 1 | 1 | 1 | 1 | 3 | 3 | 2 |
ASL success = (1 + 1 + 1 + 1 + 3 + 3 + 2) / 7 = 12/7.
Failed search ASL: a key that isn't in the table can only have H equal to one of the 7 values 0 to 6 (not the table length 10!). From each starting point, count forward up to the empty slot, and the empty slot counts too:
| H(k) | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| Compared up to the empty slot | 0 1 2 | 1 2 | 2 | 3 4 | 4 | 5 6 7 8 9 | 6 7 8 9 |
| Comparisons | 3 | 2 | 1 | 2 | 1 | 5 | 4 |
ASL failure = (3 + 2 + 1 + 2 + 1 + 5 + 4) / 7 = 18/7. The denominators are where people slip: success divides by the number of keys, failure by how many values the hash function can produce (here the modulus, 7).
The same keys with chaining and a table of length 7:
With chaining, ASL success = 10/7 and ASL failure = 7/7 = 1 (the usual exam convention: comparisons against a null pointer don't count). Checking it with a program:
1#include <stdio.h>2 3#define M 10 // table length4#define P 7 // H(k) = 3k % 75 6int t[M];7int H(int k) { return 3 * k % P; }8 9int main(void) {10 int keys[] = {7, 8, 30, 11, 18, 9, 14}, n = 7;11 for (int i = 0; i < M; i++) t[i] = -1;12 int ok = 0;13 for (int j = 0; j < n; j++) {14 for (int i = 0; ; i++) {15 int p = (H(keys[j]) + i) % M;16 if (t[p] == -1) {17 t[p] = keys[j];18 ok += i + 1; // i + 1 probes19 printf("%d goes in %d, %d comparisons\n", keys[j], p, i + 1);20 break;21 }22 }23 }24 int fail = 0;25 for (int h = 0; h < P; h++) { // failure: the 7 values H can take26 int c = 1;27 for (int p = h; t[p] != -1; p = (p + 1) % M)28 c++; // a key here means one more comparison; the empty slot counts29 fail += c;30 }31 printf("linear probing: success %d/%d, failure %d/%d\n", ok, n, fail, P);32 33 int len[P] = {0}, ok2 = 0, fail2 = 0;34 for (int j = 0; j < n; j++) {35 int s = H(keys[j]);36 len[s]++;37 ok2 += len[s]; // the k-th on a chain takes k comparisons (same total head or tail)38 }39 for (int s = 0; s < P; s++) fail2 += len[s];40 printf("chaining: success %d/%d, failure %d/%d\n", ok2, n, fail2, P);41 return 0;42}
7 goes in 0, 1 comparisons 8 goes in 3, 1 comparisons 30 goes in 6, 1 comparisons 11 goes in 5, 1 comparisons 18 goes in 7, 3 comparisons 9 goes in 8, 3 comparisons 14 goes in 1, 2 comparisons linear probing: success 12/7, failure 18/7 chaining: success 10/7, failure 7/7
In exams: always draw the table first and mark each key's comparison count beside it. The usual traps: dividing the failure sum by the table length 10; forgetting the comparison with the empty slot on a failed search; counting NULL as a comparison with chaining (follow the question's convention; if it says nothing, don't count it). The load factor α = 7 / 10 = 0.7 is often asked alongside.
Linear probing, table size 8 (indices 0–7), H(k) = k % 7, inserting 7, 14 and 21 in turn. What is the ASL for a failed search?
Pattern two: two sum, checking as you go
Given an array and a target, find two numbers that add up to the target and return their indexes. Brute force is two nested loops, O(n²). Ask the question differently: on reaching x, ask "has target − x appeared before?" If so, you're done; if not, record x in a hash table. One pass, and each lookup and insert is O(1).
Look up first, then insert, never the other way round: insert x first and, when target = 2x, x pairs with itself. Comparing the two versions for real:
1#include <stdio.h>2 3#define N 3004#define M 607 // a prime above 2N: α stays under 0.55 6int val[M], idx[M], used[M];7long cmp = 0;8 9int find(int x) { // linear probing for x: returns its index, or -1 if absent10 for (int p = x % M; ; p = (p + 1) % M) {11 cmp++; // each slot looked at counts once, the empty one too12 if (!used[p]) return -1;13 if (val[p] == x) return idx[p];14 }15}16 17void put(int x, int i) {18 int p = x % M;19 while (used[p]) p = (p + 1) % M;20 used[p] = 1; val[p] = x; idx[p] = i;21}22 23int main(void) {24 int a[N];25 for (int i = 0; i < N; i++) a[i] = 3 * i + 1;26 int target = a[N - 2] + a[N - 1]; // the answer is the last two: the worst case27 28 long brute = 0;29 int bi = -1, bj = -1;30 for (int i = 0; i < N && bi < 0; i++)31 for (int j = i + 1; j < N; j++) {32 brute++;33 if (a[i] + a[j] == target) { bi = i; bj = j; break; }34 }35 printf("nested loops: %d %d, %ld comparisons\n", bi, bj, brute);36 37 int hi = -1, hj = -1;38 for (int j = 0; j < N; j++) {39 int need = target - a[j];40 int i = need >= 0 ? find(need) : -1; // look up first41 if (i >= 0) { hi = i; hj = j; break; }42 put(a[j], j); // then insert43 }44 printf("hash table: %d %d, %ld comparisons\n", hi, hj, cmp);45 return 0;46}
nested loops: 298 299, 44850 comparisons hash table: 298 299, 300 comparisons
With 300 numbers, the nested loops make 44850 comparisons while the hash table looks at just 300 slots, one per lookup; at n = 100,000, one is 5 billion and the other still about 100,000. The price is O(n) extra space: trading space for time, the most common use of a hash table.
nums = 3 5, target = 6. If the order is swapped, so the loop first does put(a[j], j) and then looks up target - a[j], which two indices does the program report? (-1 -1 if none.)
0 0, using the same number twice. Look up first, then put: while looking up, the table only holds the numbers before x, so this can't happen.Two sum
✓Fill in the loop in main: for each j, first look up find(target - a[j]); if found, print the two indexes and stop; otherwise put(a[j], j).
4 5
1#include <stdio.h>2 3#define M 1014 5int val[M], idx[M], used[M];6 7int find(int x) {8 if (x < 0) return -1;9 for (int p = x % M; used[p]; p = (p + 1) % M)10 if (val[p] == x) return idx[p];11 return -1;12}13 14void put(int x, int i) {15 int p = x % M;16 while (used[p]) p = (p + 1) % M;17 used[p] = 1; val[p] = x; idx[p] = i;18}19 20int main(void) {21 int a[] = {11, 7, 2, 15, 8, 4}, n = 6, target = 12;22 for (int j = 0; j < n; j++) {23 // look up target - a[j] first; if i >= 0: printf("%d %d\n", i, j); return 0;24 // otherwise put(a[j], j)25 }26 printf("none\n");27 return 0;28}
Pattern three: counting and deduplication
"How many times does each thing appear", "are there duplicates", "remove the duplicates" are all one table: the key is the thing, the value the count (or just whether it's there). When the keys come from a small range, an array is a hash table: there are only 256 characters, so cnt[c] does it, with h(c) = c and never a collision.
To find a string's first character that appears only once: count in the first pass, then in the second pass walk in the original order looking for a count of 1.
i1#include <stdio.h>2 3int first_unique(const char *s) {4 int cnt[256] = {0};5 for (int i = 0; s[i]; i++)6 cnt[(unsigned char)s[i]]++; // pass one: count7 for (int i = 0; s[i]; i++)8 if (cnt[(unsigned char)s[i]] == 1) // pass two: search in the original order9 return i;10 return -1;11}12 13int main(void) {14 const char *w[] = {"leetcode", "loveleetcode", "aabb"};15 for (int i = 0; i < 3; i++)16 printf("%s: %d\n", w[i], first_unique(w[i]));17 return 0;18}
leetcode: 0 loveleetcode: 2 aabb: -1
When the keys are arbitrary integers (possibly negative, possibly in the hundreds of millions), no array is big enough, so use a real hash table. To check whether an array contains a duplicate: add the values to a hash set one by one, looking each up first; if it's already there, that's a duplicate. Or sort first and compare neighbours, O(n log n) with no extra space.
| Problem | What the hash table stores | Time |
|---|---|---|
| Two sum | value → index | O(n) |
| First unique character | character → count (an array will do) | O(n) |
| Contains duplicate / dedup | the value (just present or not) | O(n) |
| Group anagrams | the sorted word → its group of words | O(n · k log k) |
| Longest consecutive sequence | the value (is x − 1 there?) | O(n) |
An array can hold any number from −10⁹ to 10⁹, and you need to know whether there is a duplicate. What should you use?
The first unique character
✓Fill in first_unique: count with cnt[256], then in the original order find the first character whose count is 1 and return that character; if there's none, return '_'.
w s _
1#include <stdio.h>2 3char first_unique(const char *s) {4 int cnt[256] = {0};5 // pass one: cnt[(unsigned char)s[i]]++6 // pass two: if cnt[...] == 1, return s[i]7 return '_';8}9 10int main(void) {11 printf("%c %c %c\n", first_unique("swiss"), first_unique("hashtable"), first_unique("abab"));12 return 0;13}
Contains duplicate
✓Fill in add: look for x in the set with linear probing; if it's already there, return 1; on reaching an empty slot without it, put it there and return 0. The numbers may be negative, so the index is ((x % M) + M) % M.
0 1
1#include <stdio.h>2 3#define M 314 5int val[M], used[M];6 7int add(int x) {8 int p = ((x % M) + M) % M;9 // while used[p]: if val[p] == x return 1, else p = (p + 1) % M10 // stopped at an empty slot: used[p] = 1; val[p] = x; return 011 return 0;12}13 14int has_dup(int a[], int n) {15 for (int i = 0; i < M; i++) used[i] = 0;16 for (int i = 0; i < n; i++)17 if (add(a[i])) return 1;18 return 0;19}20 21int main(void) {22 int a[] = {4, -27, 35, 66, 9};23 int b[] = {3, -28, 34, 3, 12};24 printf("%d %d\n", has_dup(a, 5), has_dup(b, 5));25 return 0;26}
Summary
Three hash table patterns
- ASL success = the sum of each key's comparisons / the number of keys
- ASL failure = the sum of comparisons from each start up to an empty slot / the number of values H can take (linear probing counts the empty slot)
- Two sum: look up target − x first, then insert x: O(n²) becomes O(n)
- Counting, dedup: an array for a small key range, a hash table otherwise; space for time
1for (int j = 0; j < n; j++) {2 int i = find(target - a[j]);3 if (i >= 0) return found(i, j);4 put(a[j], j);5}
Chapter 3 quick check
5 questions: choosing the table size, string hashing, linear probing, deleting, and the ASL for chaining. Work out what each prints yourself first, then pick an option.
The 12 keys 6, 12, …, 72 go into a table with m = 12. How many slots do they use?
1#include <stdio.h>2 3int main(void) {4 int used[12] = {0}, slots = 0;5 for (int k = 6; k <= 72; k += 6) {6 if (!used[k % 12]) slots++;7 used[k % 12] = 1;8 }9 printf("%d\n", slots);10 return 0;11}
'a' is 97 and 'b' is 98. Hashing "ab" with h = h * 31 + c, what's printed?
1#include <stdio.h>2 3int main(void) {4 unsigned h = 0;5 const char *s = "ab";6 for (; *s; s++)7 h = h * 31 + *s;8 printf("%u\n", h);9 return 0;10}
Table length 7, linear probing, inserting 6 13 20 in order. Which slot does 20 land in?
1#include <stdio.h>2 3#define M 74int t[M];5 6int insert(int k) {7 for (int i = 0; i < M; i++) {8 int p = (k % M + i) % M;9 if (t[p] == -1) { t[p] = k; return p; }10 }11 return -1;12}13 14int main(void) {15 for (int i = 0; i < M; i++) t[i] = -1;16 insert(6);17 insert(13);18 printf("%d\n", insert(20));19 return 0;20}
3 10 17 all leave remainder 3, so linear probing put them in slots 3, 4 and 5. Empty 10's slot directly, then search for 17: what's printed?
1#include <stdio.h>2 3#define M 74int t[M] = {-1, -1, -1, -1, -1, -1, -1};5 6int search(int k) {7 for (int i = 0; i < M; i++) {8 int p = (k % M + i) % M;9 if (t[p] == -1) return -1;10 if (t[p] == k) return p;11 }12 return -1;13}14 15int main(void) {16 t[3] = 3; t[4] = 10; t[5] = 17; // placed by linear probing: all % 7 == 317 t[search(10)] = -1; // delete 10 by just emptying its slot18 printf("%d\n", search(17));19 return 0;20}
Chaining, table length 5, h(k) = k % 5, inserting 5 10 15 1 6 2. What's the ASL for a successful search? (It prints the fraction unreduced.)
1#include <stdio.h>2 3int main(void) {4 int keys[] = {5, 10, 15, 1, 6, 2}, n = 6, m = 5;5 int len[5] = {0}, total = 0;6 for (int i = 0; i < n; i++) {7 len[keys[i] % m]++;8 total += len[keys[i] % m]; // the k-th on its chain takes k comparisons to find9 }10 printf("%d/%d\n", total, n);11 return 0;12}