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 , solve flow problems, one for each possible , 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 , supposedly the product of two matrices. Recomputing it to check costs as much as computing it: with the usual algorithm, with the best known (the matrix multiplication exponent). But this is unnecessary. Take a random zero–one vector and compare with : three matrix–vector products, , and if the sides differ with probability at least . 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 , half of vectors 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 , some outcome is at least . 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 partitions into two nonempty sets ; its size is the number of edges with one endpoint on each side. The global minimum cut is the smallest cut size; neither nor is fixed.
The key operation is contracting edge : replace and with one vertex , each edge touching or now touches , and delete edges between and , which would become loops. Other parallel edges remain: hence multigraphs are needed. Two facts make contraction useful:
- Contraction creates no cuts. Each vertex of is a set of vertices of , so a cut of is a cut of with exactly the same edges. Thus .
- A cut survives iff none of its edges is contracted. If is a cut of and , endpoints of lie on the same side and remains a cut of .
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).
Success probability
Proof
Let be the event “contraction does not choose an edge of ,” for . By point 2 above, the algorithm returns exactly iff all occur.
Before contraction , vertices remain, and if occurred, current multigraph still contains the edges of . Every vertex of has degree at least : its degree is the size of the cut separating it from the rest, which is also a cut of (point 1). Summing degrees, has edges. Since the edge is uniformly chosen,
The product rule gives
because the product telescopes: the last two numerators, , and first two denominators, , 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 be the minimum cuts. Events “Karger returns ” are disjoint, and each has probability at least . Their sum is at most 1, so . In , choosing any two of the edges gives a cut of size 2, the minimum: exactly .
∎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 there are graphs with a unique minimum cut whose success probability decays as (measure it on a necklace of multiple edges in the implementation).
Repeat until confident
One run succeeds with probability . Repeating times with independent randomness and returning the smallest found cut fails only if every run fails:
using . With , 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 after shuffling, and total for high probability is . For multiedges with multiplicity , sort exponential clocks of rate (if , the minimum among them is edge with probability ), as in the code.
Karger–Stein: repeat only where it hurts
Why so many repetitions? Risk is uneven: at step the cut is lost with probability , negligible initially and huge at the end (with three vertices, up to ). 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 survives until vertices remain is the same telescoping product stopped earlier:
( suffices because .)
Success probability. Let be the probability of returning a particular minimum cut. Each branch succeeds if the cut survives contraction (probability ) and recursion succeeds; branches are independent. Thus,
Count levels from below: (brute force) and . By induction, : function is increasing on , and is equivalent to , i.e. . There are levels, so
Time. With the adjacency matrix (multiplicities in entries), contracting to vertices costs , and . Since , this is the balanced case of the master theorem: . Repeating times gives error ; with , total, versus for repeating Karger with the same dense representation.
Freivalds: verify without recomputing
Proof
Let and let be a nonzero entry. Bound ; it suffices to bound the probability that component vanishes:
Use the principle of deferred decisions: the are independent, so first draw all except , fixing , and draw last. Given , equation has at most one solution , and takes that value with probability at most . Since the bound holds for each , it also holds unconditionally.
∎The proof gives more. If is uniform on for a finite set , the same calculation gives : with entries in , one test fails at most one time in ten. Bound is exact: if has only one nonzero entry , the test passes exactly when .
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 product at fraction of product cost: 0.07% with and .
There are two engineering details. First is floating point: and 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 . Classical algorithm-based fault tolerance (ABFT, Huang and Abraham, 1984) adds row and column checksums, Freivalds with fixed vector applied on the right () and left (). 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 ( and in one row, and in the same columns of another) fool both. With random no error pattern passes with probability exceeding . The monitored kernel may be tiled matrix multiplication in Triton.
Schwartz–Zippel: polynomial identities
Freivalds is a special case of a broader fact. Component of is a nonzero degree-1 polynomial in variables evaluated at a random point. A nonzero polynomial cannot vanish at “too many” points.
Proof
Induct on . For , a nonzero one-variable degree- polynomial has at most roots, so probability is at most .
For , write in powers of : , where is the largest exponent of with . Since contributes terms of degree , . Let be event “”. By induction, . If does not occur, fixing makes a nonzero polynomial in of degree , and by the case it vanishes at with probability at most . Hence
∎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 determinant has . Evaluation at a random point of a large finite field costs one evaluation and errs with probability at most , only in one direction: a nonzero value certainly proves a nonzero polynomial.
Perfect matchings with determinants
Let be a graph with vertices . Its Tutte matrix has a variable per edge with , and entries , , and where no edge exists. It is skew-symmetric.
Proof
If is a perfect matching, assign value 1 on edges of and 0 elsewhere. Reordering vertices in pairs makes block diagonal with blocks of determinant 1. A polynomial with a nonzero value is nonzero.
Conversely, , and only permutations where every is an edge contribute (a term with 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 to . These terms cancel pairwise. If , 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 by a random value from with large and compute the numeric determinant in , or in . The symbolic determinant has degree , so the test errs with probability at most , 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 and of length over an integer alphabet, view them as polynomials and and compare with for random . If , is a nonzero polynomial of degree at most and collision probability is at most . This is the fingerprint used by Rabin–Karp, and with and per-comparison collision probability is below . It is also polynomial universal hashing: the analysis is the same.
Probability amplification
Karger’s success probability is tiny and Freivalds errs with probability ; neither suffices as-is. Repetition solved both. Probability amplification studies how to combine independent Monte Carlo runs so error falls exponentially in ; the combination rule depends on error type.
One-sided error. Suppose a decision algorithm answers “yes” with probability at least when the correct answer is yes, and always answers no otherwise. A yes is then proof. Run it times and answer yes if any run does. Error is possible only on a yes input and only if all runs fail:
Freivalds has this form (yes means “found a witness of ”), as does Karger, with “keep the smallest cut” playing the role of “one yes suffices.” Notice can be very close to 1: Karger has , and it still works, with .
Two-sided error. If the algorithm can err in both directions with probability , no individual answer is proof; vote.
Proof
Let be the number of erroneous runs, a sum of independent indicators with mean at most each, so . Majority errs only if , i.e. . Hoeffding’s inequality for sums of independent variables in gives ; with the bound follows.
∎Concrete figures illustrate the difference. With and target , one-sided error needs repetitions. Two-sided error needs by Hoeffding’s bound and 305 by the exact binomial tail (with odd to avoid ties). The order-of-magnitude difference arises because in the one-sided case each repetition multiplies error by , whereas in the two-sided case it asymptotically multiplies by only in the bound, or in the exact binomial tail rate.
Two observations provide context. First, constant is arbitrary. Any algorithm with error , for a polynomial , can be amplified to error using repetitions. Thus BPP (decision problems with bounded two-sided-error randomized polynomial algorithms) is defined with 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 becomes Monte Carlo by cutting it off after steps, failing with probability at most by Markov’s inequality.
Balls and bins
Many randomized-algorithm questions are fundamentally the same: throw balls, each uniformly and independently into one of 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 balls land in distinct bins is
and the approximation is good when . Collision probability reaches near : with , starting at people. For a 64-bit hash the first collision is likely near elements: far fewer than the possible values. This is why content fingerprints use 128 or 256 bits, and expected colliding-pair count follows directly from linearity of expectation.
Coupons: the last empty bin. The number of balls until all bins are full is a sum of geometric waiting times: with bins occupied, the next ball lands in a new one with probability . Thus,
It is concentrated: after balls, a particular bin is still empty with probability , and by the union bound some bin remains empty with probability at most . Ensuring no server lacks work or sampling all elements of a set requires random attempts, not .
Maximum load
With mean load is 1, but maximum load is not.
Proof
Bin 1 receives at least balls only if some subset of balls all land in it. By the union bound over subsets,
using . It remains to show , i.e. . Since increases with for , it suffices to check unrounded . With (true for ), and
Function reaches its maximum at , exactly , so the parenthesis is always at least and . A second union bound, now over bins, gives .
∎The bound is order-tight: with probability maximum load is (Mitzenmacher and Upfal, chapter 5, using Poisson approximation). But converges exasperatingly slowly: with , 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 but with high probability.
The power of two choices
Change one thing: each ball inspects 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 to ; moving from two to three merely divides it by .
Why it happens (layered argument). Let be the number of bins with load at least at the end. For a ball to land at height or more, its bins must already have load at least , occurring with probability at most . There are balls, so in expectation the number of bins with load at least satisfies
Since at most bins can have 4 or more balls, , and recurrence gives : the fraction falls doubly exponentially. It drops below when , i.e. for , yielding maximum load . The rigorous proof replaces each “” with a Chernoff bound holding with high probability at every layer, stopping when drops to , 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 is approximately the tail of a mean-1 Poisson, decaying as : only slightly faster than exponential.
An even more surprising version: if balls are thrown, with one choice the fullest bin exceeds mean by , growing with . With two choices the gap between fullest bin and mean remains , independent of (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 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 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 has , then with positive probability, so an outcome exists with . 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 independently with probability . For each edge let indicate whether and lie on different sides: . Cut size is and by linearity . A random variable cannot always be below its mean, so some partition cuts at least edges.
∎Only the fact that each pair of vertices lies on opposite sides with probability was used: pairwise independence suffices, useful for derandomization. The proof also gives a randomized algorithm: since and is integral, with , hence . Repeating until success is Las Vegas with expected attempts.
Proof
Under a uniform assignment, a clause with three distinct variables is false only if all three literals are false, with probability . By linearity, expected satisfied clauses are , and some assignment attains that. If , some assignment satisfies at least clauses, i.e. all.
∎The bound is tight in two senses. The eight clauses with all possible signs on are not jointly satisfiable. And Håstad (2001) proved that for any , guaranteeing 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 red or blue independently with probability . For each set of vertices, the probability all its edges have the same color is . By the union bound, the probability some is monochromatic is at most , so some coloring has none. With , and for .
∎Equivalently, a random coloring of has no monochromatic with . More than seventy years later, the best known explicit construction (Li, 2023, arXiv:2303.06802, using two-source extractors) guarantees none only with for some constant : 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 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 be decisions (here, each vertex’s side) and the final value. By total expectation (conditional expectation), if decisions already made are ,
so one value of has conditional expectation at least as large as the current one. Always choosing it makes sequence nondecreasing, starting at and ending, after all decisions, at actual value 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 already placed, each edge with both endpoints placed is cut or not, and each edge with a pending endpoint is cut with probability :
When placing vertex , 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 time, and conditional expectations prove it guarantees .
MAX-3SAT works similarly: with some variables fixed, an already satisfied clause counts 1, and one with free literals and the rest false counts (with , zero). Fix each variable to the value with greater total; the result satisfies at least 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 , write them in binary with bits, choose and uniformly and define
For , is uniform because , and independent of ; so is uniform on . The sample space has only points and expected cut remains exactly . Enumerating every seed, , and keeping the best yields a deterministic algorithm in time . The same trick with -independence gives spaces of size , 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 with minimum cuts, then a random graph with a unique minimum cut.
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 matches theory (the difference is sampling noise: typical error with 30 000 runs is ), and all 45 minimum cuts appear. On the random graph success probability is , eighteen times the bound: the worst case is not typical.
Now Karger–Stein. To avoid carrying parallel-edge lists through repeated contractions, store multiplicities and sort exponential clocks of rate , equivalent to shuffling the 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.
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 , decaying as : between 1.8 and 3.1 times the bound in the table, with the gap growing slowly with . With multiplicity instead of 5, the exponent is , so the exponent in bound cannot be improved. Karger–Stein’s column declines slowly, as predicts: with , 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 versus dominates as grows.
Freivalds with exact integers. Introduce one error in a matrix of 90 000 entries and measure how often it passes.
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 per test, confirmed by measurement. Checking with ten vectors is much cheaper than the product, and the advantage grows linearly with .
Floating-point products need tolerance. A simple rounding model for a length- dot product computed at precision with unit roundoff is a random walk: error order times the square root of the sum of squared terms. Propagated to it gives per-component noise scale , where is elementwise product. Compare with ten times that scale. Here is Gaussian rather than binary: in real arithmetic, if , event has probability zero, so only tolerance limits detection.
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.
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 and bound is vacuous and actual error is 9–21%; with it falls to 1%, below bound , and with it disappears. With the bound is .
Balls and bins with choices, in pure Python so code matches the analysis.
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 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.”
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 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 assignments.
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 , 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 ; typical behavior is much better because each greedy choice uses the particular formula’s structure.
The second route, pairwise independence: the points of the small sample space for a large cut of a 200-vertex graph.
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 , as pairwise independence guarantees, and the best seed exceeds it. The worst cuts zero edges ( 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
| Task | Tool | Note |
|---|---|---|
| Global minimum cut | networkx.stoer_wagner(G) | deterministic, , supports weights |
| Edge connectivity | networkx.edge_connectivity(G) | via flows |
| Maximum matching | networkx.max_weight_matching(G, maxcardinality=True) | Edmonds, deterministic |
| Verify a product | A @ (B @ r) versus C @ r with NumPy | never np.allclose(A @ B, C) when saving work is the goal |
| Symbolic identities | sympy.expand, sympy.simplify | exact but exponential worst case |
| Independent generators | np.random.default_rng(semilla).spawn(k) or SeedSequence.spawn | one independent stream per replica |
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 cuts of size at most , 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, in the determinant: already takes a fraction of a second and would be infeasible, whereas random-point evaluation in the earlier cell took milliseconds.
Common mistakes
Exercises
Step 1 of 4. Why does every vertex of multigraph before contraction have degree at least ?
Step 1 of 4. What is ?
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 TrueSummary
- Karger randomly contracts edges and preserves a particular minimum cut with probability at least because minimality forces high degrees. This yields at most minimum cuts and sufficient repetitions. Karger–Stein branches only as risk rises and achieves per call in time .
- Freivalds checks in with one-sided error 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- polynomial vanishes at a random point of with probability at most . It gives polynomial identity testing, Tutte perfect-matching tests and string fingerprints, provided .
- Amplification: one yes suffices for one-sided error, which falls as ; two-sided error uses voting and falls as . Repetitions must be independent.
- Balls and bins: first collision near balls, all bins occupied after , maximum load with . With two choices, : exponential improvement used in load balancers, hash tables and expert-capacity analysis.
- The probabilistic method proves existence by averaging (-edge cuts, of 3-SAT clauses, ), and derandomization by conditional expectations or limited independence turns some proofs into deterministic algorithms.