Randomness as a Resource
What can an algorithm do with coin flips that it cannot easily do without them?
The part opens with the top twenty words of the thirty novels counted twice: by Part 17's exact hash table, and by a sketch that keeps thirty-two candidate words in about eighteen kilobytes of program data. It separates Las Vegas algorithms, always right with a random running time, from Monte Carlo ones, and shows how independent repetition shrinks a one-sided error to 2^-k. Freivalds checks a matrix product with three matrix-vector products, Schwartz and Zippel test a polynomial identity at random points, Karger finds a minimum cut by contracting random edges, and Miller and Rabin repair Fermat's test after 561 fools it. Random walks solve 2-SAT, two choices flatten the fullest bin, and Bloom filters, reservoirs, Count-Min, HyperLogLog, the AMS sketch and MinHash answer questions about streams in little memory. The Job is rebuilt on a Count-Min sketch for ledger row 9, and a sweep of twenty hash seeds shows that its exact answer was not guaranteed. The part then turns to where the coins come from: the probabilistic method, conditional expectations, RANDU's fifteen planes, and the open question whether P equals BPP.
What you need. Discrete probability: independence, expectation, Markov's inequality, and arithmetic modulo a prime.
- Mathematics, ideas and history
- Freivalds, Schwartz–Zippel, Karger, Miller–Rabin, two choices, Bloom filters, streaming sketches, HyperLogLog, LSH, the probabilistic method
- What we build or compute
- the Job in kilobytes; RANDU's planes
What you will be able to do
Degree
- Tell a Las Vegas algorithm from a Monte Carlo one, and compute how many independent rounds bring a one-sided error below a target.
- Run Freivalds' check and the Miller-Rabin test by hand on small inputs, and say what a pass does and does not certify.
- Size a Bloom filter for a target false-positive rate, and explain why it never gives a false negative.
Graduate
- Prove Freivalds' bound by deferred decisions and the Schwartz-Zippel lemma by induction on the number of variables.
- Derive Karger's 2/(n(n-1)) bound and the corollary that a graph has at most n-choose-2 minimum cuts.
- Derive the Count-Min guarantee for one fixed item and the variance of the AMS estimator from four-wise independent signs.
Research
- State the hardness premise under which P equals BPP, and explain why a deterministic identity test would imply circuit lower bounds.
- Use the expectation argument and the local lemma to prove that an object exists, and say what Moser and Tardos add.
Industry
- Choose between an exact table, Misra-Gries, Count-Min and HyperLogLog for a stream, stating the guarantee each one actually has for the implementation's hashes.
- Explain why a simulation generator such as the Mersenne Twister must not be used for secrets, and what RANDU did to three-dimensional samples.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 22 min · Graduate 48 min · Research 51 min · Industry 30 min.
- 0The top words in kilobytesDegree1 min
- 1Las Vegas and Monte CarloDegree2 min
- 2Checking a product with a coinDegree3 min
- 3Is this polynomial zero?Graduate3 min
- 4A minimum cut by contractionDegree3 min
- 5Probable primes and primality testsDegree3 min
- 6Random walks that solve SATGraduate2 min
- 7Balls into bins, and the power of two choicesDegree3 min
- 8Bloom filtersDegree4 min
- 9Streams: one pass, little memoryGraduate5 min
- 10The Job in kilobytes: ledger row 9Industry5 min
- 11Counting distinct things: HyperLogLogGraduate2 min
- 12Sketching the second momentGraduate2 min
- 13Near-duplicates: MinHash and LSHIndustry3 min
- 14The probabilistic methodGraduate2 min
- 15Removing the coins, and where they come fromGraduate3 min
- 16Frontier: does randomness help?Research3 min
- Recap, problems, and where this comes backAll tracks2 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.
The top words in kilobytesDegree1 min
Here are the most common words in the thirty novels, counted twice. On the left, Part 17's exact hash-table program. On the right, this part's sketch with thirty-two retained word candidates. For this corpus and fixed hash seed, all twenty words and counts agree. The modeled data structures shrink from almost two megabytes to about eighteen and a half decimal kilobytes. These are program data, not total process memory. The sketch does not keep the whole vocabulary. Hash collisions can change its answer. By the end we will measure how often the complete answer survives a sweep of twenty hash seeds.
That is the theme of this part: a coin flip can stand in for cleverness. With exact arithmetic we can check a claimed matrix product with a quadratic number of arithmetic operations. We can find a network's minimum cut by contracting random edges. We can rapidly reject composite three-hundred-digit numbers and generate probable primes, useful for the RSA construction in Part 30. And we can estimate stream statistics using much less storage. The mathematical guarantees depend on the stated randomness model; the fixed hash implementations also need empirical checks.
1Las Vegas and Monte CarloDegree2 min
An algorithm that flips coins can gamble in two ways. A Las Vegas algorithm is always right, while its running time depends on the coins. Randomized quicksort, from Part 16, is one. A Monte Carlo algorithm has a prescribed running-time bound and may return a wrong answer. A proved error bound can often be reduced by independent repetition. In these theorems the input is fixed arbitrarily. The probability is over the algorithm's own coins, not over a distribution of convenient inputs.
Here is a Las Vegas algorithm at work: quicksort with random pivots on 2,000 keys, run 400 times. Each bar counts the runs that made that many comparisons. The average was 24,761, and Part 16's exact formula predicts 24,730. The runs spread by about 1,339 either side, and the slowest made 30,234. The worst case, about two million comparisons, is possible in principle, but it needs a long run of terrible pivots, and its probability is far too small to observe. And every single run sorted the keys correctly. Only the time was a gamble.
Even a one-half false-acceptance bound can be useful. For Freivalds' test, rejection certifies a wrong product; a fixed wrong product passes with probability at most one half. Repeat with fresh independent coins, accepting only if every round passes. False acceptance is at most two to the minus k. This is not a posterior probability that an accepted product is wrong. Ten rounds give at most one in a thousand, and forty about one in a trillion. With two-sided error and a fixed correctness probability p above one half, take the majority of independent runs. Hoeffding's inequality gives an error bound exponential in minus k times the square of the advantage p minus one half.
2Checking a product with a coinDegree3 min
Someone hands you square matrices A, B and C, claiming C equals A B. Classical multiplication uses a cubic number of arithmetic operations; Part 19 discussed faster asymptotic methods. Here we count arithmetic operations, not bit operations. Freivalds' 1977 test picks a uniform independent zero-one vector r. Compute B r, then A times that, and also C r: three quadratic matrix-vector products. Work over a field, or with exact integers. Our instrument prevents overflow; its floating benchmark uses integers small enough that every intermediate is exact. Different vectors certify that C is wrong. Equal vectors merely pass this round. How likely is a fixed wrong product to pass?
Suppose C is wrong. Then the difference D, A B minus C, is not the zero matrix. Some entry, d i j, is nonzero, and the test passes only if D r is the zero vector, so in particular only if its i-th entry is zero. That entry is d i j times r j, plus a sum s over the other coins. Imagine flipping every coin except r j first. The coins are independent, so this changes nothing, but now s is a fixed number. For the entry to vanish, r j must equal minus s over d i j: one particular value. At most one of the two outcomes of r j can do that. So a wrong C passes with probability at most a half, whatever A, B and C are, and k independent rounds let it through with probability at most two to the minus k. The trick of revealing the coins in a convenient order is called the principle of deferred decisions, and we will use it again.
On this shared host, with matrices of size 2000. The leading operation counts are sixteen billion floating-point operations for the full product and twenty-four million for the three matrix-vector products. We report the minimum of three runs; validate every result outside the timer; and exclude generation of the reused test vector. The observed speed ratio is 103, with one configured BLAS thread. Operation counts alone do not predict elapsed time, and this experiment does not isolate a hardware cause. We also corrupted one product entry and used four thousand independent trials per row. The displayed fractions fluctuate around their probabilities and may exceed the probability bound through sampling noise. For a single erroneous entry, exactly one coin determines acceptance, so the theoretical bound is tight. The many-error example passed no observed trials; that is a finite observation, not a zero-probability theorem.
3Is this polynomial zero?Graduate3 min
Freivalds' check is a special case of a general fact. Let p be a nonzero formal polynomial of total degree d over a field. Choose each variable independently and uniformly from the same finite subset S of that field. Then the probability that p evaluates to zero is at most d divided by the size of S, capped at one. This is the Schwartz–Zippel lemma, also associated with DeMillo and Lipton, around 1980. In one variable, a nonzero degree-d polynomial has at most d roots. In several variables, write p in the first variable, with highest power k. Its leading coefficient has total degree at most d minus k. Inductively that coefficient vanishes with probability at most d minus k over the size of S; otherwise the remaining univariate polynomial has at most k roots. Adding the two bounds proves the claim.
Here is a claimed identity: the product x minus y, times y minus z, times z minus x, against an expansion. Instead of expanding, substitute random numbers and compare. We did this twenty thousand times for each size of S. The claim is false: one sign is wrong, so the two sides differ by two x z squared, a polynomial of degree three. It vanishes only when x or z is zero, which is why the agreement rates sit a little under the lemma's bound of three over S. With a thousand values, one test in five hundred is fooled; twenty tests are fooled with probability below ten to the minus fifty. The idea scales. The determinant of an eight by eight Vandermonde matrix equals a product of differences, a polynomial with forty thousand terms if you expand it. Evaluating both sides at fifty random points modulo a large prime took a fraction of a millisecond each, and they agreed every time.
One more fingerprinting idea. Alice and Bob want to compare copies of the novel corpus without transmitting it all. Encode the byte string as a big-endian integer with a leading one byte. The sentinel preserves leading zero bytes and makes the encoding injective. Alice sends a sixty-one-bit prime p and her residue in sixteen bytes; Bob compares his own residue. The displayed experiment uses one fixed prime. Our altered copy flips one bit. Both residues are checked against independent blockwise Horner evaluation; the displayed time is a local observation. Distinct encodings collide only when p divides their nonzero difference. For a uniformly sampled prime in the stated interval, count possible large prime divisors and divide by the number of eligible primes. The displayed prime-count approximation is an asymptotic heuristic, not a certified finite upper bound. Independent modulus choices multiply their actual collision probabilities. Part 21 develops rolling string fingerprints.
4A minimum cut by contractionDegree3 min
The analysis is as short as the algorithm. Fix a connected undirected multigraph with positive minimum-cut size k, and one minimum cut C. Every vertex has at least k edges, because otherwise the edges around that one vertex would be a smaller cut. So there are at least n k over two edges, and the first random edge lands in C with probability at most two over n. Contracting never creates a smaller cut, so the same argument works at every step, with n minus one vertices, then n minus two, and so on. C survives to the end if it survives every step. Write the product out, and almost everything cancels: the success probability is at least two over n times n minus one, one over n choose two. There is a free corollary. A specific minimum cut is the output with at least that probability, and different cuts are different outcomes, so no connected graph has more than n choose two minimum cuts.
We ran the contraction twenty thousand times on the two-cluster graph. Each bar counts the runs that ended with a cut of that size. The minimum cut came out in 13% of runs. The lower bound promised at least one in a hundred and twenty, under one percent, so the observed rate on this graph is about fifteen times the lower bound. The bound is a worst case, and repetition does the rest: run it n choose two times log n times and keep the smallest cut, and it is wrong with probability at most one over n. The worst case is real. In a ring of ten vertices, any two of the ten edges form a minimum cut, which makes forty-five of them, exactly n choose two. The runs found all forty-five, each about once in forty-five tries, so here the bound is exact.
5Probable primes and primality testsDegree3 min
Part 30 will need prime numbers three hundred digits long, and lots of them. Testing one by trial division would take ten to the hundred and fifty divisions. Fermat's little theorem gives a shortcut. If n is prime, then for every a not divisible by n, a to the n minus one is one, modulo n. So if we find an a where it isn't, n is certainly composite. Two to the ninetieth, modulo ninety-one, is sixty-four, so ninety-one is composite, and we learned that without finding a factor. But some bases lie. Three to the ninetieth is one modulo ninety-one, as if ninety-one were prime. Each test is cheap: repeated squaring computes the power with about one squaring per bit of n.
Worse, some composites fool every coprime base. Here are the bases from one to five hundred and sixty for n equals five hundred and sixty-one, which is three times eleven times seventeen. Every base that shares no factor with it, all 320 of them, passes Fermat's test. Alwin Korselt explained why in 1899: this happens exactly when n is squarefree and p minus one divides n minus one for each of its prime factors p. Five hundred and sixty is divisible by two, ten and sixteen. Robert Carmichael found the first examples in 1910. There are 43 below a million, and in 1994 Alford, Granville and Pomerance proved there are infinitely many. Fermat's test needs repairing.
Gary Miller in 1976 and Michael Rabin in 1980 found the repair. Modulo a prime, the only square roots of one are one and minus one, because x squared minus one factors as x minus one times x plus one, and in a field a product is zero only if a factor is. Write n minus one as a power of two times an odd number d, and compute a to the d, then keep squaring until we reach a to the n minus one. For a prime, the sequence is all ones, or it hits minus one somewhere before the first one. Watch five hundred and sixty-one with base two: two hundred and sixty-three, one hundred and sixty-six, sixty-seven, then one. Sixty-seven squares to one but isn't plus or minus one: a square root of one that no prime can have. Fermat was fooled; this test isn't. Rabin proved that for every odd composite, at most a quarter of the bases in our stated range, one through n minus one, lie. Five hundred and sixty-one has only 10. Searching every odd composite below twenty thousand, the worst was nine, with exactly a quarter, so the bound can't be improved. Forty random bases give false acceptance of any fixed odd composite at most four to the minus forty, about ten to the minus twenty-four.
6Random walks that solve SATGraduate2 min
A 2-SAT formula is an and of clauses, each an or of two literals. Part 18 solved it exactly, with strongly connected components of the implication graph. Christos Papadimitriou analyzed a much dumber method in 1991. Start anywhere. While some clause fails, pick one, and flip one of its two variables, chosen by a coin. It uses no structure at all. Why should it ever finish?
Fix one satisfying assignment, x star, and let D be the number of variables where our assignment differs from it. A clause that fails has both its literals false, but x star makes at least one of them true, so we disagree with x star on at least one of the two variables. Flipping a random one of the two moves D one step closer to zero with probability at least a half. So D does a random walk on the line from zero to n, pushed toward zero at least as often as away. This is the gambler's ruin. From any start, the expected time to reach zero is at most n squared. Here is one walk, starting eight steps away. It took 178 flips. We may even stop sooner, at some other solution. So run two n squared steps. If the formula is satisfiable, Markov's inequality says we fail with probability at most a half, and repetition does the rest. The bound is for the worst formula: on random satisfiable ones, with up to three hundred and twenty variables, the walk needed only about two flips per variable.
7Balls into bins, and the power of two choicesDegree3 min
Throw balls into bins at random. How full does the fullest bin get? This question decides how well a hash table's chains, Part 17, or a server farm's queues are balanced. On the left, each of twenty-four balls goes into one random bin of twelve. On the right, each ball looks at two random bins and goes into the emptier one. The same random numbers drive both sides: the left uses the first choice, the right uses both. One choice leaves some bins empty and piles others high. Two choices are strikingly even.
Now with n balls and n bins, for n from a thousand to a million. With one choice the fullest bin holds about log n over log log n balls; the column beside it is that formula, which is right only up to a factor that tends to one very slowly, so the measured loads are higher. With two choices the fullest bin holds about log log n over log two, plus a constant. For a million balls: ten against four. At a million, the one-choice loads approximately follow a Poisson law, a fraction e to the minus one over k factorial of the bins holding k, with 9 unlucky bins holding 8. With two choices nothing went above 4. A tiny change in the rule, an exponential change in the result. This is the power of two choices, from Azar, Broder, Karlin and Upfal in 1994.
Why? Let beta i be the number of bins holding at least i balls. A ball lands at height i plus one only if both its bins already hold at least i, with probability about beta i over n, squared. So each height's fraction is about the square of the one below. Squaring collapses fast: a quarter, a sixteenth, one in two hundred and fifty-six, one in sixty-five thousand, below one over n after about log log n steps. With one choice there is no squaring, only one over k factorial. With d choices the load is log log n over log d, so most of the gain is in the second choice. Load balancers use exactly this rule, and cuckoo hashing gives every key two homes.
8Bloom filtersDegree4 min
In 1970 Burton Bloom asked how to test membership in a set using far less memory than the set itself, if we accept an occasional wrong yes. Take an array of bits, all zero, and three hash functions. To add a word, hash it three times and set those three bits. Here go six words from Moby-Dick. The words themselves are not stored anywhere. Only bits remain.
To ask whether a word is in the set, check its three bits. Dog: one of its bits is zero, so dog was certainly never added. Boat: also a zero, certainly not. Ocean: all three of its bits are set, by whale, so the filter says yes, wrongly. A false positive. Deck: also yes, its bits set by harpoon and Queequeg. A Bloom filter never says no to a word that is in the set, but it sometimes says yes to one that isn't. How often?
Suppose we add n words to m bits with k independent uniform hash placements in an ideal model. A particular bit is missed by all k n hashes with probability one minus one over m, to the k n, which is about e to the minus k n over m. A word that was never added is a false positive if all k of its bits happen to be set: probability about one minus that, to the k. There is a balance. Too few hash functions give too few membership probes; too many fill the bit array and make each probe less selective. Calculus gives the best k, m over n times log two, and at that continuous optimum the modeled occupancy is one half. The error is then about 0.6185 to the power m over n. Every extra bit per word divides the error by about 1.6, and ten bits per word give about one percent, under this approximation, with integer hash counts rounded and finite dependencies treated separately. Our double-hash implementation is measured against the model rather than certified by it.
Now a real one: all 57,895 distinct words of the novels, ten bits per word, queried with a hundred thousand random strings that are not words of the novels. The purple curve is the formula, and the green dots are what we measured for each number of hash functions. At the best k, seven, 0.81 percent of the non-words slipped through, against a predicted 0.82, and almost exactly half the bits were set. With sixteen bits per word the rate falls to one in two thousand. The packed filter takes about seventy-one kibibytes, while just the letters of the words take about four hundred and forty-two kibibytes. Every inserted word was checked; none was missed. Counting filters allow deletions, cuckoo filters do better at low error rates, and nearly every log-structured database keeps a Bloom filter per file to skip disk reads, as Part 34 will show.
9Streams: one pass, little memoryGraduate5 min
Part 17 kept every distinct word of the novels, almost fifty-eight thousand. What if we can't afford that? In the streaming model the items go by once, can't be stored, and memory is far smaller than the stream, often smaller than the number of different items in it. Routers, sensors, logs and query planners live in this world.
First, a fair sample. We want k items chosen uniformly from the stream, but we don't know how long it will be. Reservoir sampling, as Jeffrey Vitter described it in 1985: keep the first k. When the i-th item arrives, keep it with probability k over i, throwing out a random one of the k. By induction, every item seen so far is in the sample with probability exactly k over i. An item stays when the next one arrives unless the newcomer is kept and picks its slot, and the arithmetic turns k over i into k over i plus one. We drew five items from a hundred, fifty thousand times: every item was picked close to the expected two thousand five hundred times. And here are eight words drawn uniformly from all four million six hundred thousand in the novels, in a single pass.
Next, the frequent items, the Job's own question. Jayadev Misra and David Gries gave a deterministic method in 1982, with k minus one counters. A word that has a counter adds one. A new word takes a free counter. A new word with no free counter subtracts one from every counter, and the counters that reach zero are freed. Each subtraction cancels k words at once, the new one and one from each counter, so it can happen at most n over k times. So every count is low by at most n over k, and any word more frequent than n over k must survive. With ninety-nine counters on the novels, n over k is about forty-six thousand. The thirteen words above that all survived, each undercounted by about thirty-nine thousand, and words below it may vanish. A second pass, counting only the survivors, makes the counts exact. But the estimates themselves are poor. Can coin flips do better?
Graham Cormode and S. Muthukrishnan's Count-Min sketch, from 2005, keeps a small table: d rows of w counters, with an independent hash function for each row. To add a word, hash it once per row and add one to each of those counters. To estimate a word's count, look at the same d counters and take the smallest. Every counter holds the word's true count plus the counts of whatever other words collided with it there. Collisions only ever add, so the estimate is never too low, and the minimum picks the row with the fewest collisions.
How large can the error be in the standard insertion-only Count-Min model? In one row, use a hash family with collision probability at most one over w for each pair. The expected excess for a fixed queried item is at most N over w. Markov bounds excess above e times that by one over e. With independently chosen row hashes, all rows must fail, so the probabilities multiply. Choose width at least e over epsilon and depth at least the natural log of one over delta. Each fixed item then has additive error at most epsilon N with probability at least one minus delta. This is not a simultaneous guarantee for every item without an additional union bound. The counter count depends on epsilon and delta; each counter still needs enough bits for N. The corpus experiment has a comparison level of 12,273 and mean excess about 968. Its concrete polynomial and double hashes are an empirical implementation, not a proof that the independent-row theorem applies. The reported fraction across words is not a failure probability over independent hash choices.
10The Job in kilobytes: ledger row 9Industry5 min
Now the Job itself, rebuilt so that it never stores the vocabulary. A Count-Min sketch of four rows of 1021 counters estimates every word's count. Only thirty-two words are kept, candidates for the top twenty, in a heap ordered by estimate; a word replaces the weakest when its estimate beats it. A table of a hundred and twenty-eight slots finds a word among the candidates, and an evicted one is deleted by shifting its neighbours back, Knuth's Algorithm R. Estan and Varghese's conservative update raises only the counters at the minimum: it still never undercounts, but it adds far less to other words. And double hashing gives all four row positions from one division per word.
Here is the function that runs once per word, compiled by Part 13's compiler. First the four counter positions, each the last plus the step g, wrapped by a subtraction instead of a division. The estimate is the smallest of the four counters, and only the counters equal to it are raised. Then the test that makes the program cheap: if the heap is full and this word's estimate can't beat the weakest candidate, we are done. Almost every word in English stops here. A word that is already a candidate gets its new estimate and moves down the heap. Anything else joins, or replaces the weakest candidate.
What does the program remember? The sketch contains four-byte counters; the retained candidates, letters, heap and index slots add storage. The complete global-data block contains 18,588 bytes, about eighteen and a half decimal kilobytes. This excludes the host interpreter, input corpus, code and stack. Part 17's modeled exact table stores every distinct word and uses 1.9 decimal megabytes. This comparison is about a hundredfold data-storage reduction. A 150-kilobyte passage was traced through Part 9's cache model: 295 distinct data lines, at most 6 in one eight-way set. We extrapolate its stalls under the fixed-working-set model; we did not trace every full-corpus cache access.
The ledger gets its ninth row. The emulator executed all 1,069,411,435 instructions on the complete corpus, about 43 per byte. The full output matched both the sketch reference and the exact top-word counts for this fixed seed. The displayed processor time is a projection: full instruction count divided by IPC from three short passages, plus sampled cache stalls, at the ledger's clock frequency. The sampled core includes the sketch's comparison dependencies. It is not a whole-corpus core simulation. Cache costs for both versions also belong to their stated trace and projection models. Read row nine as a modeled time-storage tradeoff, alongside the independently measured complete emulator runtime. The emulator's wall time and the projected processor time are different quantities.
Was the exact answer luck? We reran the algorithm in C with twenty fixed polynomial-hash multipliers and several sketch sizes. This is an empirical seed sweep, not a universal-hash proof. At four rows of 1021 counters, five of twenty seeds gave exactly the correct top twenty and counts. The program's seed was one. Average word overlap was 19.1, with eighteen the minimum. One rare intruder was , occurring , but estimated near fifty-nine thousand. Collisions need not respect a word's real frequency. The observed exact shares increased at the wider configurations shown. Storage and per-update work are bounded by the design, while complete top-twenty correctness has no theorem here. A single item's Count-Min bound does not certify the retained candidate set. All true top words survived among the thirty-two candidates in these twenty runs. A second pass counting those candidates would repair these runs. For a new stream, missing a true top word would still defeat that repair.
11Counting distinct things: HyperLogLogGraduate2 min
How many different words are in the novels? An exact general-purpose set can grow with the distinct items. Flajolet and Martin proposed a much smaller randomized summary in 1985: hash each item to random-looking bits and examine its leading zeros. Repeated items reuse their hash and do not change the maximum. In an ideal independent-bit model, a rank of rho, meaning rho minus one zeros followed by a one, has probability two to the minus rho. The largest observed rank therefore gives a noisy scale for cardinality. Remember the largest rank. Its storage is logarithmic in the hash bit width; finite hashes eventually saturate and collide. Five bits do not cover every possible stream. A single extreme hash makes the estimate unstable, so we use many registers.
The cure uses many registers. The leading hash bits choose one of m registers. Store the largest rank of the remaining suffix in that register. Here are sixty-four registers after hashing the novel vocabulary. HyperLogLog, from Flajolet and colleagues in 2007, combines powers of those ranks through a bias-corrected harmonic estimate. The familiar one point zero four over root m is a leading relative standard-error scale under the hashing model, not a guaranteed relative-error interval. When many registers are zero, our implementation switches to the small-range empty-register correction. The actual register vector is checked against an independent scalar implementation.
12Sketching the second momentGraduate2 min
Counting distinct items and counting the stream's length are two cases of one family. The p-th frequency moment is the sum, over items, of each item's count to the power p. F zero is the number of distinct items, the last chapter. F one is the length of the stream, which one counter tracks. F two, the sum of the squared counts, measures how concentrated the stream is. It is the number of rows when a database joins a table with itself on that column, and it jumps when a network sees a flood of identical packets. For the novels it is a hundred and seventy-seven billion, and the word the contributes thirty percent of it on its own. Can we estimate F two without counting every word?
Alon, Matias and Szegedy gave a foundational streaming result in 1996. Assign every item a consistent random sign, plus or minus one. On each arrival add its sign to counter Z. In the worked six-arrival stream, the counter ends at two, so this one squared estimate is four; the true second moment is fourteen. Algebraically, Z squared is the sum of squared frequencies plus cross terms involving two different signs. Unbiased pairwise-independent signs make those cross terms vanish in expectation. Averaging over all eight sign assignments in this three-item example gives exactly fourteen. Four-wise independence gives variance at most twice F two squared. Averaging k independent counters gives relative standard deviation at most the square root of two divided by k. Chebyshev bounds a chosen error threshold; independent groups and their median amplify confidence. This is the median-of-means construction: a standard-error scale becomes a probability statement only after specifying the threshold and group count.
13Near-duplicates: MinHash and LSHIndustry3 min
Search engines, plagiarism detectors and the people who clean training data for language models all need to find documents that are nearly the same. Represent a passage by its shingles, every run of five consecutive words. Two passages are as alike as the share of shingles they have in common: the Jaccard similarity, the size of the intersection over the size of the union. These two lines, from two versions of the same letter in The Count of Monte Cristo, share four of their ten distinct shingles, because changing one word breaks every shingle that contains it. The novels have thirty-four thousand paragraphs of forty words or more. Comparing every pair means almost six hundred million comparisons of sets.
Broder popularized MinHash for document resemblance in 1997. First consider an ideal uniform random permutation of the distinct shingles. The two minimums agree exactly when the first element of their union belongs to the intersection. Every union element is equally likely to be first. Therefore agreement probability is exactly Jaccard similarity in this ideal model. With one hundred independent ideal rows, the agreement fraction has worst-case standard error five hundredths. This is not a guaranteed plus-or-minus-five-hundredths interval. Our fast affine hashes are an approximation to minwise randomness and receive empirical validation; their Jaccard identity is not exact by this proof.
Signatures are short, but all paragraph pairs are still numerous. Split each signature into twenty bands of five rows and index each band. A pair becomes a candidate if any band agrees exactly. Under independent ideal minwise rows, one band matches with probability J to the fifth, and at least one matches with probability one minus one minus J to the fifth, raised to the twentieth. This is a smooth probability curve, not a hard threshold. The six hundred planted edited copies compare empirical candidate rates with that ideal curve. The affine-hash implementation can depart from the independent ideal model.
Now the novels. We use collision-free dictionary IDs for whole five-word shingles. The producer records actual signature and banding times, yielding 3 candidate pairs. Timing includes the stated stages only. An exhaustive inverted index includes every posting list, even common shingles. Every pair with positive intersection is checked using exact integer intersection and union counts. Seven pairs have Jaccard similarity at least one fifth. Recall is reported with its threshold: finding two of two pairs above one half does not mean finding all seven above one fifth. The table gives exact scores and candidate flags for the full seven-pair inventory. Broader applications include web-page similarity and training-data deduplication. SimHash is a different locality-sensitive sketch; practical systems must also select thresholds and verify candidate pairs.
14The probabilistic methodGraduate2 min
Colour every edge of a complete graph red or blue. Frank Ramsey proved in 1930 that if the graph is big enough, some k vertices have all their edges the same colour, whatever you do. With four vertices, seventeen are not enough. On the left, a random colouring of the complete graph on seventeen vertices: on average it has 74 groups of four in a single colour. On the right, a clever colouring, blue exactly when the difference of the two vertices is a square modulo seventeen, has none at all. Eighteen vertices always contain one, so the Ramsey number R of four, four is eighteen. Larger diagonal Ramsey numbers pose much harder questions. For growing k, random colorings provide a powerful existence proof.
In 1947 Erdős reversed the question. Color each edge independently by a fair coin. A particular set of k vertices is monochromatic with probability two to the one minus k choose two. Summing over all sets gives the expected number of bad cliques. If it is below one, some coloring has none, because an integer-valued nonnegative count cannot always be at least one. This yields an exponential lower bound on the Ramsey number, of scale two to the k over two. The table gives the finite values certified by this expectation calculation. Expectation below one proves existence; it alone does not imply almost every coloring works. Explicit constructions matching the random asymptotic scale remain a major challenge. Campos, Griffiths, Morris and Sahasrabudhe reported a base below four in 2023. A selected 2024 preprint by Gupta, Ndiaye, Norin and Wei, revised in 2026, reports base 3.8 with a lower-order exponent. These are dated source claims, not a complete latest-record survey. The exponential gap between upper and lower bounds remains large.
15Removing the coins, and where they come fromGraduate3 min
Can the coins be removed? Sometimes, mechanically. MAX-CUT splits a graph's vertices to maximize crossing edges. Finding the optimum is NP-hard. Independent fair sides cut each edge with probability one half, so the expected cut is m over two. The small worked graph has five edges and expectation two and a half. Fix vertices one at a time, choosing the side with the larger conditional expectation. Edges to unassigned vertices still contribute one half each. The two branch values average to the current expectation, so the better branch cannot lower it. Our worked trace rises to a deterministic cut of four. It does not claim the optimum in general. The separate sixty-vertex experiment compares the deterministic result with two thousand sampled random cuts. Its measured values are shown below the worked proof.
There is a second way. The MAX-CUT argument looks at one edge at a time, which involves only two vertices' coins. So the coins don't need to be fully independent, only pairwise independent. Pairwise independent bits are cheap. Pick k truly random bits s, and give vertex i the parity of the bits of s where i's binary expansion has a one. Any two of these bits are independent and fair, so k coins become about two to the k. With only about n possible seeds, we can try every one, deterministically, and keep the best cut: the expectation guarantees one of them reaches m over two. Limited independence, small-bias spaces and walks on expander graphs, Part 56, are the general tools for stretching a few random bits a long way.
The probabilistic guarantees use ideal randomness, with limited independence sufficient for some arguments. Our reproducible experiments use seeded generators. In the 1960s and 70s, many scientific programs used IBM's RANDU: multiply by sixty-five thousand five hundred and thirty-nine, modulo two to the thirty-one. Here are two and a half thousand consecutive triples of its outputs, plotted as points in a cube. They look random. Now turn the cube slowly. A projection can hide structure: watch how a cloud of points collapses into evenly spaced sheets as the viewpoint changes. The multiplier is two to the sixteen plus three, and squaring it shows that each output is six times the previous one minus nine times the one before, modulo two to the thirty-one. So nine u minus six v plus w is always a whole number, and every point lies on one of just 15 planes. Any simulation that sampled points in space with RANDU was sampling fifteen sheets. Donald Knuth called it truly horrible.
16Frontier: does randomness help?Research3 min
Several problems now have deterministic alternatives. AKS gave polynomial-time primality in 2002. Reingold gave logarithmic-space undirected connectivity in 2005. Kawarabayashi and Thorup gave a deterministic near-linear minimum-cut result for simple graphs in 2015; Henzinger, Li, Rao and Wang reported the weighted-graph extension in 2024. Fenner, Gurjar and Thierauf's 2016 bipartite perfect-matching result is quasi-NC squared: quasi-polynomial size and polylogarithmic depth, not an NC algorithm. These are different models and individual achievements. Is there a general route for bounded-error decision algorithms?
There is a conditional route. BPP consists of decision problems solvable in polynomial time with error at most one third on every input. For an input length, imagine an efficiently computable generator with logarithmic seed length that fools every circuit of the required polynomial size to sufficiently small additive advantage. Its output supplies the algorithm's polynomially many random bits. Enumerate all seeds and take the majority of acceptance decisions. The seed count is polynomial, and fooling preserves the acceptance gap. This is a decision simulation, not a promise to reproduce arbitrary sampling or search tasks. Nisan–Wigderson and Impagliazzo–Wigderson connect such generators to circuit hardness. The 1997 sufficient premise is a language in E, deterministic time two to order n, requiring exponential-size Boolean circuits. Under that premise, P equals BPP. Arbitrary exponential-time hardness is not the same stated premise. Hard functions can produce pseudorandom bits for bounded computations. The unconditional equality P equals BPP remains open.
Streaming space bounds require a model. For insertion-only distinct counting over a universe of size n, Kane, Nelson and Woodruff's 2010 result uses order epsilon to the minus two plus log n bits, with a fixed constant success probability such as two thirds. Raising confidence has additional cost. Bounds for other moments and point queries depend on the moment, update model, approximation and failure probability. Exact unrestricted top-item recovery can require space growing with the input universe; no theorem here makes our candidate heap exact. Communication reductions explain many lower bounds: if a tiny sketch solved the streaming problem, two parties could exchange it to solve a communication problem with a proved larger cost. Part 27 develops this argument.
Here is where things stand. Does P equal BPP, and can that be proved without first proving circuit lower bounds? Is there a deterministic polynomial-time test for polynomial identities? Can anyone write down a colouring of a complete graph that is as good as a random one? Explicit constructions improved dramatically after 2016, with two-source extractors, but still fall short. And can perfect matchings be found fast in parallel without coins, for every graph? This part's research problem takes the second.
Recap, problems, and where this comes backAll tracks2 min
What we built in this part. Las Vegas and Monte Carlo, and amplification. Freivalds' check and the Schwartz–Zippel lemma, with perfect matchings and fingerprints. Karger's random contractions. Miller–Rabin. Random walks for satisfiability, balls in bins and the power of two choices. Bloom filters, reservoirs, Misra–Gries and Count-Min, and the Job in eighteen kilobytes. HyperLogLog, the AMS sketch and MinHash. The probabilistic method, and the ways to remove the coins.
Where this comes back. Part 21 turns fingerprints into Rabin and Karp's string search, and Part 22 uses locality-sensitive hashing for nearest neighbours. Part 23 rounds linear programs at random, including MAX-CUT's famous 0.878. Part 27 develops BPP, hardness against randomness and the lower bounds for streams. Part 29 builds cryptographic generators, and Part 30 needs the big primes. Part 34's storage engines keep a Bloom filter per file; Parts 46 and 47 run sketches and SimHash in production; and Part 48's load balancers use two choices, while Part 56 builds the expanders.
Six problems, with worked arguments in the notes. The fifth is a design exercise: a Pebble HyperLogLog sketch using repeated halving, with finite-hash limitations. Its pseudocode has not been compiled or benchmarked as a finished program. The last is a research problem, marked with a star: general deterministic polynomial identity testing. Its solution is unknown, and the notes give a starting point.
Next time, the oldest data of all, text. Searching it efficiently leads to automata built from patterns, to indexes of every suffix, and to a reversible transform that sorts a book into compressible runs, so that we can search the novels while they stay compressed. And every git diff turns out to be a shortest path on a grid. Part 21, Strings.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Fingerprints become Rabin and Karp's string search in Part 21, and locality-sensitive hashing finds nearest neighbours in Part 22; Part 23 rounds linear programs at random; Part 27 develops BPP, hardness against randomness and streaming lower bounds; Part 29 builds cryptographic generators and Part 30 needs the large primes; Bloom filters return in Part 34's storage engines, sketches in Parts 46 and 47, two choices in Part 48 and expanders in Part 56.
Key results
The part's results in one place, for revision.
Try it
Lab 20 · Coins against their bounds
Let a wrong matrix product through Freivalds' check, contract a two-cluster graph to its minimum cut, count the bases that lie to Fermat and to Miller-Rabin, fill a Bloom filter at ten bits per word, and throw balls into bins with one and two choices; compare every rate with the bound or formula the part proves.
python -m videos.cs.labs 20
needs numpy, scipy, matplotlib · download lab20.py ·
source on GitHubFreivalds, one wrong entry passes 48.8%, 25.5%, 12.4%, 6.0% of trials after 1, 2, 3, 4 rounds (2^-k: 50%, 25%, 12.5%, 6.25%)
Karger, two clusters of 6 minimum cut found in 19.7% of 3,000 runs (bound 2/(n(n-1)) = 1.5%)
561 = 3 x 11 x 17 320 Fermat liars of 560 bases, 10 Miller-Rabin liars
worst odd composite below 2,000 n = 9: 25% of bases lie (Rabin: at most 25%)
Bloom, 10 bits per word, k = 7 false positives 1.16% (formula 0.82%); bits set 50.6%
50,000 balls, fullest bin one choice 7, two choices 3
Each bound is a statement about the algorithm's own coins on a fixed input: tight for Freivalds with one wrong entry, a worst case for Karger, and an idealized model for the Bloom filter's hashes.
The code (105 lines; it asserts its own result)
"""Lab 20: measure four randomized algorithms against their bounds: Freivalds, Karger, Miller-Rabin and a Bloom filter."""
from videos.coursekit import labs # noqa: I001 (must stay first: it lets explainer.cs import without manim)
import random
import numpy as np
from explainer.cs.algo import randomized as rz
TITLE = "Coins against their bounds"
GOAL = ("Let a wrong matrix product through Freivalds' check, contract a two-cluster graph to its minimum cut, count "
"the bases that lie to Fermat and to Miller-Rabin, fill a Bloom filter at ten bits per word, and throw balls "
"into bins with one and two choices; compare every rate with the bound or formula the part proves.")
TASKS = [
"Corrupt a whole row of C instead of one entry. The pass rate falls far below 2^-k: which step of the deferred-decisions proof is no longer tight?",
"Replace the two-cluster graph by a ring of ten vertices and tabulate which pair of edges each run cuts. How many different minimum cuts appear, and how often each?",
"Give the Bloom filter 16 bits per word, find the best k by experiment, and compare with (m/n) ln 2 and 0.6185^(m/n).",
]
def two_clusters(size=6, bridges=3):
"""Two complete graphs on ``size`` vertices joined by ``bridges`` disjoint edges: the minimum cut is the bridges."""
edges = [(a + off, b + off) for off in (0, size) for a in range(size) for b in range(a + 1, size)]
return 2 * size, edges + [(i, size + i) for i in range(bridges)]
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. Freivalds: one wrong entry passes k rounds with probability exactly 2^-k
n, trials = 30, 3000
A, B = rng.integers(-9, 10, (n, n)), rng.integers(-9, 10, (n, n))
C = A @ B
assert all(rz.freivalds(A, B, C, rounds=3, rng=rng) for _ in range(200)), "a correct product always passes"
bad = C.copy()
bad[rng.integers(n), rng.integers(n)] += 1
rounds = np.arange(1, 7)
passed = np.array([np.mean([rz.freivalds(A, B, bad, rounds=int(k), rng=rng) for _ in range(trials)]) for k in rounds])
for k, p in zip(rounds, passed):
q = 0.5 ** k
assert abs(p - q) < 4.5 * np.sqrt(q * (1 - q) / trials) + 1e-9, f"{k} rounds: {p:.4f} against {q:.4f}"
lab.row("Freivalds, one wrong entry", "passes " + ", ".join(f"{p:.1%}" for p in passed[:4])
+ " of trials after 1, 2, 3, 4 rounds (2^-k: 50%, 25%, 12.5%, 6.25%)")
# 2. Karger: the minimum cut of a two-cluster graph, against 2 / (n (n - 1))
nv, edges = two_clusters()
runs = 3000
cuts = np.array([rz.karger(nv, edges, rng) for _ in range(runs)])
success, bound = float(np.mean(cuts == 3)), 2 / (nv * (nv - 1))
assert cuts.min() == 3, "contraction never reports less than the minimum cut"
assert bound < success < 0.9, "at least the bound, and not always right"
lab.row("Karger, two clusters of 6", f"minimum cut found in {success:.1%} of {runs:,} runs (bound 2/(n(n-1)) = {bound:.1%})")
# 3. primes: 561 fools Fermat on every coprime base; Miller-Rabin's liars are at most a quarter
fermat = sum(rz.fermat_liar(a, 561) for a in range(1, 561))
strong = sum(rz.mr_liar(a, 561) for a in range(1, 561))
worst = max((sum(rz.mr_liar(a, m) for a in range(1, m)) / (m - 1), m) for m in range(9, 2000, 2)
if any(m % p == 0 for p in range(3, int(m ** 0.5) + 1, 2)))
assert fermat == 320, "every base coprime to 561 = 3 * 11 * 17 is a Fermat liar"
assert strong <= 560 // 4 and worst == (0.25, 9), "Rabin's quarter, attained at 9"
prime_rng = random.Random(seed)
assert rz.miller_rabin(2 ** 127 - 1, rng=prime_rng) and not rz.miller_rabin(2 ** 127 + 1, rng=prime_rng)
lab.row("561 = 3 x 11 x 17", f"{fermat} Fermat liars of 560 bases, {strong} Miller-Rabin liars")
lab.row("worst odd composite below 2,000", f"n = {worst[1]}: {worst[0]:.0%} of bases lie (Rabin: at most 25%)")
# 4. a Bloom filter at ten bits per word, against (1 - e^(-kn/m))^k
words = [f"word{i}".encode() for i in range(2000)]
others = [f"other{i}".encode() for i in range(5000)]
ks, measured, theory = [1, 2, 3, 4, 5, 6, 7, 8, 10, 12], [], []
for k in ks:
f = rz.Bloom(10 * len(words), k, key=b"lab20-%d" % seed)
for w in words:
f.add(w)
if k == 7:
assert all(w in f for w in words), "no false negatives"
full = float(f.bits.mean())
measured.append(float(np.mean([w in f for w in others])))
theory.append(rz.bloom_theory(len(words), f.m, k))
m7, t7 = measured[ks.index(7)], theory[ks.index(7)]
assert abs(m7 - t7) < 0.006 and m7 < measured[0] / 4, "k = 7 is near 0.82%, far below one hash"
assert abs(full - 0.5) < 0.03, "at the best k about half the bits are set"
lab.row("Bloom, 10 bits per word, k = 7", f"false positives {m7:.2%} (formula {t7:.2%}); bits set {full:.1%}")
# 5. balls into bins
one, two = rz.max_load(50_000, 1, rng), rz.max_load(50_000, 2, rng)
assert two <= 4 and one >= two + 2, "two choices flatten the fullest bin"
lab.row("50,000 balls, fullest bin", f"one choice {one}, two choices {two}")
lab.note = ("Each bound is a statement about the algorithm's own coins on a fixed input: tight for Freivalds with "
"one wrong entry, a worst case for Karger, and an idealized model for the Bloom filter's hashes.")
fig, ax = labs.figure(2, size=(11, 4.4))
ax[0].semilogy(rounds, passed, "o", color=labs.GOLD, ms=7, label=f"wrong product passed ({trials:,} trials each)")
ax[0].semilogy(rounds, 0.5 ** rounds, color=labs.BLUE, label="2^-k")
ax[0].set(title="Freivalds: false acceptance against rounds", xlabel="independent rounds k", ylabel="share of trials passed")
ax[0].legend()
grid = np.linspace(1, 12, 100)
ax[1].plot(grid, 100 * (1 - np.exp(-grid / 10)) ** grid, color=labs.PURPLE, label="(1 − e^(−kn/m))^k")
ax[1].plot(ks, 100 * np.array(measured), "o", color=labs.GREEN, label="measured, 5,000 non-words")
ax[1].axvline(10 * np.log(2), color=labs.MUTED, ls="--", label="k = (m/n) ln 2")
ax[1].set(title="Bloom filter, 10 bits per word", xlabel="hash functions k", ylabel="false positives (%)")
ax[1].legend()
lab.fig = fig
return lab
Now change it
- Corrupt a whole row of C instead of one entry. The pass rate falls far below 2^-k: which step of the deferred-decisions proof is no longer tight?
- Replace the two-cluster graph by a ring of ten vertices and tabulate which pair of edges each run cuts. How many different minimum cuts appear, and how often each?
- Give the Bloom filter 16 bits per word, find the best k by experiment, and compare with (m/n) ln 2 and 0.6185^(m/n).
Problems, with solutions
Try each problem before opening its solution.
-
Freivalds with q values. In exact arithmetic, let each coordinate of r be independent and uniform on q distinct field elements. Prove false acceptance ≤1/q for any fixed C≠AB, and show tightness when 0 is available.
Solution
Let D=AB−C and choose dᵢⱼ≠0. Fix every coordinate except rⱼ. The necessary equation dᵢⱼrⱼ+Σₖ≠ⱼdᵢₖrₖ=0 has at most one solution in the q-element set. Averaging over the fixed coordinates gives the bound. With D having a single nonzero entry, acceptance is exactly rⱼ=0, of probability 1/q. For integer choices 0,…,q−1 in a finite field, require distinct residues; otherwise this argument's q-value premise fails.
-
Near-minimum cuts. For fixed α≥1 and a graph with positive minimum cut k, show that the number of cuts of size at most αk is Oα(n²α). Count an unordered bipartition once.
Solution
Fix such a cut C, put β=2α and t=⌈β⌉. When i>t supervertices remain and C survives, at least ik/2 edges remain. Its next-step destruction probability is at most β/i. Contract to t vertices and choose a nontrivial remaining bipartition uniformly. The survival lower bound is
∏(1−β/i), i=t+1,…,n = Γ(n+1−β) Γ(t+1) / [Γ(t+1−β) Γ(n+1)] = Θα(n^−β).The final random choice adds the constant factor 1/(2ᵗ⁻¹−1). Distinct output cuts are disjoint outcomes, so there can be only Oα(nᵝ). The finitely many n≤t cases can be absorbed into the α-dependent constant. For integer β=t the product is 1/C(n,t); the argument can give nᵗ. The noninteger proof here claims an α-dependent constant, not an unproved leading constant of one. At α=1 the sharper chapter argument gives C(n,2).
-
Bloom sizing in the ideal approximation. Minimize f(k)=(1−exp(−kn/m))ᵏ over positive real k. Write p=exp(−kn/m), so log f=−(m/n) log p log(1−p). The symmetric product is maximized at p=1/2; differentiating gives a positive derivative before 1/2 and negative after. Thus k=(m/n)ln2 and f≈exp(−(m/n)(ln2)²). A target ε gives m≈n log₂(1/ε)/ln2. In a finite implementation choose a feasible integer k, round storage to bytes, and check hash behavior. This continuous optimum is not an exact finite double-hash false-positive theorem.
-
Weighted sampling without replacement. Let all weights wᵢ be positive and uᵢ independent uniform on (0,1). Keep the k largest uᵢ^(1/wᵢ). Define Tᵢ=−log(uᵢ)/wᵢ. These are independent exponential clocks with rates wᵢ. The first clock is i with probability wᵢ/Σⱼwⱼ. The memoryless property leaves independent exponential clocks for the unchosen items after each arrival, so the next item is proportional to remaining weight. This proves the ordered sequential sampling law. For k>1, an item's marginal inclusion probability is generally not k wᵢ/Σⱼwⱼ. Keep a max-heap of the k smallest times; use stable log computations and define finite-RNG tie rules.
-
Design sketch: HyperLogLog on Pebble. Design 256 registers with ranks found by repeated halving. This is an unexecuted sketch, not a compiled solution or a measured program.
Solution
Tokenize a word and compute a repeatable integer hash h. Select register h mod 256; let q=⌊h/256⌋ and compute one plus the trailing-zero count of q. Preserve the maximum for that register. If h has only 24 effective bits, q has only 16: cap the all-zero suffix consistently at rank 17. A rank loop cannot manufacture extra random bits. The proposed polynomial hash modulo 16,777,213 is neither uniform 24-bit randomness nor a proved independent family. Hash collisions, suffix saturation and correlation therefore need tests.
Combine registers with the HLL harmonic estimate and the appropriate small-range correction. A fixed-point implementation must prove its intermediate bounds and quantify rounding; a floating formula alone does not do that. Before reporting accuracy or instructions, compile the complete implementation, compare every register against an independent reference, run several seeds and corpora, and retain actual measurements. The ideal leading 1.04/√256≈6.5% standard error is a comparison scale, not a guarantee for this hash sketch.
-
★ Research: general deterministic polynomial identity testing. Decide whether an arithmetic circuit computes the zero formal polynomial in deterministic polynomial time. The general problem remains open. Specify the field, coefficient encoding, degree and whether the circuit is given explicitly or as an oracle. Kabanets–Impagliazzo's integer-PIT implication supplies a starting point. Restricted circuit classes and quasi-polynomial hitting sets do not settle the general question. A successful substitution on 20–40 vertex Tutte matrices is an experiment, not a universal deterministic matching construction.
Notes and sources
Sources
Selected primary sources and scope
These sources were checked at the abstract/introduction or metadata level for the stated claims; this is not an independent proof verification or a comprehensive current-record survey.
- Henzinger, Li, Rao and Wang, deterministic weighted minimum cut (2024).
- Fenner, Gurjar and Thierauf, bipartite perfect matching in quasi-NC (2016).
- Impagliazzo and Wigderson, E circuit hardness implies P=BPP (1997).
- Kabanets and Impagliazzo, PIT and circuit lower bounds (2004).
- Kane, Nelson and Woodruff, optimal distinct elements (2010): insertion-only universe [n], fixed constant success, O(ε⁻²+log n) bits; amplification costs are separate.
- Campos, Griffiths, Morris and Sahasrabudhe (submitted 2023, revised 2025): a diagonal Ramsey upper-bound base below four.
- Gupta, Ndiaye, Norin and Wei (submitted 2024, revised August 2026): selected reported upper bound 3.8^(k+o(k)).
Preview evidence belongs to the sequential QA ledger. Sampled layout, decoded motion and speech-signal checks remain distinct from continuous listening, Chinese speech synthesis and complete native-production approval.
About this partfrom its README
Part 20 of the 61-part course develops randomized algorithms through proofs, worked visual
examples and reproducible experiments. The instruments are randomized.py
and job3.py; producers live in compute.py, independent references in
measurements.py, and regression checks in tests/test_cs20_randomized.py.
The opening compares the exact word table with a Count-Min sketch retaining 32 candidate words. For this corpus and fixed seed, all top-20 words and counts agree. The 18,588-byte figure is the compiled program's global-data block, including candidates and indices; it is not the Python process footprint. In a separate sweep of 20 fixed hash multipliers, only 5/20 configurations at the program's shape have the completely exact answer. All true top words survive among the candidates in those 20 runs. Neither observation is a universal guarantee.
The chapters cover:
- Las Vegas versus bounded-time Monte Carlo algorithms; independent amplification, with false acceptance distinguished from a posterior probability of error after acceptance.
- Freivalds' three matrix-vector products and deferred-decisions proof. The theorem requires exact arithmetic. The instrument accepts integer matrices, prevents overflow and rejects fractional input. The float64 benchmark uses bounded integers with exact intermediates; a full integer product reference checks every timed result. The leading FLOP counts at size 2,000 are 16 billion versus 24 million. Wall times are host observations.
- Schwartz–Zippel over a field with independent uniform substitutions, a false identity, a Vandermonde check, and Tutte's perfect-matching test. Whole-field sampling gives the coarse degree-n bound n/p. The former nonzero-element sampler also admitted this coarse bound through its degree-n/2 Pfaffian; no defect is claimed for that original displayed inequality. The teaching API uses odd prime fields. A sentinel byte makes the integer file encoding injective; prime-count asymptotics are labeled heuristics, not finite error certificates.
- Karger's contraction and telescoping success lower bound, the ten-cycle's 45 minimum cuts, and Karger–Stein. Both graph fixtures have independent deterministic Stoer–Wagner certificates. Success shares are finite trials.
- Fermat and Carmichael numbers; Miller–Rabin's fixed-composite false-acceptance bound. The finite liar inventory below 20,000 uses exact trial division. Large generated values are probable primes: 40 screening rounds plus an independent 64-round rescreen do not constitute primality certificates.
- Papadimitriou's 2-SAT walk and Schöning's restarted 3-SAT search. Final permitted flips are checked, and attempts are counted directly, including initially solved restarts. The experiment uses small uniquely satisfying formulas checked exhaustively; it does not identify universally hardest instances or prove a runtime lower bound.
- One versus two random bin choices, finite histograms and asymptotic maximum-load scales.
- Bloom membership with a packed byte array, checked for every inserted word. The familiar false-positive formula assumes ideal independent placements and uses an occupancy approximation; the concrete double hash is empirical.
- Reservoir sampling, deterministic Misra–Gries, and insertion-only Count-Min. The standard error theorem is for each fixed query with suitable collision control and independent row hashes. It does not automatically certify every vocabulary item, a double-hash implementation or the retained top-word candidates.
- The complete Pebble Job execution, separately from processor and cache projections. Every corpus instruction is emulated and the entire output is checked. IPC comes from three short passages; cache accesses come from a 150,000-byte passage. Projected cycles assume that sampled working-set behavior extends to the whole corpus.
- HyperLogLog and KMV. The 1.04/√m expression is a leading standard-error scale, not a confidence interval. The six-bit packed register model needs 3 KiB at m=4,096; the actual uint64 NumPy registers need 32 KiB, excluding corpus, hash arrays and interpreter. Scalar references check all registers for the displayed runs.
- AMS: a six-arrival signed-counter trace, the exact eight-sign expectation, variance, and median of means. Unsquared compatible counters merge linearly; their squared estimates do not simply add.
- MinHash's exact identity for ideal uniform minwise permutations and its affine-hash approximation. One hundred independent ideal rows have worst standard error 0.05, not a guaranteed ±0.05 interval. Whole-token shingle IDs are collision-free. The reference includes all inverted-index postings, including common shingles, and every positive-intersection pair. There are seven pairs with J≥0.2; observed recall is 3/7 at 0.2, 2/2 at 0.5 and 1/1 at 0.8. The ideal banding curve is smooth and requires independent minwise rows.
- Ramsey's expectation argument and the variable-model local lemma. Moser–Tardos now starts from exactly the assignment used in the initial-failure column. Dependency degree is an upper bound. Its expected-work theorem is separate from each observed resampling count; exhausting an execution budget does not establish UNSAT.
- Conditional expectations, with a five-edge graph and both branch values at each choice; pairwise-independent seed enumeration; RANDU's planes; simulation generators versus cryptographic generators and physical entropy.
- BPP as a decision class, explicit PRG seed/circuit quantifiers, the E-hardness premise of Impagliazzo–Wigderson, and the specific integer-PIT lower-bound implication. Bipartite matching in quasi-NC² still has quasi-polynomial size. Streaming bounds state their universe, update model and fixed success probability.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Las Vegas against Monte Carlo: randomized quicksort's 400 runs on 2,000 keys (mean 24,761 against the exact 24,730); one-sided error and 2^{−k}; majority votes and Hoeffding.
- Freivalds (1977), error ≤ ½ per round, proved by deferred decisions; at n = 2,000, 24 million operations against 16 billion (23 ms against BLAS's 0.13 s); one wrong entry passes 50.9%, 25.1%, 12.4%, … of 4,000 trials.
- The Schwartz–Zippel lemma (proved); a false identity against 3/|S|; an 8 × 8 Vandermonde identity; the Tutte matrix (Lovász 1979) against Edmonds' blossoms on 48 random graphs; a 61-bit fingerprint of the corpus (false match ≤ 1.2 × 10^{−10}).
- Karger's min cut (1993), contraction animated (one success, one failure): ≥ 2/(n(n − 1)) proved, 13.1% measured against 0.83%; the 10-cycle's 45 = C(10, 2) minimum cuts; Karger–Stein.
- Primality: Fermat; 561 and Korselt; 43 Carmichael numbers below 10⁶; Miller–Rabin (561's sequence 263, 166, 67, 1; Rabin's ¼, attained at 9); random primes to 2,048 bits timed; AKS (2002).
- Random walks: Papadimitriou's 2-SAT as a gambler's ruin (≤ n², about 2n flips measured); Schöning's (4/3)ⁿ against restarts measured on unique-solution formulas to n = 20; PPSZ.
- Balls into bins, animated with one and two choices; max loads to 10⁶ (10 against 4); the full histograms; why two choices square the tail.
- Bloom filters (1970): 32 bits drawn with two false positives; (1 − e^{−kn/m})ᵏ and k = (m/n) ln 2 (derived); the novels' vocabulary at 10 bits per word (0.815% against 0.819%); counting and cuckoo filters.
- Streaming: reservoir sampling (proved uniform, 50,000 trials); Misra–Gries (99 counters); Count-Min and its (ε, δ) guarantee, measured on every word of the novels.
- The Job in kilobytes: Count-Min with conservative update and double hashing, 32 candidates in a heap, in the Pebble language; every instruction emulated (1.07 billion); 18,588 bytes against 1.9 MB; ledger row 9, 1.00 s against 0.794 s; the same algorithm over 20 hash functions in C (exact 25% of the time at 16 KB, 95% at 64 KB; the top 20 always among the candidates).
- Distinct counting: Flajolet–Martin, HyperLogLog (error against 1.04/√m from 16 to 16,384 registers), the corpus and its 4.5 million five-word phrases in 3 KB.
- The AMS F₂ sketch (1996) from 4-wise independent signs; the median of means; linear sketches as random projections (callback to AI, Built 3's Johnson–Lindenstrauss).
- LSH: MinHash (Broder 1997, proved) and banding (Indyk & Motwani 1998), the S-curve matched by 600 planted copies; near-duplicate paragraphs among 34,525 in the novels, checked by an inverted index; SimHash.
- The probabilistic method: K₁₇ coloured at random and by Paley; R(k, k) > 2^{k/2}; the 2023 upper bound; the Lovász local lemma and Moser–Tardos (2010) on 10-SAT inside the lemma's condition.
- Derandomization: conditional expectations (MAX-CUT ≥ m/2, 176 of 265 edges); pairwise independence from k bits; expanders (Part 56); where random bits come from: RANDU's fifteen planes on a rotating cube, Mersenne Twister, PCG, cryptographic PRGs (Part 29), physical entropy.
- Frontier: coins removed one problem at a time (AKS; Reingold; deterministic near-linear min cut; matching in quasi-NC); hardness against randomness (Nisan–Wigderson, Impagliazzo–Wigderson); PIT and circuit lower bounds (Kabanets–Impagliazzo); optimal sketches and their lower bounds; open problems. Outro.
Computed: every number above, in videos/cs/cs20/compute.py with explainer/cs/algo/randomized.py and
explainer/cs/algo/job3.py (tested in tests/test_cs20_randomized.py): Freivalds' error rates; Schwartz–Zippel and
Tutte; Karger's success rate against the bound; Miller–Rabin's liars; walks; max loads; Bloom filters against theory;
reservoir, Misra–Gries and Count-Min on the novels; the Job v3 emulated (ledger row 9) and swept in C; HLL, KMV and
AMS on the novels; MinHash duplicates; Ramsey and Moser–Tardos; MAX-CUT; RANDU.
Visuals: a graph contracting edge by edge; bins filling with one and two choices; RANDU's cube rotating until the
planes appear; a Bloom bit array lighting up; HyperLogLog's registers; the LSH S-curve; K₁₇ in two colourings.
In practice: Bloom filters in databases and caches, HyperLogLog in Redis and analytics engines, Count-Min in network monitoring and cache admission, MinHash dedup in data pipelines, Miller–Rabin in TLS.
Reading: Motwani & Raghavan, Randomized Algorithms; Mitzenmacher & Upfal, Probability and Computing; Alon &
Spencer, The Probabilistic Method; Cormode & Yi, Small Summaries for Big Data; Muthukrishnan, Data Streams;
Knuth, TAOCP 2 ch. 3; Karger 1993; Flajolet et al. 2007; Alon, Matias & Szegedy 1996; Moser & Tardos 2010.
Build the film
python -m videos.cs.cs20.compute # the part's numbers, into .cache/cs20
python tools/build.py cs20 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs20 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs20. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build itReproduce measurements and previews
source /workspace/environment/activate.sh
PYTHONPATH=. OPENBLAS_NUM_THREADS=1 .venv/bin/python -m unittest tests.test_cs20_randomized -v
PYTHONPATH=. OPENBLAS_NUM_THREADS=1 .venv/bin/python -m videos.cs.cs20.compute --force
PYTHONPATH=. .venv/bin/python tools/build.py cs20 -q l
The --force rebuild matters when replacing older payloads. All 16 producers use schema 2. Payloads preserve
seeds, raw timing samples, the actual platform/NumPy build and queried BLAS thread configuration. Validation runs
after timers stop. Minimum-of-repeated, single-run and arithmetic-mean statistics are identified separately.
The 2,048-bit generation observation has one repetition; smaller generation sizes have three. AMS applies random signs to a retained exact frequency vector; its counter budget excludes that input. The MinHash timed
signature output has a full shape/range check and an independent scalar check of all 100 rows for 32 sampled
paragraphs, not a full independent signature certificate. Candidate band matches and the whole exact similarity
inventory are separate checks. Measurements on a shared host do not isolate a causal hardware improvement.