Module contents
Lesson 23 of 33Advanced 115 min

Randomized algorithm techniques

Randomness produces simpler, faster or the only known algorithms. Study Karger and Karger–Stein min-cut, Freivalds verification and Schwartz–Zippel polynomial identity testing, probability amplification, balls and bins with the power of two choices, the probabilistic method and derandomization by conditional expectations.

After this lesson you can

  • Analyze Karger's algorithm and calculate repetitions ensuring high-probability success.
  • Apply Freivalds and Schwartz–Zippel to verify computations faster than performing them.
  • Amplify one-sided and two-sided error Monte Carlo algorithms.
  • Calculate maximum balls-and-bins load and explain the power of two choices.
  • Prove existence with the probabilistic method and derandomize by conditional expectations.

Before you start

Motivation: ten lines and a cheap check

Two problems to start.

A network’s minimum cut. Given an undirected graph, such as a data-center topology or document similarity graph, find the smallest number of edges whose removal disconnects it: network reliability or the weakest boundary between two communities. With what you know, use the max-flow min-cut theorem: fix a vertex ss, solve n−1n - 1 flow problems, one for each possible tt, and keep the minimum. It works, but each flow is a delicate algorithm. Another method fits in ten lines: choose a random edge, merge its endpoints into one vertex, repeat until two remain and return the edges between them. It seems too naive to work, yet finds a minimum cut with exactly analyzable probability, large enough that a few thousand repetitions make success nearly certain.

Did the GPU calculate correctly? A kernel returns C\mat{C}, supposedly the product AB\mat{A}\mat{B} of two n×nn \times n matrices. Recomputing it to check costs as much as computing it: O(n3)\bigO(n^3) with the usual algorithm, O(nω)\bigO(n^{\omega}) with the best known (the matrix multiplication exponent). But this is unnecessary. Take a random zero–one vector r\vb{r} and compare A(Br)\mat{A}(\mat{B}\vb{r}) with Cr\mat{C}\vb{r}: three matrix–vector products, O(n2)\bigO(n^2), and if C≠AB\mat{C} \ne \mat{A}\mat{B} the sides differ with probability at least 1/21/2. Twenty vectors make the probability of missing an error less than one in a million.

Both are Monte Carlo algorithms: runtime is fixed in advance and they can err with bounded probability controlled by the algorithm, not the input. Quicksort showed the first reason to randomize: preventing worst cases from depending on whoever chooses data. Here are three more:

  • Abundant witnesses. If C≠AB\mat{C} \ne \mat{A}\mat{B}, half of vectors r\vb{r} demonstrate it; evaluating two different polynomials at a random point distinguishes them almost everywhere. We do not know how to find a witness deterministically and cheaply, but can stumble upon one.
  • Survival of the rare. A minimum cut has few edges, so a randomly chosen edge rarely belongs to it. Karger turns this observation into an algorithm.
  • Existence by averaging. If a random quantity averages m/2m/2, some outcome is at least m/2m/2. The probabilistic method thus proves objects exist that nobody knows how to construct, and derandomization sometimes constructs them.

The tools are always the same: linearity of expectation and indicator variables, the union bound, independence and Chernoff bounds.

Karger’s minimum cut

Work with undirected multigraphs: multiple edges can join the same vertices, and each counts. A cut of G=(V,E)G = (V, E) partitions VV into two nonempty sets (S,V∖S)(S, V \setminus S); its size is the number of edges with one endpoint on each side. The global minimum cut λ(G)\lambda(G) is the smallest cut size; neither ss nor tt is fixed.

The key operation is contracting edge e={u,v}e = \{u, v\}: replace uu and vv with one vertex uvuv, each edge touching uu or vv now touches uvuv, and delete edges between uu and vv, which would become loops. Other parallel edges remain: hence multigraphs are needed. Two facts make contraction useful:

  1. Contraction creates no cuts. Each vertex of G/eG/e is a set of vertices of GG, so a cut of G/eG/e is a cut of GG with exactly the same edges. Thus λ(G/e)≥λ(G)\lambda(G/e) \ge \lambda(G).
  2. A cut survives iff none of its edges is contracted. If CC is a cut of GG and e∉Ce \notin C, endpoints of ee lie on the same side and CC remains a cut of G/eG/e.

It always returns a cut, though not necessarily a minimum one: it is one-sided-error Monte Carlo because a minimum cut found really is minimum. The figure shows each supervertex as the blob formed by contracted edges (a tree spanning it).

InteractiveKarger contractions
Two supervertices remain. The 2 edges joining them form the cut returned by this run.
contraction 8 / 8
  • chosen edge
  • marked minimum cut
  • discarded loop
Frequency of each cut size in 1 000 runs
0 %21 %42 %21833842851262.9789returned cut size
  • any minimum cut
  • marked minimum cut
  • other cuts
  • bound 2/(n(n−1))2/(n(n-1))
One run
Many runs
Minimum cut λ\lambda (brute force)2 (1 cut)
Marked cutintact
Runs1 000
Find a minimum cut18.4 %
Find the marked cut18.40 %
Bound 2/(n(n−1))2/(n(n-1))2.22 %
Repetitions for failure < 1%208
This run found a minimum cut of size 2.
Above, a step-by-step run: the selected edge is highlighted then contracted; resulting loops are discarded. Red edges form a minimum cut calculated by brute force: if one is contracted (a cross appears), that cut can no longer be returned. Below, frequency of each cut size across thousands of runs: orange marks any minimum cut, red the marked cut and dashed line the bound 2/(n(n−1))2/(n(n-1)). Compare three graphs: on clusters the bound is pessimistic; on the cycle the marked cut occurs almost exactly at the bound, yet some minimum cut always occurs.

Success probability

Proof

Let AiA_i be the event “contraction ii does not choose an edge of CC,” for i=1,…,n−2i = 1, \dots, n - 2. By point 2 above, the algorithm returns exactly CC iff all occur.

Before contraction ii, ni=n−i+1n_i = n - i + 1 vertices remain, and if A1,…,Ai−1A_1, \dots, A_{i-1} occurred, current multigraph GiG_i still contains the kk edges of CC. Every vertex of GiG_i has degree at least kk: its degree is the size of the cut separating it from the rest, which is also a cut of GG (point 1). Summing degrees, GiG_i has mi≥nik/2m_i \ge n_i k/2 edges. Since the edge is uniformly chosen,

P(Ai‾∣A1∩⋯∩Ai−1)=kmi≤knik/2=2ni.\Pr(\overline{A_i} \given A_1 \cap \dots \cap A_{i-1}) = \frac{k}{m_i} \le \frac{k}{n_i k/2} = \frac{2}{n_i}.

The product rule gives

P(⋂i=1n−2Ai)≥∏i=1n−2(1−2n−i+1)=∏j=3nj−2j=n−2n⋅n−3n−1⋅n−4n−2⋯24⋅13=2n(n−1),\Pr\Big(\bigcap_{i=1}^{n-2} A_i\Big) \ge \prod_{i=1}^{n-2}\Big(1 - \frac{2}{n - i + 1}\Big) = \prod_{j=3}^{n}\frac{j - 2}{j} = \frac{n-2}{n}\cdot\frac{n-3}{n-1}\cdot\frac{n-4}{n-2}\cdots\frac{2}{4}\cdot\frac{1}{3} = \frac{2}{n(n-1)},

because the product telescopes: the last two numerators, 2⋅12 \cdot 1, and first two denominators, n(n−1)n(n-1), remain.

∎

Notice the power of the argument: minimality forces every degree to be large, so there are many edges and few in the cut. The minimum cut is a minority and uniform selection avoids it. The bound is for one particular minimum cut, and a structural theorem follows for free.

Proof

Let C1,…,CNC_1, \dots, C_N be the minimum cuts. Events “Karger returns CjC_j” are disjoint, and each has probability at least 1/(n2)1/\binom{n}{2}. Their sum is at most 1, so N≤(n2)N \le \binom{n}{2}. In CnC_n, choosing any two of the nn edges gives a cut of size 2, the minimum: exactly (n2)\binom{n}{2}.

∎

For a cycle, the bound is exact for each particular cut, yet Karger always succeeds: all size-2 cuts are minimum. The practical probability, returning some minimum cut, is usually much higher than the bound, as in the figure’s clusters. But it cannot generally be improved: for every ε>0\eps > 0 there are graphs with a unique minimum cut whose success probability decays as n−2+εn^{-2+\eps} (measure it on a necklace of multiple edges in the implementation).

Repeat until confident

One run succeeds with probability p≥1/(n2)p \ge 1/\binom{n}{2}. Repeating TT times with independent randomness and returning the smallest found cut fails only if every run fails:

P(fallo)≤(1−p)T≤e−pT,T=⌈(n2)ln⁡1δ⌉  ⟹  P(fallo)≤δ,\Pr(\text{fallo}) \le (1 - p)^T \le e^{-pT}, \qquad T = \Big\lceil \binom{n}{2}\ln\frac{1}{\delta}\Big\rceil \;\Longrightarrow\; \Pr(\text{fallo}) \le \delta,

using 1−x≤e−x1 - x \le e^{-x}. With δ=1/n\delta = 1/n, O(n2log⁡n)\bigO(n^2 \log n) repetitions are needed.

What does one run cost? Contracting in random order is equivalent to shuffling edges and scanning them, joining endpoints with union-find, skipping those already joining vertices of one group (loops) and stopping at two groups. The equivalence: in a uniform permutation, conditioned on everything read, the next edge that is not a loop is uniform among nonloops. This is Kruskal with random weights, stopped at two components. It costs O(m α(n))\bigO(m\,\alpha(n)) after shuffling, and total for high probability is O(mn2log⁡n)\bigO(m n^2 \log n). For multiedges with multiplicity ww, sort exponential clocks of rate ww (if Xe∼Exp(we)X_e \sim \text{Exp}(w_e), the minimum among them is edge ee with probability we/∑ww_e/\sum w), as in the code.

Karger–Stein: repeat only where it hurts

Why so many repetitions? Risk is uneven: at step ii the cut is lost with probability 2/ni2/n_i, negligible initially and huge at the end (with three vertices, up to 2/32/3). Repeating the whole algorithm also repeats cheap safe steps. Karger and Stein (1996) propose contracting once until risk starts rising, then branching.

The probability that CC survives until tt vertices remain is the same telescoping product stopped earlier:

∏j=t+1nj−2j=t(t−1)n(n−1)≥12si t=⌈1+n2⌉.\prod_{j=t+1}^{n}\frac{j-2}{j} = \frac{t(t-1)}{n(n-1)} \ge \frac12 \quad\text{si } t = \Big\lceil 1 + \frac{n}{\sqrt 2}\Big\rceil.

((t−1)2≥n2/2(t-1)^2 \ge n^2/2 suffices because t(t−1)≥(t−1)2≥n2/2≥n(n−1)/2t(t-1) \ge (t-1)^2 \ge n^2/2 \ge n(n-1)/2.)

Success probability. Let P(n)P(n) be the probability of returning a particular minimum cut. Each branch succeeds if the cut survives contraction (probability ≥1/2\ge 1/2) and recursion succeeds; branches are independent. Thus,

P(n)≥1−(1−12P(t))2=P(t)−14P(t)2.P(n) \ge 1 - \Big(1 - \tfrac12 P(t)\Big)^2 = P(t) - \tfrac14 P(t)^2.

Count levels from below: p0=1p_0 = 1 (brute force) and pd+1≥pd−pd2/4p_{d+1} \ge p_d - p_d^2/4. By induction, pd≥1/(d+1)p_d \ge 1/(d+1): function f(p)=p−p2/4f(p) = p - p^2/4 is increasing on [0,2][0, 2], and f(1d+1)≥1d+2f\big(\tfrac{1}{d+1}\big) \ge \tfrac{1}{d+2} is equivalent to 1(d+1)(d+2)≥14(d+1)2\tfrac{1}{(d+1)(d+2)} \ge \tfrac{1}{4(d+1)^2}, i.e. 4(d+1)≥d+24(d+1) \ge d+2. There are log⁡2n+O(1)=2log⁡2n+O(1)\log_{\sqrt 2} n + \bigO(1) = 2\log_2 n + \bigO(1) levels, so

P(n)=Ω(1log⁡n).P(n) = \Omega\Big(\frac{1}{\log n}\Big).

Time. With the adjacency matrix (multiplicities in entries), contracting to tt vertices costs O(n2)\bigO(n^2), and T(n)=2T(n/2)+O(n2)T(n) = 2T(n/\sqrt 2) + \bigO(n^2). Since nlog⁡22=n2n^{\log_{\sqrt 2} 2} = n^2, this is the balanced case of the master theorem: T(n)=O(n2log⁡n)T(n) = \bigO(n^2 \log n). Repeating O(log⁡n⋅log⁡(1/δ))\bigO(\log n \cdot \log(1/\delta)) times gives error δ\delta; with δ=1/n\delta = 1/n, O(n2log⁡3n)\bigO(n^2\log^3 n) total, versus O(n4log⁡n)\bigO(n^4 \log n) for repeating Karger with the same dense representation.

Freivalds: verify without recomputing

Proof

Let D=AB−C≠0\mat{D} = \mat{A}\mat{B} - \mat{C} \ne \mat{0} and let dij≠0d_{ij} \ne 0 be a nonzero entry. Bound P(Dr=0)\Pr(\mat{D}\vb{r} = \vb{0}); it suffices to bound the probability that component ii vanishes:

(Dr)i=dijrj+∑l≠jdilrl=dijrj+y.(\mat{D}\vb{r})_i = d_{ij}r_j + \sum_{l \ne j} d_{il} r_l = d_{ij}r_j + y.

Use the principle of deferred decisions: the rlr_l are independent, so first draw all except rjr_j, fixing yy, and draw rjr_j last. Given yy, equation dijrj+y=0d_{ij}r_j + y = 0 has at most one solution rj=−y/dijr_j = -y/d_{ij}, and rjr_j takes that value with probability at most 1/21/2. Since the bound holds for each yy, it also holds unconditionally.

∎

The proof gives more. If r\vb{r} is uniform on SnS^n for a finite set S⊆FS \subseteq \mathbb{F}, the same calculation gives P(Dr=0)≤1/∣S∣\Pr(\mat{D}\vb{r} = \vb{0}) \le 1/\abs{S}: with entries in {0,…,9}\{0, \dots, 9\}, one test fails at most one time in ten. Bound 1/21/2 is exact: if D\mat{D} has only one nonzero entry dijd_{ij}, the test passes exactly when rj=0r_j = 0.

InteractiveCatch an incorrect product
A\mat{A}
0
0
1
1
2
0
−3
0
1
0
0
2
−1
1
1
−2
B\mat{B}
−2
−2
−1
−1
1
−3
1
1
−1
2
2
2
−1
1
−2
−3
Claimed C\mat{C} (click)
r\vb{r}
→
Br\mat{B}\vb{r}
−4
−2
1
0
→
A(Br)\mat{A}(\mat{B}\vb{r})
1
−11
−4
3
=
Cr\mat{C}\vb{r}
1
−11
−4
3
The 16 vectors r∈{0,1}4\vb{r} \in \{0,1\}^4: colored vectors detect the error
Cost of one test: 3n23n^2 products versus n3n^3 to recompute AB\mat{A}\mat{B}. With n=4096n = 4096, 5.0×1075.0\times 10^{7} versus 6.9×10106.9\times 10^{10}.
Errors in C
Random vector
Entries of r\vb{r}
r\vb{r} that detect8 / 16 (50 %)
Miss, one attempt0.500 (≤ 1/2)
This r\vb{r} does not detect the error: both columns agree even though C≠AB\mat{C} \ne \mat{A}\mat{B}. Try another.
Click entries of C\mat{C} to corrupt them and r\vb{r} to change them. Columns A(Br)\mat{A}(\mat{B}\vb{r}) and Cr\mat{C}\vb{r} update live; differing components are red. The grid shows all 16 vectors of {0,1}4\{0,1\}^4, coloring those detecting the error: with one error, exactly half. Try ‘Two that cancel’ with r=(1,1,1,1)\vb{r} = (1, 1, 1, 1), as a fixed checksum would: the error passes. Then add errors until a row is full: can fewer than half the vectors see them? Switch to entries in {0,…,9}\{0, \dots, 9\} and observe the failure fraction.

Verify GPU calculations

Why does this matter outside theory? Large data centers have documented silent data corruptions: defective processors occasionally returning incorrect arithmetic results without warning (Dixit et al., “Silent Data Corruptions at Scale,” 2021; Hochschild et al., “Cores that don’t count,” 2021; both study server CPUs). If such a fault affects matrix multiplication in a weeks-long training run on thousands of processors, it can poison weights without stopping anything. Checking every product by recomputation doubles cost; Freivalds checks an n×nn\times n product at fraction 3k/n3k/n of product cost: 0.07% with n=4096n = 4096 and k=1k = 1.

There are two engineering details. First is floating point: A(Br)\mat{A}(\mat{B}\vb{r}) and Cr\mat{C}\vb{r} never match exactly because rounding depends on summation order. Compare with a tolerance tracking rounding noise magnitude; that tolerance sets the smallest detectable error: errors far above noise are almost always detected, errors at noise scale are indistinguishable. Calibrate it in code. Second is choosing r\vb{r}. Classical algorithm-based fault tolerance (ABFT, Huang and Abraham, 1984) adds row and column checksums, Freivalds with fixed vector r=1\vb{r} = \vb{1} applied on the right (C1\mat{C}\vb{1}) and left (1⊤C\vb{1}^\top\mat{C}). It cheaply detects and localizes a single error, but some patterns always pass: two canceling errors in one row fool the row checksum, and four in a rectangle (+e+e and −e-e in one row, −e-e and +e+e in the same columns of another) fool both. With random r\vb{r} no error pattern passes with probability exceeding 1/21/2. The monitored kernel may be tiled matrix multiplication in Triton.

Schwartz–Zippel: polynomial identities

Freivalds is a special case of a broader fact. Component ii of Dr\mat{D}\vb{r} is a nonzero degree-1 polynomial in variables r1,…,rnr_1, \dots, r_n evaluated at a random point. A nonzero polynomial cannot vanish at “too many” points.

Proof

Induct on nn. For n=1n = 1, a nonzero one-variable degree-dd polynomial has at most dd roots, so probability is at most d/∣S∣d/\abs{S}.

For n>1n > 1, write pp in powers of x1x_1: p=∑i=0kx1i qi(x2,…,xn)p = \sum_{i=0}^{k} x_1^i\, q_i(x_2, \dots, x_n), where kk is the largest exponent of x1x_1 with qk≠0q_k \ne 0. Since x1kqkx_1^k q_k contributes terms of degree k+deg⁡qkk + \deg q_k, deg⁡qk≤d−k\deg q_k \le d - k. Let BB be event “qk(r2,…,rn)=0q_k(r_2, \dots, r_n) = 0”. By induction, P(B)≤(d−k)/∣S∣\Pr(B) \le (d - k)/\abs{S}. If BB does not occur, fixing r2,…,rnr_2, \dots, r_n makes p(x1,r2,…,rn)p(x_1, r_2, \dots, r_n) a nonzero polynomial in x1x_1 of degree kk, and by the n=1n = 1 case it vanishes at r1r_1 with probability at most k/∣S∣k/\abs{S}. Hence

P(p(r)=0)≤P(B)+P(p(r)=0∣B‾)≤d−k∣S∣+k∣S∣=d∣S∣.\Pr(p(\vb{r}) = 0) \le \Pr(B) + \Pr(p(\vb{r}) = 0 \given \overline{B}) \le \frac{d - k}{\abs{S}} + \frac{k}{\abs{S}} = \frac{d}{\abs{S}}.∎

This is the Schwartz–Zippel lemma (Schwartz, 1980; Zippel, 1979; preceded by DeMillo and Lipton, 1978). Its usual application is polynomial identity testing: given an implicit polynomial (a determinant of a variable matrix, arithmetic circuit, product of factors), determine whether it is identically zero. Expanding it can require exponentially many monomials: a generic n×nn\times n determinant has n!n!. Evaluation at a random point of a large finite field costs one evaluation and errs with probability at most d/∣S∣d/\abs{S}, only in one direction: a nonzero value certainly proves a nonzero polynomial.

Perfect matchings with determinants

Let GG be a graph with vertices 1,…,n1, \dots, n. Its Tutte matrix T\mat{T} has a variable xijx_{ij} per edge {i,j}\{i, j\} with i<ji < j, and entries tij=xijt_{ij} = x_{ij}, tji=−xijt_{ji} = -x_{ij}, and 00 where no edge exists. It is skew-symmetric.

Proof

If MM is a perfect matching, assign xijx_{ij} value 1 on edges of MM and 0 elsewhere. Reordering vertices in pairs makes T\mat{T} block diagonal with blocks [01−10]\begin{bmatrix} 0 & 1 \\ -1 & 0\end{bmatrix} of determinant 1. A polynomial with a nonzero value is nonzero.

Conversely, det⁡T=∑σsgn⁡(σ)∏itiσ(i)\det\mat{T} = \sum_\sigma \operatorname{sgn}(\sigma)\prod_i t_{i\sigma(i)}, and only permutations where every i→σ(i)i \to \sigma(i) is an edge contribute (a term with σ(i)=i\sigma(i) = i is zero because the diagonal is zero). Pair permutations having any odd-length cycle by reversing the odd cycle containing the smallest possible vertex. Permutation sign does not change (cycle type is unchanged), while the product changes sign because each of an odd number of cycle factors changes from tijt_{ij} to tji=−tijt_{ji} = -t_{ij}. These terms cancel pairwise. If det⁡T≠0\det\mat{T} \ne 0, some permutation survives with all even-length cycles formed by edges; choosing alternating edges on each cycle (a 2-cycle is one edge) gives a perfect matching.

∎

Lovász (1979) observed the algorithmic implication: replace each xijx_{ij} by a random value from Fp\mathbb{F}_p with large pp and compute the numeric determinant in O(n3)\bigO(n^3), or in O(nω)\bigO(n^\omega). The symbolic determinant has degree nn, so the test errs with probability at most n/pn/p, only saying “none” when one exists. It is simpler than Edmonds’ blossom algorithm, reduces to linear algebra, which parallelizes well, and starts parallel matching algorithms (Mulmuley, Vazirani and Vazirani, 1987, with the isolation lemma).

String fingerprints

To compare strings aa and bb of length LL over an integer alphabet, view them as polynomials A(x)=∑iaixiA(x) = \sum_i a_i x^i and B(x)=∑ibixiB(x) = \sum_i b_i x^i and compare A(r) mod pA(r) \bmod p with B(r) mod pB(r) \bmod p for random rr. If a≠ba \ne b, A−BA - B is a nonzero polynomial of degree at most L−1L - 1 and collision probability is at most (L−1)/p(L-1)/p. This is the fingerprint used by Rabin–Karp, and with p=261−1p = 2^{61} - 1 and L=106L = 10^6 per-comparison collision probability is below 5×10−135\times 10^{-13}. It is also polynomial universal hashing: the analysis is the same.

Probability amplification

Karger’s success probability is tiny and Freivalds errs with probability 1/21/2; neither suffices as-is. Repetition solved both. Probability amplification studies how to combine kk independent Monte Carlo runs so error falls exponentially in kk; the combination rule depends on error type.

One-sided error. Suppose a decision algorithm answers “yes” with probability at least 1−ε1 - \varepsilon when the correct answer is yes, and always answers no otherwise. A yes is then proof. Run it kk times and answer yes if any run does. Error is possible only on a yes input and only if all kk runs fail:

P(error)≤εk,k=⌈ln⁡(1/δ)ln⁡(1/ε)⌉  ⟹  P(error)≤δ.\Pr(\text{error}) \le \varepsilon^k, \qquad k = \Big\lceil\frac{\ln(1/\delta)}{\ln(1/\varepsilon)}\Big\rceil \;\Longrightarrow\; \Pr(\text{error}) \le \delta.

Freivalds has this form (yes means “found a witness of C≠AB\mat{C} \ne \mat{A}\mat{B}”), as does Karger, with “keep the smallest cut” playing the role of “one yes suffices.” Notice ε\varepsilon can be very close to 1: Karger has ε=1−1/(n2)\varepsilon = 1 - 1/\binom{n}{2}, and it still works, with k≈(n2)ln⁡(1/δ)k \approx \binom{n}{2}\ln(1/\delta).

Two-sided error. If the algorithm can err in both directions with probability ε<1/2\varepsilon < 1/2, no individual answer is proof; vote.

Proof

Let XX be the number of erroneous runs, a sum of kk independent indicators with mean at most ε\varepsilon each, so E[X]≤kε\E[X] \le k\varepsilon. Majority errs only if X≥k/2X \ge k/2, i.e. X−E[X]≥k(12−ε)X - \E[X] \ge k(\tfrac12 - \varepsilon). Hoeffding’s inequality for sums of independent variables in [0,1][0, 1] gives P(X−E[X]≥kt)≤e−2kt2\Pr(X - \E[X] \ge kt) \le e^{-2kt^2}; with t=12−εt = \tfrac12 - \varepsilon the bound follows.

∎

Concrete figures illustrate the difference. With ε=1/3\varepsilon = 1/3 and target δ=10−9\delta = 10^{-9}, one-sided error needs k=⌈9ln⁡10/ln⁡3⌉=19k = \lceil 9\ln 10/\ln 3\rceil = 19 repetitions. Two-sided error needs k=374k = 374 by Hoeffding’s bound and 305 by the exact binomial tail (with odd kk to avoid ties). The order-of-magnitude difference arises because in the one-sided case each repetition multiplies error by 1/31/3, whereas in the two-sided case it asymptotically multiplies by only e−2(1/6)2≈0.946e^{-2(1/6)^2} \approx 0.946 in the bound, or 2ε(1−ε)≈0.9432\sqrt{\varepsilon(1-\varepsilon)} \approx 0.943 in the exact binomial tail rate.

InteractiveAmplifying well and badly
  • one yes suffices: εᵏ
  • majority (wrong rule)
  • target δ = 1 × 10⁻⁹
Error type
Parameters
0.75
kk with “one yes suffices”73
kk with majoritynever
With one-sided error ε>1/2\varepsilon > 1/2, each run says “yes” with probability below 1/21/2, so a majority of yeses becomes rarer: the wrong rule worsens with repetition. One “yes” suffices.
Error of kk independent runs on a log scale, with the right rule (blue) and wrong one (red), against target δ\delta (orange). In one-sided mode, with ε\varepsilon above 1/21/2 (as initially), majority stops converging and worsens with repetition, while ‘one yes suffices’ keeps falling; lower ε\varepsilon to 1/31/3 and compare speeds. In two-sided mode compare the exact majority tail with Hoeffding’s bound and see how ‘one yes suffices’ accumulates false positives. Finally enable ‘same seed’: all curves remain flat.

Two observations provide context. First, constant 1/31/3 is arbitrary. Any algorithm with error 12−1/q(n)\tfrac12 - 1/q(n), for a polynomial qq, can be amplified to error 2−n2^{-n} using O(n q(n)2)\bigO(n\,q(n)^2) repetitions. Thus BPP (decision problems with bounded two-sided-error randomized polynomial algorithms) is defined with 1/31/3 without loss of generality, likewise RP with one-sided error. See the randomized classes lesson. Second, if an answer can be checked, Monte Carlo becomes Las Vegas by repeating until a verified answer; conversely, a Las Vegas algorithm with expected time τ\tau becomes Monte Carlo by cutting it off after 2τ2\tau steps, failing with probability at most 1/21/2 by Markov’s inequality.

Balls and bins

Many randomized-algorithm questions are fundamentally the same: throw mm balls, each uniformly and independently into one of nn bins. When do two balls collide? When are all bins occupied? How many balls are in the fullest bin? Balls may be hash-table keys, server requests, processor tasks or tokens sent to experts. This is the balls-and-bins model.

Birthdays: the first collision. The probability that mm balls land in distinct bins is

∏i=1m−1(1−in)≤exp⁡(−∑i=1m−1in)=exp⁡(−m(m−1)2n),\prod_{i=1}^{m-1}\Big(1 - \frac{i}{n}\Big) \le \exp\Big(-\sum_{i=1}^{m-1}\frac{i}{n}\Big) = \exp\Big(-\frac{m(m-1)}{2n}\Big),

and the approximation is good when m≪nm \ll n. Collision probability reaches 1/21/2 near m≈2nln⁡2≈1.18nm \approx \sqrt{2n\ln 2} \approx 1.18\sqrt n: with n=365n = 365, starting at m=23m = 23 people. For a 64-bit hash the first collision is likely near 2ln⁡2⋅264≈5.1×109\sqrt{2\ln 2 \cdot 2^{64}} \approx 5.1\times 10^9 elements: far fewer than the 1.8×10191.8\times 10^{19} possible values. This is why content fingerprints use 128 or 256 bits, and expected colliding-pair count (m2)/n\binom{m}{2}/n follows directly from linearity of expectation.

Coupons: the last empty bin. The number of balls XX until all bins are full is a sum of geometric waiting times: with ii bins occupied, the next ball lands in a new one with probability (n−i)/n(n - i)/n. Thus,

E[X]=∑i=0n−1nn−i=nHn=nln⁡n+O(n).\E[X] = \sum_{i=0}^{n-1}\frac{n}{n - i} = nH_n = n\ln n + \bigO(n).

It is concentrated: after t=nln⁡n+cnt = n\ln n + cn balls, a particular bin is still empty with probability (1−1/n)t≤e−t/n=e−c/n(1 - 1/n)^t \le e^{-t/n} = e^{-c}/n, and by the union bound some bin remains empty with probability at most e−ce^{-c}. Ensuring no server lacks work or sampling all elements of a set requires Θ(nlog⁡n)\Theta(n\log n) random attempts, not nn.

Maximum load

With m=nm = n mean load is 1, but maximum load is not.

Proof

Bin 1 receives at least kk balls only if some subset of kk balls all land in it. By the union bound over (nk)\binom{n}{k} subsets,

P(carga1≥k)≤(nk)1nk≤nkk!⋅1nk=1k!≤(ek)k,\Pr(\text{carga}_1 \ge k) \le \binom{n}{k}\frac{1}{n^k} \le \frac{n^k}{k!}\cdot\frac{1}{n^k} = \frac{1}{k!} \le \Big(\frac{e}{k}\Big)^k,

using k!≥(k/e)kk! \ge (k/e)^k. It remains to show (e/k)k≤n−2(e/k)^k \le n^{-2}, i.e. k(ln⁡k−1)≥2ln⁡nk(\ln k - 1) \ge 2\ln n. Since k(ln⁡k−1)k(\ln k - 1) increases with kk for k≥1k \ge 1, it suffices to check unrounded k0=3ln⁡n/ln⁡ln⁡nk_0 = 3\ln n/\ln\ln n. With x=ln⁡ln⁡n>0x = \ln\ln n > 0 (true for n≥3n \ge 3), ln⁡k0=ln⁡3+x−ln⁡x\ln k_0 = \ln 3 + x - \ln x and

k0(ln⁡k0−1)=3ln⁡n(1−ln⁡x+1−ln⁡3x).k_0(\ln k_0 - 1) = 3\ln n\Big(1 - \frac{\ln x + 1 - \ln 3}{x}\Big).

Function (ln⁡x+1−ln⁡3)/x(\ln x + 1 - \ln 3)/x reaches its maximum at x=3x = 3, exactly 1/31/3, so the parenthesis is always at least 2/32/3 and k0(ln⁡k0−1)≥2ln⁡nk_0(\ln k_0 - 1) \ge 2\ln n. A second union bound, now over nn bins, gives P(carga maˊxima≥k)≤n⋅n−2=1/n\Pr(\text{carga máxima} \ge k) \le n\cdot n^{-2} = 1/n.

∎

The bound is order-tight: with probability 1−o(1)1 - o(1) maximum load is (1+o(1))ln⁡n/ln⁡ln⁡n(1 + o(1))\ln n/\ln\ln n (Mitzenmacher and Upfal, chapter 5, using Poisson approximation). But o(1)o(1) converges exasperatingly slowly: with n=106n = 10^6, ln⁡n/ln⁡ln⁡n=5.26\ln n/\ln\ln n = 5.26 and measured maximum load is 8 or 9. This is the longest chain in a chained hash table at load factor 1, so worst-case search with randomized hashing is not O(1)\bigO(1) but Θ(log⁡n/log⁡log⁡n)\Theta(\log n/\log\log n) with high probability.

The power of two choices

Change one thing: each ball inspects d≥2d \ge 2 random bins and chooses the least loaded (break ties arbitrarily). The change seems minor; its effect is huge.

This is the power of two choices: moving from one to two choices reduces maximum load exponentially, from ln⁡n/ln⁡ln⁡n\ln n/\ln\ln n to ln⁡ln⁡n/ln⁡2\ln\ln n/\ln 2; moving from two to three merely divides it by ln⁡3/ln⁡2≈1.58\ln 3/\ln 2 \approx 1.58.

Why it happens (layered argument). Let βi\beta_i be the number of bins with load at least ii at the end. For a ball to land at height i+1i + 1 or more, its dd bins must already have load at least ii, occurring with probability at most (βi/n)d(\beta_i/n)^d. There are nn balls, so in expectation the number of bins with load at least i+1i + 1 satisfies

βi+1n≲(βin)d.\frac{\beta_{i+1}}{n} \lesssim \Big(\frac{\beta_i}{n}\Big)^d.

Since at most n/4n/4 bins can have 4 or more balls, β4/n≤1/4\beta_4/n \le 1/4, and recurrence gives β4+j/n≲4−dj\beta_{4+j}/n \lesssim 4^{-d^j}: the fraction falls doubly exponentially. It drops below 1/n1/n when djln⁡4≥ln⁡nd^j \ln 4 \ge \ln n, i.e. for j≥log⁡dln⁡n−O(1)j \ge \log_d \ln n - \bigO(1), yielding maximum load ln⁡ln⁡n/ln⁡d+O(1)\ln\ln n/\ln d + \bigO(1). The rigorous proof replaces each “≲\lesssim” with a Chernoff bound holding with high probability at every layer, stopping when βi\beta_i drops to O(log⁡n)\bigO(\log n), where Chernoff no longer concentrates and two or three more layers need a union bound. With one choice, by contrast, the fraction of bins with load at least ii is approximately the tail of a mean-1 Poisson, decaying as 1/i!1/i!: only slightly faster than exponential.

InteractiveOne choice versus two
d = 1max 4d = 2max 2d = 3max 2
60 balls
Maximum load as n grows (mean of 3 batches)
  • d = 1
  • d = 2
  • d = 3
  • ln n / ln ln n
  • ln ln n / ln 2
  • ln ln n / ln 3
Fraction of bins with load ≥ k, n = 10⁵
Placement
60
Measurement
Maximum load with n = 60 (d = 1, 2, 3)4 · 2 · 2
Balls placed60 / 60
Measuring in the browser: n = 10...
Above, nn balls in nn bins with the same random-number stream for d=1,2,3d = 1, 2, 3: triangles mark bins inspected by the current ball and the dark triangle the choice. Play the throws and watch the one-choice row accumulate towers while the others grow like a block. Bottom left, maximum load measured in your browser as nn grows to one million, versus theoretical order (without constants). Bottom right, fraction of bins with load at least kk for n=105n = 10^5 on a log scale: one choice follows a Poisson tail; two choices plummet.

An even more surprising version: if m≫nln⁡nm \gg n\ln n balls are thrown, with one choice the fullest bin exceeds mean m/nm/n by Θ((m/n)ln⁡n)\Theta\big(\sqrt{(m/n)\ln n}\big), growing with mm. With two choices the gap between fullest bin and mean remains ln⁡ln⁡n/ln⁡d+O(1)\ln\ln n/\ln d + \bigO(1), independent of mm (Berenbrink, Czumaj, Steger and Vöcking, 2006). The system does not accumulate imbalance over time.

Where it is used

  • Load balancing. A balancer sending each request to the least busy of all servers needs global state; random selection is simple but imbalanced. Asking two random servers and choosing the less loaded captures almost all the benefit with local information. Mitzenmacher analyzed the dynamic version with draining queues in his 1996 thesis: the fraction of queues with at least ii jobs also decays doubly exponentially. NGINX implements it as random two least_conn.
  • Hashing. A hash table with two functions inserting each key into the less full of its two buckets has bucket size O(log⁡log⁡n)\bigO(\log\log n) with high probability. Cuckoo hashing takes the idea further: two candidate positions, but existing keys may be moved, achieving maximum size 1.
  • Mixtures of experts. An MoE router assigns each token to one or more experts (top-k routing), and each expert processes at most a fixed token capacity per batch. Tokens are balls and experts bins. Even with a perfectly uniform router and one choice, maximum load exceeds the mean: in a simulation with 4096 tokens and 64 experts, mean maximum load is 83.5 tokens versus a mean of 64, requiring capacity factor 1.3 to avoid dropping tokens. Two random choices reduce it to 65.8. A learned router is not random and tends to concentrate load, so it is trained with a balancing loss; balls-and-bins analysis gives a baseline for the cost even in the ideal case.

The probabilistic method

If random variable XX has E[X]≥a\E[X] \ge a, then X≥aX \ge a with positive probability, so an outcome exists with X≥aX \ge a. If a bad event has probability less than 1, some outcome avoids it. Proving existence by showing a random object has the property with positive probability is the probabilistic method, made central to combinatorics by Erdős.

Proof

Place each vertex in SS independently with probability 1/21/2. For each edge e={u,v}e = \{u, v\} let XeX_e indicate whether uu and vv lie on different sides: P(Xe=1)=1/2\Pr(X_e = 1) = 1/2. Cut size is X=∑eXeX = \sum_e X_e and by linearity E[X]=m/2\E[X] = m/2. A random variable cannot always be below its mean, so some partition cuts at least m/2m/2 edges.

∎

Only the fact that each pair of vertices lies on opposite sides with probability 1/21/2 was used: pairwise independence suffices, useful for derandomization. The proof also gives a randomized algorithm: since X≤mX \le m and XX is integral, m2=E[X]≤(1−p)(m2−12)+pm\tfrac m2 = \E[X] \le (1-p)\big(\tfrac m2 - \tfrac12\big) + pm with p=P(X≥m/2)p = \Pr(X \ge m/2), hence p≥1/(m+1)p \ge 1/(m+1). Repeating until success is Las Vegas with O(m)\bigO(m) expected attempts.

Proof

Under a uniform assignment, a clause with three distinct variables is false only if all three literals are false, with probability 1/81/8. By linearity, expected satisfied clauses are 7m/87m/8, and some assignment attains that. If m≤7m \le 7, some assignment satisfies at least 7m/8>m−17m/8 > m - 1 clauses, i.e. all.

∎

The bound is tight in two senses. The eight clauses with all possible signs on x1,x2,x3x_1, x_2, x_3 are not jointly satisfiable. And Håstad (2001) proved that for any ε>0\varepsilon > 0, guaranteeing 7/8+ε7/8 + \varepsilon on satisfiable formulas is NP-hard: the random assignment, which does not even inspect the formula, is the best possible algorithm unless P = NP (see gap reductions).

Proof

Color each edge of KnK_n red or blue independently with probability 1/21/2. For each set TT of kk vertices, the probability all its (k2)\binom{k}{2} edges have the same color is 2⋅2−(k2)2\cdot 2^{-\binom{k}{2}}. By the union bound, the probability some TT is monochromatic is at most (nk)21−(k2)<1\binom{n}{k}2^{1 - \binom{k}{2}} < 1, so some coloring has none. With n=⌊2k/2⌋n = \lfloor 2^{k/2}\rfloor, (nk)<nk/k!≤2k2/2/k!\binom{n}{k} < n^k/k! \le 2^{k^2/2}/k! and (nk)21−(k2)<21+k/2/k!<1\binom{n}{k}2^{1-\binom{k}{2}} < 2^{1 + k/2}/k! < 1 for k≥3k \ge 3.

∎

Equivalently, a random coloring of KnK_n has no monochromatic KkK_k with k≈2log⁡2nk \approx 2\log_2 n. More than seventy years later, the best known explicit construction (Li, 2023, arXiv:2303.06802, using two-source extractors) guarantees none only with k=(log⁡n)ck = (\log n)^{c} for some constant c>1c > 1: existence is easy, construction extremely hard. The pattern also appears in information theory: Shannon’s channel coding theorem proves capacity-achieving codes exist by showing a random code does so on average; constructing explicit efficient codes approaching it took decades (turbo and LDPC in the 1990s; Arıkan’s polar codes provably attain it in 2009).

Derandomize by conditional expectations

The large-cut argument says a random partition cuts m/2m/2 edges on average. Can we find one without randomness? Make random decisions one at a time, at each step choosing the value that does not decrease the expected value of remaining decisions.

Let x1,…,xnx_1, \dots, x_n be decisions (here, each vertex’s side) and XX the final value. By total expectation (conditional expectation), if decisions already made are x1=b1,…,xi−1=bi−1x_1 = b_1, \dots, x_{i-1} = b_{i-1},

E[X∣b1,…,bi−1]=12 E[X∣b1,…,bi−1,xi=0]+12 E[X∣b1,…,bi−1,xi=1],\E[X \given b_1, \dots, b_{i-1}] = \tfrac12\,\E[X \given b_1, \dots, b_{i-1}, x_i = 0] + \tfrac12\,\E[X \given b_1, \dots, b_{i-1}, x_i = 1],

so one value of xix_i has conditional expectation at least as large as the current one. Always choosing it makes sequence E[X∣b1,…,bi]\E[X \given b_1, \dots, b_i] nondecreasing, starting at E[X]\E[X] and ending, after all decisions, at actual value XX for the constructed assignment. This is derandomization by conditional expectations. It requires just one thing, not always available: efficiently computing conditional expectations.

For cuts this is immediate. With vertices 1,…,i1, \dots, i already placed, each edge with both endpoints placed is cut or not, and each edge with a pending endpoint is cut with probability 1/21/2:

E[X∣lados de 1,…,i]=#{aristas decididas cortadas}+12 #{aristas pendientes}.\E[X \given \text{lados de } 1, \dots, i] = \#\{\text{aristas decididas cortadas}\} + \tfrac12\,\#\{\text{aristas pendientes}\}.

When placing vertex i+1i + 1, only its edges to already placed vertices change, so the rule is: put it opposite the majority of its already placed neighbors. This greedy algorithm takes O(n+m)\bigO(n + m) time, and conditional expectations prove it guarantees m/2m/2.

InteractiveDerandomize a large cut
12345678910side Aside B
10 of 10 decided
  • conditional expectations
  • coins
  • m/2
  • optimum
How the side is chosen
Other inputs
E[cut∣decisions]\E[\text{cut} \mid \text{decisions}]11.0
Already cut + pending / 211 + 0/2
m/2m/2 · optimum7.5 · 13
Final cut 11 ≥ m/2 = 7.5, guaranteed: the conditional expectation never fell. The optimum is 13.
Place vertices one by one on side A or B. The main reading is E[corte∣decisiones]\E[\text{corte} \mid \text{decisiones}]: edges already cut plus half those pending. Conditional expectations compare both choices each step and take the larger: the magenta curve never falls and ends above m/2m/2. With coins, conditional expectation is a martingale: it rises and falls randomly, and ‘Other coins’ shows outcomes below m/2m/2. Compare both endings with the brute-force optimum.

MAX-3SAT works similarly: with some variables fixed, an already satisfied clause counts 1, and one with jj free literals and the rest false counts 1−2−j1 - 2^{-j} (with j=0j = 0, zero). Fix each variable to the value with greater total; the result satisfies at least 7m/87m/8 clauses deterministically. Implement it in the lab below.

Limited independence

A second derandomization route needs no conditional expectations: reduce the sample space until it can be exhaustively traversed. The large-cut proof only used that each edge’s endpoint sides are independent and uniform, i.e. pairwise independence. Pairwise-independent variables can fit in very few random bits: number vertices v=0,…,n−1v = 0, \dots, n-1, write them in binary with L=⌈log⁡2n⌉L = \lceil\log_2 n\rceil bits, choose a∈{0,1}L\vb{a} \in \{0,1\}^L and b∈{0,1}b \in \{0,1\} uniformly and define

Xv=⟨a,v⟩+b(mod2).X_v = \langle \vb{a}, v\rangle + b \pmod 2.

For v≠wv \ne w, Xv+Xw=⟨a,v⊕w⟩X_v + X_w = \langle\vb{a}, v \oplus w\rangle is uniform because v⊕w≠0v \oplus w \ne 0, and independent of bb; so (Xv,Xw)(X_v, X_w) is uniform on {0,1}2\{0,1\}^2. The sample space has only 2L+1≤4n2^{L+1} \le 4n points and expected cut remains exactly m/2m/2. Enumerating every seed, O(n)\bigO(n), and keeping the best yields a deterministic algorithm in time O(nm)\bigO(nm). The same trick with kk-independence gives spaces of size nO(k)n^{\bigO(k)}, behind many derandomizations and limited-independence hash families.

Implementation from scratch

First, Karger with union-find. Function contraer shuffles edges and joins endpoints until t groups remain; with t = 2 this is one Karger run. To measure the bound in its exact case use cycle C10C_{10} with (102)=45\binom{10}{2} = 45 minimum cuts, then a random graph with a unique minimum cut.

[ ]Karger with union-findBrowser
import math
import random
from collections import Counter

class UnionFind:
    def __init__(self, n):
        self.padre = list(range(n))
        self.tam = [1] * n
        self.componentes = n

    def find(self, x):
        while self.padre[x] != x:
            self.padre[x] = self.padre[self.padre[x]]      # compresión por mitades
            x = self.padre[x]
        return x

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False
        if self.tam[ra] < self.tam[rb]:
            ra, rb = rb, ra
        self.padre[rb] = ra
        self.tam[ra] += self.tam[rb]
        self.componentes -= 1
        return True

def contraer(n, aristas, t, rnd):
    """Contrae aristas en orden aleatorio hasta dejar t supervértices. Devuelve las aristas que quedan
    (sin lazos, con los vértices renombrados 0..t-1) y la etiqueta de cada vértice original."""
    orden = aristas[:]
    rnd.shuffle(orden)                   # permutación uniforme = arista uniforme no lazo en cada paso
    uf = UnionFind(n)
    for u, v in orden:
        if uf.componentes <= t:
            break
        uf.union(u, v)
    raices = {}
    etiqueta = [raices.setdefault(uf.find(v), len(raices)) for v in range(n)]
    nuevas = [(etiqueta[u], etiqueta[v]) for u, v in aristas if etiqueta[u] != etiqueta[v]]
    return nuevas, etiqueta

def karger(n, aristas, rnd):
    """Una ejecución de Karger: (tamaño del corte, lado de cada vértice)."""
    nuevas, etiqueta = contraer(n, aristas, 2, rnd)
    return len(nuevas), etiqueta

def corte_minimo_bruto(n, aristas):
    """Corte mínimo global y número de cortes mínimos, probando las 2^(n-1) - 1 particiones."""
    mejor, cuantos = math.inf, 0
    for mascara in range(1, 1 << (n - 1)):
        c = sum(((mascara >> u) ^ (mascara >> v)) & 1 for u, v in aristas)
        if c < mejor:
            mejor, cuantos = c, 1
        elif c == mejor:
            cuantos += 1
    return mejor, cuantos

def lado(etiqueta):
    """Los vértices del lado que no contiene al 0: identifica el corte."""
    return frozenset(v for v, e in enumerate(etiqueta) if e != etiqueta[0])

rnd = random.Random(1)
n = 10
ciclo = [(i, (i + 1) % n) for i in range(n)]
print("C10: (corte mínimo, número de cortes mínimos) =", corte_minimo_bruto(n, ciclo))
R = 30000
cuenta = Counter(lado(karger(n, ciclo, rnd)[1]) for _ in range(R))
fijo = frozenset({1, 2, 3})              # el corte formado por las aristas (0, 1) y (3, 4)
print(f"  P(devolver el corte fijo) medida = {cuenta[fijo] / R:.4f}   cota 2/(n(n-1)) = {2 / (n * (n - 1)):.4f}")
print(f"  cortes distintos devueltos: {len(cuenta)}, todos de tamaño 2")

def grafo_con_corte_unico(n, p, rnd):
    while True:
        A = [(u, v) for u in range(n) for v in range(u + 1, n) if rnd.random() < p]
        uf = UnionFind(n)
        for u, v in A:
            uf.union(u, v)
        if uf.componentes == 1 and corte_minimo_bruto(n, A)[1] == 1:
            return A

G = grafo_con_corte_unico(14, 0.3, random.Random(5))
lam, _ = corte_minimo_bruto(14, G)
exitos = sum(karger(14, G, rnd)[0] == lam for _ in range(5000))
print(f"\nG(14, 0.3), m = {len(G)}, corte mínimo {lam} y único")
print(f"  P(éxito) medida = {exitos / 5000:.3f}   cota = {2 / (14 * 13):.4f}")

On the cycle, fixed-cut frequency 0.02090.0209 matches theory 1/45=0.02221/45 = 0.0222 (the difference is sampling noise: typical error with 30 000 runs is 0.00090.0009), and all 45 minimum cuts appear. On the random graph success probability is 0.1990.199, eighteen times the bound: the worst case is not typical.

Now Karger–Stein. To avoid carrying parallel-edge lists through repeated contractions, store multiplicities (u,v,w)(u, v, w) and sort exponential clocks of rate ww, equivalent to shuffling the ww copies. The benchmark is a necklace: a cycle with every edge of multiplicity 5 except two opposite edges of multiplicity 4, with a unique minimum cut of size 8.

[ ]Karger–Stein versus KargerBrowser
import time

def contraer_pesos(n, aristas, t, rnd):
    """aristas: (u, v, w) con w = multiplicidad. Con relojes Exp(w), la siguiente arista no lazo que se
    contrae es cada una con probabilidad proporcional a w, como en el multigrafo."""
    orden = sorted(aristas, key=lambda e: rnd.expovariate(e[2]))
    uf = UnionFind(n)
    for u, v, w in orden:
        if uf.componentes <= t:
            break
        uf.union(u, v)
    raices = {}
    et = [raices.setdefault(uf.find(v), len(raices)) for v in range(n)]
    suma = Counter()
    for u, v, w in aristas:
        a, b = et[u], et[v]
        if a != b:
            suma[min(a, b), max(a, b)] += w      # las paralelas se funden sumando multiplicidades
    return [(a, b, w) for (a, b), w in suma.items()]

def corte_bruto_pesos(n, aristas):
    return min(sum(w for u, v, w in aristas if ((m >> u) ^ (m >> v)) & 1) for m in range(1, 1 << (n - 1)))

def karger_pesos(n, aristas, rnd):
    return sum(w for _, _, w in contraer_pesos(n, aristas, 2, rnd))

def karger_stein(n, aristas, rnd):
    if n <= 6:
        return corte_bruto_pesos(n, aristas)
    t = math.ceil(1 + n / math.sqrt(2))
    return min(karger_stein(t, contraer_pesos(n, aristas, t, rnd), rnd) for _ in range(2))

def collar(n, w=5):
    """Ciclo de multiplicidad w salvo dos aristas opuestas con w - 1: corte mínimo 2(w - 1), único."""
    return [(i, (i + 1) % n, w - 1 if i in (0, n // 2) else w) for i in range(n)]

def karger_collar_exacta(n, w=5):
    """En un ciclo, Karger devuelve las dos aristas cuyos relojes son los mayores. Que sean las dos de
    multiplicidad w - 1 exige que las n - 2 primeras elegidas sean de las otras: producto de cocientes."""
    return math.prod(j * w / (j * w + 2 * (w - 1)) for j in range(1, n - 1))

print("  n   Karger medida   exacta    2/(n(n-1))   Karger-Stein medida   ms por llamada de K-S")
for n, R_ks in ((10, 150), (20, 80), (40, 30)):
    A = collar(n)
    rnd = random.Random(3000 + n)
    pk = sum(karger_pesos(n, A, rnd) == 8 for _ in range(4000)) / 4000
    t0 = time.perf_counter()
    pks = sum(karger_stein(n, A, rnd) == 8 for _ in range(R_ks)) / R_ks
    ms = 1e3 * (time.perf_counter() - t0) / R_ks
    print(f"{n:3d}      {pk:.4f}       {karger_collar_exacta(n):.4f}     {2 / (n * (n - 1)):.4f}           {pks:.2f}                {ms:.1f}")

The Karger column matches exact probability within sampling noise (with 4000 runs, typical error is a few thousandths). On the necklace, exact probability is ∏j=1n−25j5j+8\prod_{j=1}^{n-2} \frac{5j}{5j + 8}, decaying as n−8/5n^{-8/5}: between 1.8 and 3.1 times the bound in the table, with the gap growing slowly with nn. With multiplicity ww instead of 5, the exponent is 2−2/w2 - 2/w, so the exponent in bound 1/n21/n^2 cannot be improved. Karger–Stein’s column declines slowly, as Ω(1/log⁡n)\Omega(1/\log n) predicts: with n=40n = 40, one call succeeds on three of four attempts versus less than 1% for one Karger run. At toy cell sizes repeating Karger remains competitive in time; the asymptotic difference n2log⁡3nn^2\log^3 n versus n4log⁡nn^4\log n dominates as nn grows.

Freivalds with exact integers. Introduce one error in a matrix of 90 000 entries and measure how often it passes.

[ ]Freivalds with integersBrowser
import numpy as np

def freivalds(A, B, C, k, gen):
    """False si encuentra un testigo de C != AB; True si los k vectores pasan."""
    for _ in range(k):
        r = gen.integers(0, 2, size=C.shape[1])
        if not np.array_equal(A @ (B @ r), C @ r):
            return False
    return True

gen = np.random.default_rng(0)
n = 300
A = gen.integers(-9, 10, size=(n, n))
B = gen.integers(-9, 10, size=(n, n))
C = A @ B
Cmal = C.copy()
Cmal[17, 42] += 1                         # un solo error

print("producto correcto aceptado siempre:", all(freivalds(A, B, C, 1, gen) for _ in range(200)))
for k in (1, 2, 5):
    pasa = np.mean([freivalds(A, B, Cmal, k, gen) for _ in range(2000)])
    print(f"k = {k}: el producto incorrecto pasa el {pasa:.4f} de las veces   (exacto: 2^-k = {2.0 ** -k:.4f})")

t0 = time.perf_counter(); _ = A @ B; t_mul = time.perf_counter() - t0
t0 = time.perf_counter(); freivalds(A, B, C, 10, gen); t_fr = time.perf_counter() - t0
print(f"\nn = {n}: A @ B tarda {1e3 * t_mul:.0f} ms; Freivalds con k = 10, {1e3 * t_fr:.1f} ms")

With one error, passing probability is exactly 1/21/2 per test, confirmed by measurement. Checking with ten vectors is much cheaper than the product, and the advantage grows linearly with nn.

Floating-point products need tolerance. A simple rounding model for a length-nn dot product computed at precision with unit roundoff uu is a random walk: error order unu\sqrt n times the square root of the sum of squared terms. Propagated to Cr\mat{C}\vb{r} it gives per-component noise scale un ((A∘A)(B∘B)(r∘r))1/2u\sqrt n\,\big((\mat{A}\circ\mat{A})(\mat{B}\circ\mat{B})(\vb{r}\circ\vb{r})\big)^{1/2}, where ∘\circ is elementwise product. Compare with ten times that scale. Here r\vb{r} is Gaussian rather than binary: in real arithmetic, if D≠0\mat{D} \ne \mat{0}, event Dr=0\mat{D}\vb{r} = \vb{0} has probability zero, so only tolerance limits detection.

[ ]Freivalds for a floating-point kernelBrowser
def freivalds_float(A, B, C, k, gen, c=10.0):
    """Comprueba un C calculado en baja precisión. La comprobación se hace en float64 y acepta si
    |A(Br) - Cr| <= c * ruido en cada componente."""
    u = np.finfo(C.dtype).eps / 2
    A64, B64, C64 = (M.astype(np.float64) for M in (A, B, C))
    n = A.shape[1]
    for _ in range(k):
        r = gen.standard_normal(C.shape[1])
        dif = A64 @ (B64 @ r) - C64 @ r
        ruido = u * np.sqrt(n) * np.sqrt((A64 ** 2) @ ((B64 ** 2) @ (r ** 2)))
        if np.any(np.abs(dif) > c * ruido):
            return False
    return True

n = 256
A32 = gen.standard_normal((n, n)).astype(np.float32)
B32 = gen.standard_normal((n, n)).astype(np.float32)
C32 = A32 @ B32                          # el «kernel» vigilado, en float32

# calibración: ¿cuánto vale |dif| / ruido cuando el producto es correcto?
r = gen.standard_normal(n)
A64, B64 = A32.astype(np.float64), B32.astype(np.float64)
cociente = np.abs(A64 @ (B64 @ r) - C32.astype(np.float64) @ r) / (np.finfo(np.float32).eps / 2 * np.sqrt(n) * np.sqrt((A64 ** 2) @ ((B64 ** 2) @ (r ** 2))))
print(f"producto correcto: |dif| / ruido llega a {cociente.max():.2f} (media {cociente.mean():.2f})")
falsas = np.mean([not freivalds_float(A32, B32, C32, 1, gen) for _ in range(300)])
print(f"falsas alarmas con c = 10: {falsas:.3f}")
for tam in (1.0, 1e-1, 1e-2, 1e-3):
    Cm = C32.copy()
    Cm[100, 7] += np.float32(tam)
    det = np.mean([not freivalds_float(A32, B32, Cm, 1, gen) for _ in range(300)])
    print(f"error de {tam:g} en una entrada (|c_ij| medio {np.abs(C32).mean():.1f}): detectado en {det:.2f} de las pruebas")

The model is well calibrated: for a correct product the discrepancy-to-noise-scale ratio is order 1, so factor 10 causes no false alarms. Errors of a tenth or more in an entry of typical size 13 are almost always caught in one test; errors of a thousandth, on the scale of accumulated float32 rounding, are not. This is the real boundary for any floating-point verifier.

Schwartz–Zippel in three uses: an identity between degree-45 polynomials in 10 variables, Tutte testing versus exhaustive matching search, and what happens with a field too small.

[ ]Schwartz–Zippel: identities and matchingsBrowser
P = 2**61 - 1                            # primo de Mersenne

def det_mod(M, p=P):
    """Determinante módulo p (primo) por eliminación gaussiana."""
    M = [fila[:] for fila in M]
    n, d = len(M), 1
    for c in range(n):
        piv = next((f for f in range(c, n) if M[f][c] % p), None)
        if piv is None:
            return 0
        if piv != c:
            M[c], M[piv] = M[piv], M[c]
            d = -d
        d = d * M[c][c] % p
        inv = pow(M[c][c], p - 2, p)
        for f in range(c + 1, n):
            factor = M[f][c] * inv % p
            if factor:
                M[f] = [(a - factor * b) % p for a, b in zip(M[f], M[c])]
    return d % p

rnd = random.Random(0)
# 1) det(Vandermonde) = prod_{i<j} (x_j - x_i): grado 45 en 10 variables, 10! = 3 628 800 monomios en el det
def vandermonde_ok(x):
    V = [[pow(xi, j, P) for j in range(len(x))] for xi in x]
    derecha = math.prod((x[j] - x[i]) % P for i in range(len(x)) for j in range(i + 1, len(x))) % P
    return det_mod(V) == derecha
print("Vandermonde en 20 puntos aleatorios:", all(vandermonde_ok([rnd.randrange(P) for _ in range(10)]) for _ in range(20)))

# 2) Tutte: hay emparejamiento perfecto <=> det de la matriz de Tutte no es nulo
def tiene_perfecto_tutte(n, aristas, rnd, p=P):
    T = [[0] * n for _ in range(n)]
    for u, v in aristas:
        x = rnd.randrange(1, p)
        T[u][v], T[v][u] = x, (-x) % p
    return det_mod(T, p) != 0            # error unilateral: solo puede fallar diciendo «no»

def tiene_perfecto_bruto(n, aristas):
    ady = {frozenset(e) for e in aristas}
    def rec(libres):
        if not libres:
            return True
        u = libres[0]
        return any(frozenset((u, v)) in ady and rec([w for w in libres[1:] if w != v]) for v in libres[1:])
    return rec(list(range(n)))

coinciden, con_perfecto = 0, 0
for _ in range(60):
    ar = [(u, v) for u in range(12) for v in range(u + 1, 12) if rnd.random() < 0.18]
    b = tiene_perfecto_bruto(12, ar)
    coinciden += tiene_perfecto_tutte(12, ar, rnd) == b
    con_perfecto += b
print(f"Tutte frente a fuerza bruta: {coinciden}/60 coinciden ({con_perfecto} grafos con emparejamiento perfecto)")

# 3) un cuerpo pequeño respecto al grado (12): el test falla de verdad
ar = [(2 * i, 2 * i + 1) for i in range(6)] + [(i, (i + 3) % 12) for i in range(12)]
rnd = random.Random(3)
for p in (5, 13, 101, 10007):
    fallos = sum(not tiene_perfecto_tutte(12, ar, rnd, p=p) for _ in range(1000)) / 1000
    print(f"p = {p:5d}: dice «no hay» en el {100 * fallos:4.1f} % de los intentos (cota d/|S| = {12 / (p - 1):.3f})")

The final graph has perfect matchings, so every “none” is an error. With p=5p = 5 and p=13p = 13 bound d/∣S∣d/\abs{S} is vacuous and actual error is 9–21%; with p=101p = 101 it falls to 1%, below bound 0.120.12, and with p=10007p = 10007 it disappears. With p=261−1p = 2^{61} - 1 the bound is 5×10−185\times 10^{-18}.

Balls and bins with dd choices, in pure Python so code matches the analysis.

[ ]Balls and bins with d choicesBrowser
def cargas(n, m, d, rnd):
    """m bolas en n cajas; cada bola mira d cajas uniformes y va a la menos cargada (empate: la primera)."""
    carga = [0] * n
    rand = rnd.randrange
    for _ in range(m):
        mejor = rand(n)
        for _ in range(d - 1):
            c = rand(n)
            if carga[c] < carga[mejor]:
                mejor = c
        carga[mejor] += 1
    return carga

rnd = random.Random(0)
print("      n   d=1  d=2  d=3    ln n/ln ln n   ln ln n/ln 2")
for n in (10**3, 10**4, 10**5):
    maximos = [max(cargas(n, n, d, rnd)) for d in (1, 2, 3)]
    print(f"{n:7d}   {maximos[0]:3d}  {maximos[1]:3d}  {maximos[2]:3d}       {math.log(n) / math.log(math.log(n)):5.2f}          {math.log(math.log(n)) / math.log(2):5.2f}")

n = 10**5
poisson = [1 - sum(math.exp(-1) / math.factorial(j) for j in range(k)) for k in range(9)]
for d in (1, 2):
    c = np.bincount(cargas(n, n, d, rnd))
    cola = c[::-1].cumsum()[::-1] / n          # fracción de cajas con carga >= k
    print(f"d = {d}, fracción con carga >= k:  " + "  ".join(f"{k}: {f:.1e}" for k, f in enumerate(cola)))
print("Poisson(1), P(X >= k):            " + "  ".join(f"{k}: {f:.1e}" for k, f in enumerate(poisson)))

With one choice, the load tail reproduces a mean-1 Poisson almost digit for digit, as Poisson approximation predicts. With two, the fraction of bins with load at least 3 is already order 10−210^{-2} and none reaches 4: the layered argument’s doubly exponential fall.

Finally amplification: the section example’s repetition count and the error from reusing a seed. Function freivalds_semilla creates its generator inside the loop with a fixed seed, a common mistake when passing a seed “for reproducibility.”

[ ]Amplifying, and amplifying badlyBrowser
def error_mayoria(k, eps):
    """P[Bin(k, eps) >= (k + 1)/2]: la mayoría de k ejecuciones (k impar) se equivoca."""
    return sum(math.comb(k, j) * eps**j * (1 - eps)**(k - j) for j in range((k + 1) // 2, k + 1))

eps, delta = 1 / 3, 1e-9
k1 = math.ceil(math.log(delta) / math.log(eps))
k2 = next(k for k in range(1, 1000, 2) if error_mayoria(k, eps) <= delta)
k3 = math.ceil(math.log(1 / delta) / (2 * (0.5 - eps) ** 2))
print(f"unilateral: k = {k1} (error {eps ** k1:.2e});  bilateral: mayoría exacta k = {k2}, Hoeffding k = {k3}")

def freivalds_semilla(A, B, C, k, semilla):
    for _ in range(k):
        gen = np.random.default_rng(semilla)      # MAL: el mismo r en todas las vueltas
        r = gen.integers(0, 2, size=C.shape[1])
        if not np.array_equal(A @ (B @ r), C @ r):
            return False
    return True

gen = np.random.default_rng(7)
pasa_fija = np.mean([freivalds_semilla(A, B, Cmal, 20, s) for s in range(400)])
pasa_bien = np.mean([freivalds(A, B, Cmal, 20, gen) for _ in range(400)])
print(f"k = 20 con semilla fija: el producto incorrecto pasa en {pasa_fija:.2f} de las semillas")
print(f"k = 20 con aleatoriedad nueva: pasa en {pasa_bien:.4f}   (teoría 2^-20 = {2 ** -20:.1e})")

With a reused seed, twenty repetitions are worth one: the wrong product passes for more than half the seeds, as expected from one test. With fresh randomness each time, theoretical probability is 10−610^{-6} and none passes in 400 attempts.

Lab: derandomize MAX-3SAT

Random 3-CNF formulas with 12 variables and 90 clauses, above the satisfiability threshold so the optimum is nontrivial. Compare average random assignments, the assignment derandomized by conditional expectations, and the exact optimum, calculated by vectorizing 212=40962^{12} = 4096 assignments.

[ ]MAX-3SAT: randomness, conditional expectations and optimumBrowser
def formula_3cnf(n, m, rnd):
    """m cláusulas con 3 variables distintas y signos al azar. Literal +i es x_i y -i es su negación."""
    return [tuple(v if rnd.random() < 0.5 else -v for v in rnd.sample(range(1, n + 1), 3)) for _ in range(m)]

def satisfechas(formula, x):
    """x[i] en {0, 1} para i = 1..n (x[0] no se usa)."""
    return sum(any((x[abs(l)] == 1) == (l > 0) for l in c) for c in formula)

def esperanza_condicionada(formula, x, fijadas):
    """E[#cláusulas satisfechas] con x_1..x_fijadas fijadas y el resto monedas justas."""
    total = 0.0
    for c in formula:
        libres, cierta = 0, False
        for l in c:
            if abs(l) <= fijadas:
                cierta |= (x[abs(l)] == 1) == (l > 0)
            else:
                libres += 1
        total += 1.0 if cierta else 1.0 - 0.5 ** libres
    return total

def desaleatorizar(formula, n):
    x = [0] * (n + 1)
    trayectoria = [esperanza_condicionada(formula, x, 0)]      # = 7m/8
    for i in range(1, n + 1):
        x[i] = 1
        e1 = esperanza_condicionada(formula, x, i)
        x[i] = 0
        e0 = esperanza_condicionada(formula, x, i)
        x[i] = 1 if e1 >= e0 else 0
        trayectoria.append(max(e0, e1))
    return x, trayectoria

def optimo_bruto(formula, n):
    X = (np.arange(2 ** n)[:, None] >> np.arange(n)) & 1      # una fila por asignación
    cuenta = np.zeros(2 ** n, dtype=np.int32)
    for c in formula:
        sat = np.zeros(2 ** n, dtype=bool)
        for l in c:
            sat |= X[:, abs(l) - 1] == (1 if l > 0 else 0)
        cuenta += sat
    return int(cuenta.max())

rnd = random.Random(0)
n, m = 12, 90
print(f"7m/8 = {7 * m / 8}")
print(" fórmula   azar (media de 200)   desaleatorizada   óptimo")
for t in range(8):
    F = formula_3cnf(n, m, rnd)
    azar = np.mean([satisfechas(F, [0] + [rnd.randint(0, 1) for _ in range(n)]) for _ in range(200)])
    x, tray = desaleatorizar(F, n)
    assert all(b >= a - 1e-9 for a, b in zip(tray, tray[1:]))     # la esperanza condicionada nunca baja
    print(f"    {t}           {azar:6.2f}                {satisfechas(F, x):3d}            {optimo_bruto(F, n):3d}")

The random-assignment average is about 7m/8=78.757m/8 = 78.75, as linearity predicts. The derandomized assignment satisfies 85–89 clauses: always above the guarantee (the assertion checks conditional expectation never falls), reaching optimum on half the formulas and never more than three clauses below. The guarantee is 7/87/8; typical behavior is much better because each greedy choice uses the particular formula’s structure.

The second route, pairwise independence: the 2L+12^{L+1} points of the small sample space for a large cut of a 200-vertex graph.

[ ]Derandomize with pairwise independenceBrowser
def lados_pareados(n, a, b):
    """X_v = <a, v> + b (mod 2) con v en binario: independientes por pares si (a, b) es uniforme."""
    return [(bin(a & v).count("1") + b) & 1 for v in range(n)]

def corte(aristas, lado):
    return sum(lado[u] != lado[v] for u, v in aristas)

rnd = random.Random(2)
n = 200
aristas = [(u, v) for u in range(n) for v in range(u + 1, n) if rnd.random() < 0.05]
m = len(aristas)
L = (n - 1).bit_length()
cortes = [corte(aristas, lados_pareados(n, a, b)) for a in range(2 ** L) for b in (0, 1)]
print(f"n = {n}, m = {m}: {len(cortes)} semillas frente a 2^{n} asignaciones")
print(f"media exacta sobre las semillas = {sum(cortes) / len(cortes):.2f}   m/2 = {m / 2}")
print(f"mejor semilla: {max(cortes)}   peor: {min(cortes)}")

lado = [0] * n                           # el voraz de las esperanzas condicionadas
ady = [[] for _ in range(n)]
for u, v in aristas:
    ady[u].append(v)
    ady[v].append(u)
for v in range(n):
    previos = [lado[w] for w in ady[v] if w < v]
    lado[v] = 1 if previos.count(0) > previos.count(1) else 0
print("esperanzas condicionadas:", corte(aristas, lado))

The mean over 512 seeds is exactly m/2m/2, as pairwise independence guarantees, and the best seed exceeds it. The worst cuts zero edges (a=0\vb{a} = \vb{0} puts all vertices on one side): a small sample space guarantees only the mean and must be enumerated. Conditional-expectation greedy, which examines the graph, achieves much more.

The library version

TaskToolNote
Global minimum cutnetworkx.stoer_wagner(G)deterministic, O(nm+n2log⁡n)\bigO(nm + n^2\log n), supports weights
Edge connectivitynetworkx.edge_connectivity(G)via flows
Maximum matchingnetworkx.max_weight_matching(G, maxcardinality=True)Edmonds, deterministic
Verify a productA @ (B @ r) versus C @ r with NumPynever np.allclose(A @ B, C) when saving work is the goal
Symbolic identitiessympy.expand, sympy.simplifyexact but exponential worst case
Independent generatorsnp.random.default_rng(semilla).spawn(k) or SeedSequence.spawnone independent stream per replica
[ ]networkx and SymPy versus randomized methodsBrowser
import networkx as nx
import sympy as sp

# dos comunidades densas unidas por tres aristas
rnd = random.Random(4)
G = nx.disjoint_union(nx.gnp_random_graph(25, 0.4, seed=1), nx.gnp_random_graph(25, 0.4, seed=2))
G.add_edges_from([(0, 30), (5, 41), (12, 27)])
valor, (S, Sc) = nx.stoer_wagner(G)
print(f"Stoer-Wagner: corte mínimo {valor}, lados de {len(S)} y {len(Sc)} vértices")

idx = {v: i for i, v in enumerate(G.nodes)}
A_ks = [(idx[u], idx[v], 1) for u, v in G.edges]
t0 = time.perf_counter()
mejor = min(karger_stein(G.number_of_nodes(), A_ks, rnd) for _ in range(3))
print(f"Karger-Stein (3 llamadas): {mejor}   en {time.perf_counter() - t0:.2f} s")

# el desarrollo simbólico crece como n!; la evaluación aleatoria, no
for n in (3, 4, 5):
    xs = sp.symbols(f"x0:{n}")
    V = sp.Matrix(n, n, lambda i, j: xs[i] ** j)
    t0 = time.perf_counter()
    dif = sp.expand(V.det(method="berkowitz") - sp.prod([xs[j] - xs[i] for i in range(n) for j in range(i + 1, n)]))
    print(f"n = {n}: SymPy confirma la identidad ({dif == 0}) en {1e3 * (time.perf_counter() - t0):.0f} ms")

For minimum cut, Stoer–Wagner is the default library choice: deterministic with no confidence parameters. Karger–Stein shines on large dense graphs and above all as an idea: contraction analysis shows at most O(n2α)\bigO(n^{2\alpha}) cuts of size at most αλ\alpha\lambda, supporting sampling in almost-linear algorithms and enumeration of all near-minimum cuts. For polynomial identities, SymPy is exact but cost grows with monomial count, n!n! in the determinant: n=5n = 5 already takes a fraction of a second and n=10n = 10 would be infeasible, whereas random-point evaluation in the earlier cell took milliseconds.

Common mistakes

Exercises

ProofKarger’s bound and the number of minimum cuts
Prove: Karger’s algorithm returns a particular minimum cut CC with probability at least 2/(n(n−1))2/(n(n-1)), and consequently a connected multigraph with nn vertices has at most n(n−1)/2n(n-1)/2 minimum cuts.
0
Let k=∣C∣=λ(G)k = \abs{C} = \lambda(G) and AiA_i be the event ‘contraction ii does not choose an edge of CC’.

Step 1 of 4. Why does every vertex of multigraph GiG_i before contraction ii have degree at least kk?

ProofA cut with half the edges, and how to find it
Prove: Every graph with mm edges has a cut with at least m/2m/2 edges, findable deterministically in time O(n+m)\bigO(n + m).
0
Place each vertex independently on a side with probability 1/21/2, and let XX be cut-edge count.

Step 1 of 4. What is E[X]\E[X]?

NumericKarger repetitions
A graph has 100 vertices. Using only one-run bound p≥2/(n(n−1))p \ge 2/(n(n-1)), what is the smallest number TT of independent Karger repetitions guaranteeing failure probability below 10−610^{-6}? (Both the exact calculation with (1−p)T(1 - p)^T and the one using e−pTe^{-pT} are accepted.)
QuizAmplify according to error type
You have two decision algorithms. The first has one-sided error 1/31/3 (yes is always correct and on yes inputs it fails with probability at most 1/31/3). The second has two-sided error 1/31/3. How do you amplify them to error 10−910^{-9}, and how many independent repetitions does each need?
CodeFreivalds with k repetitions
Implement freivalds(A, B, C, k, gen) for integer NumPy matrices: return False if any of k tests with a vector r uniform on {0, 1}^n, generated with gen (an np.random.Generator), shows A @ (B @ r) != C @ r, and True if all k tests pass. Do not compute A @ B: tests use matrices that raise an error if two matrices are multiplied. For k = 0 return True.
import numpy as np

def freivalds(A, B, C, k, gen):
  """True si C pasa k pruebas de Freivalds; False en cuanto una prueba encuentra un testigo."""
  # tu código: k vectores r en {0,1}^n con gen, y compara A @ (B @ r) con C @ r
  return True
Shift+Enter to run
NumericA 64-bit hash birthday
Assign every document a uniform 64-bit hash. Around how many documents does the probability that two share a hash reach 1/21/2? Use approximation m≈2nln⁡2m \approx \sqrt{2n\ln 2} with n=264n = 2^{64}.
NumericSurvival in Karger–Stein
The first Karger–Stein call on a graph of n=1000n = 1000 vertices contracts to t=⌈1+n/2⌉t = \lceil 1 + n/\sqrt 2\rceil vertices. What lower bound t(t−1)/(n(n−1))t(t-1)/(n(n-1)) applies to the probability that a particular minimum cut survives that contraction?
NumericWhat size S?
You want to check whether a total-degree-50 polynomial in 3 variables is identically zero with one evaluation at a random point of S3S^3, with probability of declaring a nonzero polynomial zero at most 10−610^{-6} by Schwartz–Zippel. What smallest ∣S∣\abs{S} guarantees this?
NumericErdős’ bound for k = 10
What is the largest nn for which (n10)21−(102)<1\binom{n}{10}2^{1 - \binom{10}{2}} < 1? For that nn a two-coloring of KnK_n exists without monochromatic K10K_{10}, so R(10,10)>nR(10, 10) > n.
QuizKarger on a cycle
Run Karger once on cycle C20C_{20}. Which claim is correct?

Summary

Key idea
Randomness works when the target is abundant (witnesses of C≠AB\mat{C} \ne \mat{A}\mat{B}, points where a polynomial does not vanish) or the danger is rare (minimum-cut edges); repeating with fresh coins turns a small advantage into practical certainty, and sometimes the analysis itself teaches how to remove randomness.
  • Karger randomly contracts edges and preserves a particular minimum cut with probability at least 2/(n(n−1))2/(n(n-1)) because minimality forces high degrees. This yields at most (n2)\binom{n}{2} minimum cuts and (n2)ln⁡(1/δ)\binom{n}{2}\ln(1/\delta) sufficient repetitions. Karger–Stein branches only as risk rises and achieves Ω(1/log⁡n)\Omega(1/\log n) per call in time O(n2log⁡n)\bigO(n^2\log n).
  • Freivalds checks C=AB\mat{C} = \mat{A}\mat{B} in O(n2)\bigO(n^2) with one-sided error ≤1/2\le 1/2 per test; floating point requires a tolerance calibrated to rounding noise, and a random vector prevents errors from always canceling.
  • Schwartz–Zippel: a nonzero degree-dd polynomial vanishes at a random point of SnS^n with probability at most d/∣S∣d/\abs{S}. It gives polynomial identity testing, Tutte perfect-matching tests and string fingerprints, provided ∣S∣≫d\abs{S} \gg d.
  • Amplification: one yes suffices for one-sided error, which falls as εk\varepsilon^k; two-sided error uses voting and falls as e−2k(1/2−ε)2e^{-2k(1/2-\varepsilon)^2}. Repetitions must be independent.
  • Balls and bins: first collision near 2nln⁡2\sqrt{2n\ln 2} balls, all bins occupied after nln⁡nn\ln n, maximum load Θ(log⁡n/log⁡log⁡n)\Theta(\log n/\log\log n) with m=nm = n. With two choices, ln⁡ln⁡n/ln⁡2+O(1)\ln\ln n/\ln 2 + \bigO(1): exponential improvement used in load balancers, hash tables and expert-capacity analysis.
  • The probabilistic method proves existence by averaging (m/2m/2-edge cuts, 7/87/8 of 3-SAT clauses, R(k,k)>2k/2R(k,k) > 2^{k/2}), and derandomization by conditional expectations or limited independence turns some proofs into deterministic algorithms.