Skip to content

12.5 Discrete math 2 problem set, part b: trees, birthday bounds, MinHash and LSH, Bloom filters, recurrences

The data structures that the corpus pipeline and the tokenizers stand on each have a number that must be chosen before they run. The trie of Trees and tries, longest-prefix match is a tree whose size can be predicted. The A Bloom filter in Programming and Algorithms, which Exact dedup: paragraph hashes, a Bloom screen, and a sort-merge confirm in Data Engineering uses to drop exact duplicates, needs a bit budget and a hash count; pick them by feel and the filter is ten times leakier than it needs to be, silently. The near-duplicate stage, Near-duplicate dedup: MinHash, LSH, union-find, and decontamination, splits 128 MinHash values into 16 bands of 8 rows, which decides at what similarity two documents get compared at all; the wrong split either compares everything or misses the near-copies. And the hash tables keyed by 32- or 64-bit hashes need to know when collisions start.

Concepts from other sections (18)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

  • Trie: a rooted tree whose edges carry characters so that each node spells the string on its path. Read more: 12.2 Trees and tries, longest-prefix match
  • Characteristic equation (recurrences): for a linear recurrence an=c1an−1+c2an−2a_n = c_1 a_{n-1} + c_2 a_{n-2}, the equation r2=c1r+c2r^2 = c_1 r + c_2; with distinct roots r1,r2r_1, r_2 the closed form is an=Ar1n+Br2na_n = A r_1^n + B r_2^n. Read more: Chapter 12: Discrete Math 2
  • Generating function: the power series A(x)=∑anxnA(x) = \sum a_n x^n whose coefficients are a sequence; algebra on A(x)A(x) solves counting problems and recurrences. Read more: Chapter 12: Discrete Math 2
  • Power series: a series ∑cn(x−a)n\sum c_n (x - a)^n in powers of x−ax - a; it converges for ∣x−a∣|x - a| less than its radius of convergence RR and can diverge beyond it. Read more: Chapter 8: Calculus 2
  • Connected graph: a graph with a path (a sequence of distinct vertices, each joined to the next by an edge) between every pair of vertices; a tree is a connected graph with no cycles. Read more: Chapter 12: Discrete Math 2
  • Complete binary tree: a tree with every level full except possibly the last, which is filled left to right; it is what makes the array layout work. Read more: 18.4 Binary heap in Programming and Algorithms
  • Binary heap: a complete binary tree in an array in which no child comes out before its parent. Read more: 15.6 A binary heap with lazy deletion in Programming and Algorithms
  • Linearity of expectation: E[aX+bY]=aE[X]+bE[Y]E[aX + bY] = aE[X] + bE[Y], which holds even when XX and YY are dependent; it is the main tool for analysing randomized algorithms, such as the coupon collector’s nHnn H_n expected draws. Read more: Chapter 13: Probability and Statistics
  • Variance: the expected squared distance from the mean; its square root is the standard deviation. Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller
  • Divide and conquer / divide-and-conquer: an algorithm design that splits a problem into independent subproblems, solves them recursively, and combines their results; unlike dynamic programming the subproblems do not overlap, and the gain comes from better asymptotics, as in merge sort. Read more: Chapter 13: Recursion and divide-and-conquer in Programming and Algorithms
  • Huffman tree: the binary tree Huffman’s algorithm builds, with each character at a leaf; a character’s code is its path from the root, 0 for a left branch and 1 for a right one, so frequent characters sit near the root and get short codes. Read more: 10.1 Huffman coding in Programming and Algorithms
  • Base case: an input on which a recursive function returns directly without calling itself; together with an input that strictly shrinks on every call, it guarantees that the recursion terminates. Read more: Chapter 13: Recursion and divide-and-conquer in Programming and Algorithms
  • Induction hypothesis: the assumption P(k)P(k) used to prove P(k+1)P(k + 1). Read more: 11.3.4 Relations, functions, and validation
  • Bijection: a function that is both injective and surjective, and so has an inverse. Read more: 11.3.4 Relations, functions, and validation
  • Injective: no two inputs share an output; for a dict, no value appears twice. Read more: 11.2 Injective, surjective, bijective: the GPT-2 byte map
  • MinHash signature: the minima of nn hash functions over a document’s shingles; equal entries estimate Jaccard. Read more: 5.4 Near-duplicate dedup: MinHash, LSH, union-find, and decontamination in Data Engineering
  • Standard deviation: Var⁡(X)\sqrt{\operatorname{Var}(X)}, the typical distance of a random variable from its mean, in the same units as the variable itself. Read more: Chapter 13: Probability and Statistics
  • roofline: the bound min⁡(F,I⋅W)\min(F, I \cdot W) on a loop’s speed from peak compute FF, memory bandwidth WW, and arithmetic intensity II. Read more: 22.3 Cache-blocked, packed, batch-invariant matmul in C in AI Engineering

None of these mistakes raises an error. This problem set derives the formulas, so that the parameters in the solution code are calculations rather than guesses. It is a pen-and-paper set with no code to write: 26 problems with answers (27 parts in all) and 3 proofs. Problems 19 to 22 size a Bloom filter, Problems 13 to 18 set up MinHash and LSH bands, and Problem 28 gives the cost of the tiled matmul in Cache-blocked, packed, batch-invariant matmul in C.

You should have worked part a of the problem set (graphs, hashing, expected collisions) and read the trie section and the chapter opening. The review below derives every formula the problems use and works a Bloom filter, an LSH curve, and a proof by hand. Every problem is then followed by a collapsed worked answer with the final result or a complete model proof, together with the common wrong answers and why they are wrong. Try each problem before opening its answer.

Learning objectives

  • Count the edges, internal nodes, and trie nodes of a tree, and prove that a tree on nn nodes has n−1n - 1 edges.
  • Use inclusion-exclusion and birthday bounds to predict when hashed keys start to collide.
  • Prove that MinHash estimates Jaccard similarity, and read the threshold of an LSH S-curve from its bands and rows.
  • Derive the optimal number of Bloom filter hashes and the bits per key for a target false-positive rate.
  • Solve recurrences by unrolling, by the characteristic equation, and with generating functions.

The notation is shared by the review and the problems.

SymbolMeaningType / shape
nnthe number of nodes of a tree, of keys in a filter, or the size of a recurrence’s inputint
∣A∣\lvert A \rvertthe number of elements of a finite set AAint
mmthe number of buckets of a hash, or of bits of a Bloom filterint
kkthe number of keys hashed (birthday), or of hash functions per key (Bloom)int
J(A,B)=∣A∩B∣/∣A∪B∣J(A, B) = \lvert A \cap B \rvert / \lvert A \cup B \rvertthe Jaccard similarity of two non-empty setsfloat in [0,1][0, 1]
π\pia uniformly random permutation of the universe UUpermutation
bb, rrthe LSH bands and rows per band, brb r = signature lengthint
ssthe probability that one MinHash row agrees (the pair’s Jaccard similarity)float
T(n)T(n)the cost of a recursive algorithm on input size nnfunction
A(x)=∑n≥0anxnA(x) = \sum_{n \ge 0} a_n x^nthe ordinary generating function of a sequence a0,a1,…a_0, a_1, \dotsformal power series

A tree is a connected graph with no cycle. Between two of its nodes there is exactly one path; it has exactly n−1n - 1 edges (Problem 6 asks for the proof); and a tree with at least two nodes has at least two leaves. Rooting it makes every non-root node the child of exactly one parent. In a full binary tree every internal node has two children, so counting edges two ways, 2⋅internal=n−12 \cdot \text{internal} = n - 1 with n=internal+leavesn = \text{internal} + \text{leaves}, gives internal=leaves−1\text{internal} = \text{leaves} - 1. A complete binary tree of nn nodes is the shape of a binary heap (node ii has children 2i2i and 2i+12i + 1), and its height is ⌊log⁡2n⌋\lfloor \log_2 n \rfloor. Cayley’s formula counts the trees on nn labelled nodes: nn−2n^{n-2}.

Counting unions needs one more tool. Inclusion-exclusion says: to count a union, add the sizes, subtract every pairwise overlap (counted twice), add back every triple overlap (subtracted once too often), and so on:

∣A∪B∪C∣=∣A∣+∣B∣+∣C∣−∣A∩B∣−∣A∩C∣−∣B∩C∣+∣A∩B∩C∣.\lvert A \cup B \cup C \rvert = \lvert A \rvert + \lvert B \rvert + \lvert C \rvert - \lvert A \cap B \rvert - \lvert A \cap C \rvert - \lvert B \cap C \rvert + \lvert A \cap B \cap C \rvert.

The same alternating sum over the events “element ii is fixed” counts derangements.

Counting turns into probability as soon as keys are hashed. Hash kk keys uniformly into mm buckets. The keys are all in different buckets with probability ∏i=0k−1(1−i/m)\prod_{i=0}^{k-1}(1 - i/m): the (i+1)(i+1)-th key must avoid the ii occupied buckets. Using 1−x≤e−x1 - x \le e^{-x}, this is at most e−k(k−1)/(2m)≈e−k2/(2m)e^{-k(k-1)/(2m)} \approx e^{-k^2/(2m)}. Each of the (k2)\binom{k}{2} pairs collides with probability 1/m1/m, so by linearity of expectation the expected number of colliding pairs is (k2)/m\binom{k}{2}/m, and by the union bound that is also an upper bound on the probability of any collision. All three say the same thing: collisions start at k≈mk \approx \sqrt{m}.

Collisions are usually the enemy; MinHash turns them into a measurement. Two documents are sets of shingles (overlapping substrings), and their similarity is the Jaccard similarity JJ. Apply a random permutation π\pi to the universe and keep the minimum of each set. Among A∪BA \cup B, the element with the smallest π\pi value is equally likely to be any of the ∣A∪B∣\lvert A \cup B \rvert elements, and the two minima agree exactly when it lies in A∩BA \cap B. So P(min⁡π(A)=min⁡π(B))=J(A,B)P(\min \pi(A) = \min \pi(B)) = J(A, B) (Problem 14). With NN independent permutations, the fraction that agree is an unbiased estimate of JJ with variance J(1−J)/NJ(1 - J)/N, the variance of a mean of Bernoulli variables. The near-duplicate stage stands in for permutations with seeded hash functions.

Estimating every pair’s similarity is still too expensive: comparing every pair of 10610^6 documents is 5×10115 \times 10^{11} comparisons. Instead, split each signature into bb bands of rr rows and hash each band; two documents become candidates when they agree on every row of some band. With per-row agreement ss, one band agrees with probability srs^r and fails with 1−sr1 - s^r, all bb fail with (1−sr)b(1 - s^r)^b, so

P(candidate)=1−(1−sr)b.P(\text{candidate}) = 1 - (1 - s^r)^b.

As a function of ss this is an S-curve: near 0 for dissimilar pairs, near 1 for similar ones, rising most steeply around t≈(1/b)1/rt \approx (1/b)^{1/r}. More rows per band push the threshold up and sharpen the curve; more bands pull it down.

A Bloom filter answers “have I seen this key?” in a fixed number of bits. It is mm bits, all 0. Inserting a key sets the kk bits its kk hashes point to. A lookup reports “present” when all kk of its bits are set, so it never misses an inserted key, and it reports a false positive when an absent key finds all its bits set by others. After nn insertions one bit is still 0 with probability (1−1/m)kn≈e−kn/m(1 - 1/m)^{kn} \approx e^{-kn/m}. Treating the kk probed bits as independent (an approximation, accurate for large mm), the false-positive rate is

f(k)=(1−e−kn/m)k.f(k) = \big(1 - e^{-kn/m}\big)^k.

Write p=e−kn/mp = e^{-kn/m} for the fraction of zero bits, so k=−(m/n)ln⁡pk = -(m/n) \ln p and ln⁡f=−(m/n)ln⁡p ln⁡(1−p)\ln f = -(m/n) \ln p \, \ln(1 - p). That is symmetric under p↔1−pp \leftrightarrow 1 - p and is smallest at p=1/2p = 1/2: the best filter has half its bits set, k=(m/n)ln⁡2k = (m/n) \ln 2, and f=2−kf = 2^{-k}. Solving 2−k=ptarget2^{-k} = p_{\text{target}} for the bits per key gives m/n=−ln⁡ptarget/(ln⁡2)2≈1.44log⁡2(1/ptarget)m/n = -\ln p_{\text{target}} / (\ln 2)^2 \approx 1.44 \log_2(1/p_{\text{target}}).

The last topic is cost. A recurrence defines a sequence by its earlier terms, and there are three standard ways to solve one:

  1. Unroll and sum. T(n)=T(n−1)+nT(n) = T(n-1) + n unrolls to 1+2+⋯+n1 + 2 + \dots + n. For T(n)=2T(n/2)+nT(n) = 2T(n/2) + n each of the log⁡2n\log_2 n levels of the recursion costs nn in total.
  2. Characteristic equation. For an=c1an−1+c2an−2a_n = c_1 a_{n-1} + c_2 a_{n-2} try an=λna_n = \lambda^n: then λ2=c1λ+c2\lambda^2 = c_1 \lambda + c_2. With distinct roots λ1,λ2\lambda_1, \lambda_2 the general solution is αλ1n+βλ2n\alpha \lambda_1^n + \beta \lambda_2^n, and the two initial values fix α\alpha and β\beta.
  3. Generating functions. Multiply the recurrence by xnx^n and sum, and it becomes an equation for A(x)A(x). The basic pair is ∑nxn=1/(1−x)\sum_n x^n = 1/(1 - x), and differentiating it gives ∑n(n+1)xn=1/(1−x)2\sum_n (n + 1) x^n = 1/(1-x)^2.

For divide-and-conquer costs T(n)=a T(n/b)+ndT(n) = a\,T(n/b) + n^d, compare log⁡ba\log_b a with dd. The leaves dominate when log⁡ba>d\log_b a > d, giving T(n)=Θ(nlog⁡ba)T(n) = \Theta(n^{\log_b a}), which is why 8 half-size matrix products cost n3n^3 and Strassen’s 7 cost nlog⁡27n^{\log_2 7}.

The three examples here are siblings of the problems, not answers to them. Start by sizing a Bloom filter at 8 bits per key. The optimal number of hashes is k∗=(m/n)ln⁡2=8×0.6931=5.545k^* = (m/n) \ln 2 = 8 \times 0.6931 = 5.545. A filter needs an integer, so compare the neighbours with f(k)=(1−e−k/8)kf(k) = (1 - e^{-k/8})^k:

kke−k/8e^{-k/8}1−e−k/81 - e^{-k/8}f(k)f(k)
50.53530.46470.02168
60.47240.52760.02158

k=6k = 6 is (barely) better, giving about 2.16% false positives. At the real-valued optimum the rate would be 2−5.545=0.02142^{-5.545} = 0.0214. For 1% you need m/n=ln⁡100/(ln⁡2)2=9.59m/n = \ln 100 / (\ln 2)^2 = 9.59 bits per key.

Next, read an LSH S-curve with 20 bands of 5 rows. The threshold is (1/20)1/5=0.549(1/20)^{1/5} = 0.549. At s=0.8s = 0.8: s5=0.32768s^5 = 0.32768, a band fails with 0.672320.67232, all 20 fail with 0.6723220=0.0003560.67232^{20} = 0.000356, so the pair becomes a candidate with probability 0.999640.99964. At s=0.3s = 0.3: s5=0.00243s^5 = 0.00243, (1−0.00243)20=0.9525(1 - 0.00243)^{20} = 0.9525, so only 0.04750.0475. Similar pairs are almost always compared and dissimilar ones rarely.

Finally, a model proof. Claim: a full binary tree with L≥1L \ge 1 leaves has L−1L - 1 internal nodes. Method: strong induction on LL. Base: L=1L = 1 is a single node, which is a leaf, with 0 internal nodes. Step: let L≥2L \ge 2 and assume the claim for every full binary tree with fewer than LL leaves. The root is internal (a leaf root would mean L=1L = 1), so it has two subtrees, each a full binary tree, with L1≥1L_1 \ge 1 and L2≥1L_2 \ge 1 leaves, L1+L2=LL_1 + L_2 = L, so each has fewer than LL. By the hypothesis they have L1−1L_1 - 1 and L2−1L_2 - 1 internal nodes. Adding the root: (L1−1)+(L2−1)+1=L−1(L_1 - 1) + (L_2 - 1) + 1 = L - 1. So every full binary tree with LL leaves has L−1L - 1 internal nodes. Every symbol is defined, the hypothesis is used for the subtrees and not for the tree itself, and the last line restates the claim: the model proofs of Problems 6 and 29 have the same shape.

Answers are exact where the problem says so; otherwise a closed form is given together with a decimal to the stated precision. log means the natural logarithm, and log⁡2x=ln⁡x/ln⁡2\log_2 x = \ln x / \ln 2. Lettered parts share one answer block. The tag after each problem says what kind of answer is expected.

The first six problems count edges, trie nodes, internal nodes, labelled trees, and heap heights, and finish with the proof that a tree on nn nodes has n−1n - 1 edges.

Problem 1. A tree has 12 nodes. How many edges does it have? [number]

Answer

1111. A tree on nn nodes has n−1n - 1 edges (Problem 6): every non-root node has exactly one edge to its parent. This is how a parent array or a trie arena sizes itself. Common mistakes: 12 gives every node an edge, including the root; 66 =(122)= \binom{12}{2} is the complete graph.

Problem 2. Build the trie of Trees and tries, longest-prefix match for the five keys car, cart, care, cat, dog. How many nodes does it have, counting the root? [number]

Answer

1010. Count distinct prefixes plus the root. Under c: c, ca, car, then cart, care, and cat (6 nodes). Under d: d, do, dog (3 nodes). With the root: 1+6+3=101 + 6 + 3 = 10. Shared prefixes are stored once, which is what makes a trie small. Common mistakes: 18 is 1 plus the 17 characters of the keys, with no sharing; 9 forgets the root.

Problem 3. A full binary tree is a rooted tree in which every node has either 0 or 2 children. One has 10 leaves. How many internal (non-leaf) nodes does it have? [number]

Answer

99. In a full binary tree, internal == leaves −1- 1 (the model proof worked by hand above). Counting edges two ways: 2I=n−1=I+L−12I = n - 1 = I + L - 1, so I=L−1=9I = L - 1 = 9. A BPE merge tree and a Huffman tree have this shape. Common mistakes: 10, and 19, which is the total number of nodes.

Problem 4. How many different trees are there on the 5 labelled nodes {1,2,3,4,5}\{1, 2, 3, 4, 5\}? (Two trees differ when some pair of nodes is joined in one and not in the other.) [number]

Answer

125125. Cayley’s formula, nn−2=53=125n^{n-2} = 5^3 = 125. Common mistakes: 5!=1205! = 120 counts orderings, and 54=6255^4 = 625 is nn−1n^{n-1}, the count of rooted trees.

Problem 5. A complete binary tree fills every level except possibly the last, and fills the last level from the left. One has n=100n = 100 nodes. What is its height, the number of edges on its longest root-to-leaf path? [number]

Answer

66. The height of a complete binary tree with nn nodes is ⌊log⁡2n⌋\lfloor \log_2 n \rfloor: levels 0 to 5 hold 1+2+⋯+32=631 + 2 + \dots + 32 = 63 nodes, and the remaining 37 sit on level 6. A common mistake is 7, which counts levels instead of edges.

Problem 6. Prove that every tree with n≥1n \ge 1 nodes has exactly n−1n - 1 edges. [proof]

Answer

Claim. A tree is a connected graph with no cycle. For every n≥1n \ge 1, every tree with nn nodes has exactly n−1n - 1 edges.

Lemma (a leaf exists). A tree TT with n≥2n \ge 2 nodes has a node of degree 1. Since TT is connected and has at least two nodes, it has an edge, so paths of length at least 1 exist. Take a longest path v0v1…vℓv_0 v_1 \dots v_\ell (paths have no repeated nodes, so there are finitely many). The end v0v_0 is adjacent to v1v_1. If v0v_0 had another neighbour ww, then either w=viw = v_i for some i≥2i \ge 2, and v0v1…viv0v_0 v_1 \dots v_i v_0 is a cycle, which a tree does not have; or ww is off the path, and wv0v1…vℓw v_0 v_1 \dots v_\ell is a longer path, contradicting the choice. So v0v_0 has degree 1.

Lemma (removing a leaf leaves a tree). Let vv be a leaf of TT with its one edge vuvu, and let T′=T−vT' = T - v. T′T' has no cycle, because every cycle of T′T' is a cycle of TT. T′T' is connected: for nodes x,y≠vx, y \ne v, the path from xx to yy in TT cannot pass through vv, since an interior node of a path needs two distinct path neighbours and vv has only one. So that path lies in T′T'.

Proof (induction on nn). Base case n=1n = 1: a single node has no edge, since an edge would need a second endpoint (and a loop is a cycle). So it has 0=n−10 = n - 1 edges.

Inductive step: let n≥2n \ge 2 and assume every tree with n−1n - 1 nodes has n−2n - 2 edges. Let TT be a tree with nn nodes. By the first lemma it has a leaf vv; by the second, T′=T−vT' = T - v is a tree with n−1n - 1 nodes, and it has exactly one edge fewer than TT (the edge vuvu). The induction hypothesis applied to T′T' gives n−2n - 2 edges for T′T', so TT has (n−2)+1=n−1(n - 2) + 1 = n - 1 edges. By induction the claim holds for every n≥1n \ge 1.

Model proof also in q6.md.

Problems on inclusion-exclusion and birthday bounds

Section titled “Problems on inclusion-exclusion and birthday bounds”

These problems count unions and derangements, then turn to the probability that hashed keys collide and how many keys it takes.

Problem 7. Three sets have ∣A∣=∣B∣=∣C∣=10\lvert A \rvert = \lvert B \rvert = \lvert C \rvert = 10, every pairwise intersection has 3 elements, and ∣A∩B∩C∣=1\lvert A \cap B \cap C \rvert = 1. Give ∣A∪B∪C∣\lvert A \cup B \cup C \rvert. [number]

Answer

2222. 10+10+10−3−3−3+1=2210 + 10 + 10 - 3 - 3 - 3 + 1 = 22. A common mistake is 21, which forgets to add the triple intersection back: an element in all three sets is added 3 times and subtracted 3 times, so it must be added once more. 30 makes no correction at all.

Problem 8. How many integers in {1,2,…,100}\{1, 2, \dots, 100\} are divisible by 2, 3, or 5? [number]

Answer

7474. Let DkD_k be the multiples of kk. ∣D2∣+∣D3∣+∣D5∣=50+33+20=103|D_2| + |D_3| + |D_5| = 50 + 33 + 20 = 103; pairwise ∣D6∣+∣D10∣+∣D15∣=16+10+6=32|D_6| + |D_{10}| + |D_{15}| = 16 + 10 + 6 = 32; triple ∣D30∣=3|D_{30}| = 3. Total 103−32+3=74103 - 32 + 3 = 74. Common mistakes: 103 is the plain sum, and 71 forgets to add ∣D30∣|D_{30}| back.

Problem 9. A derangement of {1,2,3,4}\{1, 2, 3, 4\} is a permutation that moves every element. How many are there? [number]

Answer

99. Inclusion-exclusion over the events “element ii is fixed”: 4!−(41)3!+(42)2!−(43)1!+(44)0!=24−24+12−4+1=94! - \binom41 3! + \binom42 2! - \binom43 1! + \binom44 0! = 24 - 24 + 12 - 4 + 1 = 9. Common mistakes: 24 is every permutation; 8 drops the last term.

Problem 10. Three keys are hashed independently and uniformly into m=10m = 10 buckets. Give the exact probability that all three land in different buckets. [number] (exact)

Answer

18/2518/25. The second key must avoid one bucket and the third two: 1⋅910⋅810=72100=18251 \cdot \frac{9}{10} \cdot \frac{8}{10} = \frac{72}{100} = \frac{18}{25}. Common mistakes: 7/10=1−3/107/10 = 1 - 3/10 subtracts the union bound on a collision, which is only an upper bound; 7/257/25 is the complement, the probability of at least one collision.

Problem 11. kk keys are hashed independently and uniformly into mm buckets. Give the expected number of unordered pairs of keys that share a bucket, as a formula in kk and mm. [expr] (variables k, m)

Answer

k(k−1)2m\frac{k(k - 1)}{2m}. There are (k2)\binom{k}{2} unordered pairs, each colliding with probability 1/m1/m, and expectation is linear. Common mistakes: k2/mk^2/m and k(k−1)/mk(k-1)/m count ordered pairs (and the first also self-pairs).

Problem 12. Using P(no collision among k keys)≈e−k2/(2m)P(\text{no collision among } k \text{ keys}) \approx e^{-k^2/(2m)}, find the kk at which a collision becomes as likely as not, for a 32-bit hash (m=232m = 2^{32}). [number] (to 3 significant digits)

Answer

≈77,200\approx 77{,}200 (2162ln⁡2≈77,1632^{16}\sqrt{2\ln 2} \approx 77{,}163). Set e−k2/(2m)=12e^{-k^2/(2m)} = \frac12: k2=2mln⁡2k^2 = 2m\ln 2, k=2ln⁡2⋅232=2162ln⁡2k = \sqrt{2 \ln 2 \cdot 2^{32}} = 2^{16}\sqrt{2\ln 2}. So a 32-bit hash collides after about 77,000 keys, not 4 billion. Common mistakes: 216=m2^{16} = \sqrt m drops the constant 2ln⁡2≈1.18\sqrt{2\ln 2} \approx 1.18, and 2312^{31} (half the table) is the intuition the birthday bound refutes.

This group computes Jaccard similarities, proves the MinHash property, and reads the LSH S-curve for the banding used in near-duplicate detection.

Problem 13. Give the Jaccard similarity J(A,B)=∣A∩B∣/∣A∪B∣J(A, B) = \lvert A \cap B \rvert / \lvert A \cup B \rvert of the shingle sets A={ab,bc,cd,de}A = \{ab, bc, cd, de\} and B={bc,cd,de,ef,fg}B = \{bc, cd, de, ef, fg\}. [number] (exact)

Answer

1/21/2. A∩B={bc,cd,de}A \cap B = \{bc, cd, de\} (3 elements), A∪B={ab,bc,cd,de,ef,fg}A \cup B = \{ab, bc, cd, de, ef, fg\} (6), so J=3/6J = 3/6. Common mistakes: 3/53/5 divides by ∣B∣|B| and 3/43/4 by ∣A∣|A|; neither is symmetric in AA and BB.

Problem 14. Let AA and BB be non-empty subsets of a finite universe UU and π\pi a uniformly random permutation of UU. Prove that P(min⁡π(A)=min⁡π(B))=J(A,B)P(\min \pi(A) = \min \pi(B)) = J(A, B). (This is why one MinHash value per permutation is an unbiased estimate of Jaccard similarity.) [proof]

Answer

Claim. Let A,BA, B be non-empty subsets of a finite universe UU and π\pi a uniformly random permutation of UU (a bijection U→{1,…,∣U∣}U \to \{1, \dots, |U|\}). Then P(min⁡π(A)=min⁡π(B))=∣A∩B∣/∣A∪B∣P(\min \pi(A) = \min \pi(B)) = |A \cap B| / |A \cup B|, which is the Jaccard similarity J(A,B)J(A, B).

Proof. Let mm be the element of A∪BA \cup B with the smallest value π(m)\pi(m); it is well defined because A∪BA \cup B is non-empty and π\pi is injective. For a uniform π\pi every ordering of A∪BA \cup B is equally likely, and by symmetry each of the ∣A∪B∣|A \cup B| elements is equally likely to be first. So mm is uniformly distributed over A∪BA \cup B.

Now compare the two minima. min⁡π(A)=π(m)\min \pi(A) = \pi(m) when m∈Am \in A, because no element of A⊆A∪BA \subseteq A \cup B has a smaller value; likewise min⁡π(B)=π(m)\min \pi(B) = \pi(m) when m∈Bm \in B.

  • If m∈A∩Bm \in A \cap B, both minima equal π(m)\pi(m), so they are equal.
  • If m∈A∖Bm \in A \setminus B, then min⁡π(A)=π(m)\min \pi(A) = \pi(m), while every element of BB differs from mm and has a larger value, so min⁡π(B)>π(m)\min \pi(B) > \pi(m) and the minima differ. The case m∈B∖Am \in B \setminus A is symmetric.

So the minima are equal exactly when m∈A∩Bm \in A \cap B, and

P(min⁡π(A)=min⁡π(B))=P(m∈A∩B)=∣A∩B∣∣A∪B∣=J(A,B).P(\min \pi(A) = \min \pi(B)) = P(m \in A \cap B) = \frac{|A \cap B|}{|A \cup B|} = J(A, B).

Hence the indicator that one MinHash position agrees has mean J(A,B)J(A, B): it is an unbiased estimate of the Jaccard similarity.

Model proof also in q14.md.

Problem 15. A MinHash signature with 128 independent permutations estimates JJ by the fraction of the 128 positions that agree. Each position agrees with probability JJ, independently. Give the variance of the estimate when J=1/2J = 1/2. [number] (exact)

Answer

1/5121/512. The estimate is a mean of 128 independent Bernoulli(JJ) variables, so its variance is J(1−J)/128=1/4128=1512J(1 - J)/128 = \frac{1/4}{128} = \frac{1}{512}, a standard deviation of about 0.044. Common mistakes: 1/2561/256, and 1/1281/128, which forgets the factor J(1−J)J(1 - J).

Problem 16. LSH splits a signature into bb bands of rr rows; two documents become a candidate pair when all rr rows of at least one band agree. Each row agrees with probability ss (their Jaccard similarity), independently. Give the probability that they become candidates for b=16b = 16, r=8r = 8 (the defaults of the near-duplicate stage in Data Engineering), as a formula in ss. [expr] (variable s)

Answer

1−(1−s8)161 - (1 - s^8)^{16}. One band (8 rows) agrees with probability s8s^8, fails with 1−s81 - s^8; all 16 bands fail with (1−s8)16(1 - s^8)^{16}; the pair is a candidate unless they all fail. Common mistakes: 1−(1−s16)81 - (1 - s^{16})^8 swaps bands and rows, and (1−(1−s)8)16(1 - (1 - s)^8)^{16} swaps AND and OR (it would require every band to have at least one agreeing row).

Problem 17. The S-curve of Problem 16 rises most steeply near the threshold t≈(1/b)1/rt \approx (1/b)^{1/r}. Give tt for b=16b = 16, r=8r = 8. [number] (to 3 significant digits)

Answer

≈0.707\approx 0.707 (2−1/22^{-1/2}). (1/16)1/8=2−4/8=2−1/2≈0.7071(1/16)^{1/8} = 2^{-4/8} = 2^{-1/2} \approx 0.7071. So with the near-duplicate stage’s defaults, pairs above about 0.7 similarity are likely to be compared. Common mistakes: 1/161/16 forgets the rr-th root, and 1/21/2 guesses.

Problem 18. With b=16b = 16, r=8r = 8, give the probability that two documents with s=1/2s = 1/2 become candidates. [number] (to 6 significant digits)

Answer

≈0.0607019\approx 0.0607019 (1−(255/256)161 - (255/256)^{16}). s8=1/256s^8 = 1/256, a band fails with 255/256255/256, so the pair is a candidate with probability 1−(255/256)16≈0.06070191 - (255/256)^{16} \approx 0.0607019. Common mistakes: 16/256=0.062516/256 = 0.0625 is the union bound over bands, close but not the probability; 1/2561/256 is one band.

The Bloom problems derive the false-positive rate, the optimal number of hashes, and the bits per key needed for a target rate.

A Bloom filter has mm bits, holds nn keys, and sets kk bits per key with independent uniform hashes. A lookup of a key that was never inserted is a false positive when all kk of its bits are set.

Problem 19. Give the standard approximation of the false-positive rate, using (1−1/m)kn≈e−kn/m(1 - 1/m)^{kn} \approx e^{-kn/m}, as a formula in kk, nn, and mm. [expr] (variables k, n, m)

Answer

(1−e−kn/m)k\left(1 - e^{-kn/m}\right)^k. After knkn bit-settings, one bit is still 0 with probability (1−1/m)kn≈e−kn/m(1 - 1/m)^{kn} \approx e^{-kn/m}, so set with 1−e−kn/m1 - e^{-kn/m}. A false positive needs all kk probed bits set: raise to the kk-th power. Common mistakes: (1−e−n/m)k(1 - e^{-n/m})^k sets only one bit per key, and 1−e−kn/m1 - e^{-kn/m} probes one bit.

Problem 20. The rate of Problem 19 is smallest at k=(m/n)ln⁡2k = (m/n) \ln 2. Give this optimal kk for 10 bits per key (m/n=10m/n = 10), before rounding to an integer. [number] (to 6 significant digits)

Answer

≈6.93147\approx 6.93147 (10ln⁡210 \ln 2). Directly from k∗=(m/n)ln⁡2k^* = (m/n) \ln 2. Common mistakes: 10/ln⁡2≈14.410/\ln 2 \approx 14.4 inverts the factor, and 7 rounds before it was asked (a real filter does round, and compares the neighbours as in the Bloom example worked by hand above).

Problem 21. At the optimal kk of Problem 20 every bit is set with probability 1/21/2. Give the false-positive rate at that kk. [number] (to 6 significant digits)

Answer

≈0.00819255\approx 0.00819255 (2−10ln⁡22^{-10 \ln 2}). With half the bits set, each probe hits a set bit with probability 1/21/2, so f=2−k∗=2−6.93147≈0.0082f = 2^{-k^*} = 2^{-6.93147} \approx 0.0082, about 0.82%. Common mistakes: 1/1024=2−101/1024 = 2^{-10} uses bits per key as the number of hashes, and (1/2)7(1/2)^7 rounds kk first.

Problem 22. With the optimal kk, the bits per key needed for a target false-positive rate pp are m/n=−ln⁡p/(ln⁡2)2m/n = -\ln p / (\ln 2)^2. Give m/nm/n for p=0.01p = 0.01. [number] (to 6 significant digits)

Answer

≈9.58506\approx 9.58506 (ln⁡100/(ln⁡2)2\ln 100 / (\ln 2)^2). −ln⁡0.01=ln⁡100≈4.6052-\ln 0.01 = \ln 100 \approx 4.6052, and (ln⁡2)2≈0.48045(\ln 2)^2 \approx 0.48045. So 1% needs about 9.6 bits per key, with k=9.585⋅ln⁡2≈6.6k = 9.585 \cdot \ln 2 \approx 6.6 hashes. Common mistakes: ln⁡100/ln⁡2≈6.64\ln 100 / \ln 2 \approx 6.64 is kk, not bits per key, and a filter sized at 6.6 bits per key misses its target; 100 confuses the rate with its reciprocal.

Problems on recurrences and generating functions

Section titled “Problems on recurrences and generating functions”

The last group solves recurrences by unrolling, by the characteristic equation, and with generating functions, and closes with a proof of the merge-sort cost.

Problem 23. Solve T(n)=2 T(n/2)+nT(n) = 2\,T(n/2) + n with T(1)=0T(1) = 0 for nn a power of 2. [expr] (variable n)

Answer

nlog⁡2nn \log_2 n. Unroll: the recursion has log⁡2n\log_2 n levels, and level ii has 2i2^i subproblems of size n/2in/2^i, each costing n/2in/2^i, so every level costs nn. The leaves cost T(1)=0T(1) = 0. Problem 29 proves it by induction. Common mistakes: nln⁡nn \ln n uses the natural log, off by a factor ln⁡2\ln 2; n2n^2 ignores the halving.

Problem 24. Solve T(n)=T(n−1)+nT(n) = T(n - 1) + n with T(0)=0T(0) = 0. [expr] (variable n)

Answer

n(n+1)2\frac{n(n + 1)}{2}. Unroll: T(n)=n+(n−1)+⋯+1+T(0)T(n) = n + (n - 1) + \dots + 1 + T(0). Common mistakes: n2/2n^2/2 keeps only the leading term, and n(n−1)/2n(n - 1)/2 is off by one (it stops at n−1n - 1).

Problem 25. Solve an=3an−1−2an−2a_n = 3a_{n-1} - 2a_{n-2} with a0=0a_0 = 0 and a1=1a_1 = 1. [expr] (variable n)

Answer

2n−12^n - 1. Characteristic equation λ2=3λ−2\lambda^2 = 3\lambda - 2, roots 1 and 2, so an=α+β2na_n = \alpha + \beta 2^n. a0=0a_0 = 0 gives α=−β\alpha = -\beta; a1=1a_1 = 1 gives −β+2β=1-\beta + 2\beta = 1, so β=1\beta = 1, α=−1\alpha = -1. Check: a2=3−0=3=22−1a_2 = 3 - 0 = 3 = 2^2 - 1. Common mistakes: 2n2^n and 2n−12^{n-1} ignore the initial values.

Problem 26. Give the ordinary generating function A(x)=∑n≥0anxnA(x) = \sum_{n \ge 0} a_n x^n of the sequence an=n+1a_n = n + 1 (that is, 1,2,3,…1, 2, 3, \dots) in closed form. [expr] (variable x)

Answer

1(1−x)2\frac{1}{(1 - x)^2}. Differentiate ∑n≥0xn=11−x\sum_{n \ge 0} x^n = \frac{1}{1 - x}: ∑n≥1nxn−1=∑n≥0(n+1)xn=1(1−x)2\sum_{n \ge 1} n x^{n-1} = \sum_{n \ge 0} (n + 1) x^n = \frac{1}{(1-x)^2}. Common mistakes: 11−x\frac{1}{1-x} is the sequence of all 1s, and x(1−x)2\frac{x}{(1-x)^2} generates an=na_n = n, not n+1n + 1.

Problem 27. How many binary strings of length 10 contain no two consecutive 1s? [number]

Answer

144144. Let cnc_n count the valid strings of length nn. A valid string ends in 0 (anything valid of length n−1n - 1 before it) or in 01 (anything valid of length n−2n - 2): cn=cn−1+cn−2c_n = c_{n-1} + c_{n-2}, with c1=2c_1 = 2, c2=3c_2 = 3. So cn=Fn+2c_n = F_{n+2}: 2,3,5,8,13,21,34,55,89,1442, 3, 5, 8, 13, 21, 34, 55, 89, 144. Common mistakes: 89 is c9c_9, off by one; 1024 counts every string.

Problem 28. Recursive matrix multiplication splits each n×nn \times n matrix into four n/2×n/2n/2 \times n/2 blocks. (a) The plain method does 8 half-size products and Θ(n2)\Theta(n^2) additions: T(n)=8 T(n/2)+n2T(n) = 8\,T(n/2) + n^2. Give the exponent cc with T(n)=Θ(nc)T(n) = \Theta(n^c). (b) Strassen’s method does 7: T(n)=7 T(n/2)+n2T(n) = 7\,T(n/2) + n^2. Give cc. [number]

Answer

(a) 33, (b) log⁡27≈2.807\log_2 7 \approx 2.807. Compare log⁡ba\log_b a with d=2d = 2. (a) log⁡28=3>2\log_2 8 = 3 > 2: the leaves dominate, T(n)=Θ(n3)T(n) = \Theta(n^3). (b) log⁡27≈2.807>2\log_2 7 \approx 2.807 > 2: Θ(nlog⁡27)\Theta(n^{\log_2 7}). Common mistakes: 2 for (a) reads the cost of the additions; 3 for (b) ignores that one fewer product changes the exponent; ln⁡7\ln 7 uses the wrong base.

Problem 29. Prove by induction that T(n)=2 T(n/2)+nT(n) = 2\,T(n/2) + n with T(1)=0T(1) = 0 gives T(n)=nlog⁡2nT(n) = n \log_2 n for every nn that is a power of 2. [proof]

Answer

Claim. Let T(1)=0T(1) = 0 and T(n)=2T(n/2)+nT(n) = 2T(n/2) + n for n≥2n \ge 2 a power of 2. Writing n=2jn = 2^j, we prove T(2j)=2j⋅jT(2^j) = 2^j \cdot j for every integer j≥0j \ge 0, which is T(n)=nlog⁡2nT(n) = n \log_2 n for every power of 2.

Base case j=0j = 0. T(20)=T(1)=0=1⋅0=20⋅0T(2^0) = T(1) = 0 = 1 \cdot 0 = 2^0 \cdot 0.

Inductive step. Assume T(2j)=2j⋅jT(2^j) = 2^j \cdot j for some j≥0j \ge 0. Since 2j+1≥22^{j+1} \ge 2, the recurrence applies with n=2j+1n = 2^{j+1} and n/2=2jn/2 = 2^j:

T(2j+1)=2 T(2j)+2j+1.T(2^{j+1}) = 2\,T(2^j) + 2^{j+1}.

By the hypothesis T(2j)=2jjT(2^j) = 2^j j, so

T(2j+1)=2⋅2j⋅j+2j+1=2j+1j+2j+1=2j+1(j+1).T(2^{j+1}) = 2 \cdot 2^j \cdot j + 2^{j+1} = 2^{j+1} j + 2^{j+1} = 2^{j+1}(j + 1).

This is the claim for j+1j + 1. By induction T(2j)=2jjT(2^j) = 2^j j for all j≥0j \ge 0, and with j=log⁡2nj = \log_2 n this reads T(n)=nlog⁡2nT(n) = n \log_2 n.

Model proof also in q29.md.

Each common mistake in this set shows up as a wrong answer to a specific problem. The table collects them, with the symptom in a real system and the habit that avoids it.

PitfallSymptomHow to avoid it
Counting a trie as one node per charactersizes a node arena for the worst case, ignoring shared prefixescount distinct prefixes plus the root (Problem 2)
Forgetting to add back the triple overlapa union undercounted by every element in all three setsalternate signs through every intersection size, including the triple (Problems 7, 8)
Reading the union bound as the probability“1 - 3/10” instead of the exact productmultiply the exact per-step probabilities; use the union bound only as a bound (Problems 10, 18)
Expecting collisions only near a full tablea 32-bit-keyed cache that collides after 77 000 entries, not 4 billionsolve e−k2/(2m)=1/2e^{-k^2/(2m)} = 1/2: k≈1.18mk \approx 1.18\sqrt m (Problem 12)
Dividing the overlap by one set’s sizea similarity that is not symmetric and overstates small documentsdivide by the union, which is symmetric (Problem 13)
Swapping bands and rows, or AND and ORthe S-curve’s threshold lands far from the intended similarityAND within a band (srs^r), OR across bands (1−(1−sr)b1 - (1 - s^r)^b) (Problem 16)
One hash per Bloom key, or a single probea false-positive rate formula off by orders of magnitudecount knkn bit-settings and kk probes (Problem 19)
Confusing kk with bits per keya filter sized at 6.6 bits per key that misses its 1% targetkeep m/n=−ln⁡p/(ln⁡2)2m/n = -\ln p/(\ln 2)^2 apart from k=(m/n)ln⁡2k = (m/n)\ln 2 (Problem 22)
Natural log where log⁡2\log_2 is meantcosts off by a factor of ln⁡2\ln 2write log⁡2\log_2 explicitly, since the recursion halves (Problem 23)

Looking back, this set extends the expected colliding pairs (Problem 17) and modular hashing of part a of the problem set to birthday bounds, and Problem 2 predicts the node count of the trie in Trees and tries, longest-prefix match. Looking forward, Bloom::with_rate(n, p) in the A Bloom filter section of Algorithms computes mm and kk with Problems 20 to 22. The MinHash signatures of 128 values in 16 bands of 8 rows in Near-duplicate dedup: MinHash, LSH, union-find, and decontamination are analysed by Problems 15 to 18. And the cost and roofline of the tiled matmul in Cache-blocked, packed, batch-invariant matmul in C use the recurrence of Problem 28.

  • Leskovec, Rajaraman, and Ullman, Mining of Massive Datasets, chapter 3 (MinHash, LSH).
  • Broder and Mitzenmacher, “Network Applications of Bloom Filters: A Survey” (2004).
  • Graham, Knuth, and Patashnik, Concrete Mathematics, chapter 7 (generating functions).
  • Full binary tree: a rooted tree in which every node has 0 or 2 children; it has one fewer internal node than leaves.
  • Inclusion-exclusion: counting a union by alternately adding and subtracting the sizes of intersections.
  • Birthday bound: the observation that kk keys in mm buckets start to collide at k≈mk \approx \sqrt m.
  • Jaccard similarity: ∣A∩B∣/∣A∪B∣\lvert A \cap B \rvert / \lvert A \cup B \rvert.
  • MinHash: estimating Jaccard similarity by how often the minima of random permutations agree.
  • LSH banding: splitting a signature into bb bands of rr rows so that pairs agreeing on some whole band become candidates.
  • Bloom filter: a bit array with kk hashes per key that never misses an inserted key and has a tunable false-positive rate.
  • Recurrence: a definition of a sequence in terms of its earlier terms.
  • A tree on nn nodes has n−1n - 1 edges, and a trie stores each shared prefix once, so its size is one more than the number of distinct prefixes (Problems 1, 2, 6).
  • Collisions arrive at about m\sqrt{m} keys, not mm: a 32-bit hash is likely to collide after about 77 000 keys (Problems 11, 12).
  • One random permutation’s minimum agrees on two sets with probability exactly their Jaccard similarity, and banding b×rb \times r MinHash rows turns that into an S-shaped candidate probability with its threshold near (1/b)1/r(1/b)^{1/r} (Problems 14, 16 to 18).
  • A Bloom filter with m/nm/n bits per key is best with k=(m/n)ln⁡2k = (m/n) \ln 2 hashes, which sets half its bits and gives a false-positive rate of 2−k2^{-k} (Problems 20 to 22).
  • Divide-and-conquer costs follow from their recurrences: 2T(n/2)+n2T(n/2) + n is nlog⁡2nn \log_2 n, and 8 half-size products cost n3n^3 (Problems 23, 28, 29).
  • Model proofs for Problems 6, 14, and 29 are also in course/solutions/solve/S-M06b/.