Why Monte Carlo / Las Vegas Algorithms Matters
Imagine checking a large matrix product produced by another program. Recomputing every entry gives a direct answer, but it may cost almost as much as producing the product. Randomly testing a few carefully chosen projections can detect an incorrect answer much faster, at the price of occasionally missing an error. Now imagine finding a median: random pivots can make the search fast while preserving the exact answer for every pivot choice.
These are two different uses of randomness. Monte Carlo algorithms allow a controlled probability of an incorrect answer, usually within a specified work budget. Las Vegas algorithms return only correct answers, while their running time depends on the random choices and is analyzed in expectation. These names classify guarantees; they do not describe one common function or one particular implementation.
This lesson implements Freivalds' matrix-product test as the Monte Carlo example and randomized three-way Quickselect as the Las Vegas example. You will trace an actual false acceptance, follow an exact selection through several pivots, prove the relevant guarantees, and learn why repeating a seeded run is different from amplifying an error bound.
Randomness can buy speed by allowing a small chance of a wrong verdict, or by varying the work needed to obtain an exact result. Monte Carlo analysis bounds the error probability under a stated random model; Las Vegas analysis proves correctness for every completed run and bounds expected running time. Always identify which quantity is random and which guarantee is unconditional.
Core Concepts and Terminology
For an input $x$ and random choices $R$, write the output as $A(x;R)$ and the work as $T(x;R)$. A Monte Carlo guarantee might say $\Pr_R[A(x;R)\text{ is wrong}]\le\delta$ for every fixed valid $x$, together with a bounded amount of work. A Las Vegas guarantee says the returned answer is correct for every allowed choice sequence, with a finite expected running time over $R$ and termination with probability $1$ in the stated model.
The Monte Carlo task here is to decide whether $AB=C$ for square matrices over the field $\mathbb F_q$, with $q=1000003$. Every entry is represented by a residue in $[0,q)$. A round draws a vector $r\in\{0,1\}^n$ and compares $A(Br)$ with $Cr$, with all arithmetic modulo $q$. A mismatch proves inequality. A match can happen even when the product is wrong.
The Las Vegas task is to return the element at zero-based rank $k$ in the sorted order of an integer array, counting duplicates. Quickselect draws a pivot, partitions into smaller, equal, and larger values, and retains only the region containing rank $k$. It does not need to guess whether the selected answer is correct: the partition invariant establishes that fact.
| Term | Meaning and role in these examples |
|---|---|
| Monte Carlo | A randomized computation with a quantified possibility of error; an incorrect product may pass Freivalds' test. |
| Las Vegas | A randomized computation returning an exact answer, with random work; every valid Quickselect pivot sequence preserves the target rank. |
| One-sided error | Only one verdict can be wrong. Here REJECT is conclusive, while ACCEPT can falsely claim equality. |
| Two-sided error | Either verdict may be wrong; majority repetition needs an advantage over chance and its own analysis. |
| Witness | A vector $r$ for which $A(Br)\ne Cr$ is a checkable certificate that $AB\ne C$. |
| Amplification | Independent repetitions reduce the probability of a wrong result; all rounds must pass in this one-sided test. |
| Error budget | A chosen bound $\delta$; $t\ge\lceil\log_2(1/\delta)\rceil$ independent Freivalds rounds suffice. |
| Expected time | Average work over the algorithm's random choices for a fixed input, rather than an average over friendly inputs. |
| Seeded replay | Reproducing the same choice sequence to debug and compare implementations. It does not supply independent repetitions. |
| Explicit unknown | A timeout or exhausted search budget that declines to answer; it must not be silently turned into a claimed exact result. |
“Las Vegas” does not mean that every execution must have an unbounded worst case. Quickselect's partition work has a quadratic worst-case bound even though its expected work is linear. Conversely, a Monte Carlo algorithm can stop early on a decisive witness; bounded work need not mean identical work on every run.
How Monte Carlo / Las Vegas Algorithms Works, Step by Step
For Freivalds' test:
- Validate that all three matrices are equally sized, square, and contain valid field residues. Choose a positive round budget $t$.
- Draw $n$ bits for the current vector $r$. The probability proof assumes these bits are independent and fair.
- Compute $u=Br$, then $v=Au$, and separately $w=Cr$. Parenthesizing as matrix–vector products avoids forming the full matrix product.
- If $v\ne w$, return
REJECTand retain $r$ as a witness. No later round can make an unequal product equal. - If all $t$ rounds match, return
ACCEPT. The algorithm has accepted the equality claim, but a false acceptance remains possible.
For Quickselect, work on a copy so the caller's input is unchanged. Maintain inclusive active bounds lo,hi and the absolute target index $k$. Choose a pivot from that interval and partition with indices lt,i,gt. During the scan, positions before lt are smaller than the pivot, positions from lt to i-1 are equal, positions after gt are larger, and positions from i to gt are still unknown.
If the current value is smaller, swap it into the left region and advance both lt and i. If it is larger, swap it with position gt, decrease gt, and examine the replacement at i next. If equal, advance i. Once the unknown region is empty, keep the left region when $k\lt\mathrm{lt}$, keep the right region when $k\gt\mathrm{gt}$, or return when $\mathrm{lt}\le k\le\mathrm{gt}$. The equality block is nonempty because the pivot was selected from the active interval.
flowchart TD
A["Choose the problem and guarantee"] --> B{"Matrix verification or selection?"}
B -->|Verification| C["Validate matrices; set round budget"]
C --> D["Draw a vector; compute A(Br) and Cr"]
D --> E{"Vectors differ?"}
E -->|Yes| F["REJECT with an exact witness"]
E -->|No| G{"Round budget exhausted?"}
G -->|No| D
G -->|Yes| H["ACCEPT; one-sided error remains"]
B -->|Selection| I["Validate rank; copy input"]
I --> J["Draw a pivot; partition three ways"]
J --> K{"Target in equality block?"}
K -->|Yes| L["Return exact selected value"]
K -->|No| M["Keep the smaller active interval containing k"]
M --> J
The programs deliberately keep these stopping rules separate. A matching projection is sufficient for one Monte Carlo round to pass. Quickselect stops only when an ordering invariant identifies the answer exactly. Random choices alone are not a certificate of either equality or balance.
Worked Example with a Full Trace
Use the following matrices over $\mathbb F_{1000003}$:
$$A=\begin{pmatrix}1&2\\3&4\end{pmatrix},\qquad B=\begin{pmatrix}2&0\\1&2\end{pmatrix},\qquad AB=\begin{pmatrix}4&4\\10&8\end{pmatrix}.$$
Give the verifier the incorrect claimed product
$$C=\begin{pmatrix}3&5\\10&8\end{pmatrix},\qquad D=AB-C=\begin{pmatrix}1&-1\\0&0\end{pmatrix}.$$
The displayed $-1$ denotes its field residue $q-1$. Here $Dr=0$ precisely when the two coordinates of the binary vector are equal. Enumerating all four possibilities gives:
| Vector $r$ | $Br$ | $A(Br)$ | $Cr$ | Verdict for the incorrect product |
|---|---|---|---|---|
| $(0,0)^{\mathsf T}$ | $(0,0)^{\mathsf T}$ | $(0,0)^{\mathsf T}$ | $(0,0)^{\mathsf T}$ | ACCEPT: the error is hidden. |
| $(0,1)^{\mathsf T}$ | $(0,2)^{\mathsf T}$ | $(4,8)^{\mathsf T}$ | $(5,8)^{\mathsf T}$ | REJECT: a witness. |
| $(1,0)^{\mathsf T}$ | $(2,1)^{\mathsf T}$ | $(4,10)^{\mathsf T}$ | $(3,10)^{\mathsf T}$ | REJECT: a witness. |
| $(1,1)^{\mathsf T}$ | $(2,3)^{\mathsf T}$ | $(8,18)^{\mathsf T}$ | $(8,18)^{\mathsf T}$ | ACCEPT: the errors cancel. |
Under uniform independent bits, the one-round false-acceptance probability is exactly $1/2$ for this input. The runnable programs use the recurrence $s_{j+1}=16807s_j\bmod2147483647$ and take each output's parity as a bit. Starting at seed $7$, the first outputs are $117649,1977326743,621132276,452154665$, yielding first $r=(1,1)^{\mathsf T}$ and then $r=(0,1)^{\mathsf T}$. A one-round call falsely accepts; a four-round-budget call rejects at round $2$, using four raw outputs. Each call starts a new generator with its specified seed.
For the correct product, a separate four-round call with seed $7$ tests vectors $(1,1)$, $(0,1)$, $(1,1)$, and $(0,0)$ and accepts after eight raw draws. These seeded observations demonstrate the mechanics; the ideal probability bound is not a statistical guarantee about this particular deterministic stream.
Now select zero-based rank $k=4$ from $[9,1,8,2,7,3,6,4,5]$, using seed $11$. Bounded sampling uses the raw value minus one and rejects an uneven suffix of the generator's output domain before reducing modulo the active length. The first three raw outputs are $184877,959744092,669281627$, with no rejected draws here.
| Partition | Active indices | Chosen index / value | Work array after the partition | Equal block | Next action | Cumulative key comparisons |
|---|---|---|---|---|---|---|
| $1$ | $[0,8]$ | $7$ / $4$ | $[1,3,2,4,7,6,8,5,9]$ | $[3,3]$ | Keep $[4,8]$. | $15$ |
| $2$ | $[4,8]$ | $5$ / $6$ | $[1,3,2,4,5,6,8,9,7]$ | $[5,5]$ | Keep $[4,4]$. | $24$ |
| $3$ | $[4,4]$ | $4$ / $5$ | $[1,3,2,4,5,6,8,9,7]$ | $[4,4]$ | Return $5$. | $26$ |
Every tested less-than comparison counts once. When it fails, the subsequent greater-than comparison counts once more. Thus the final singleton partition contributes two comparisons. The copied work array is not fully sorted; finding one order statistic does not require sorting either discarded region.
Trace It by Hand
After the first false acceptance with $r=(1,1)^{\mathsf T}$, predict what the next vector $(0,1)^{\mathsf T}$ reveals. It selects the second columns, giving $Br=(0,2)^{\mathsf T}$, $A(Br)=(4,8)^{\mathsf T}$, and $Cr=(5,8)^{\mathsf T}$, so the unequal first coordinates certify rejection. For Quickselect, rank $4$ lies to the right of the first equality block $[3,3]$; keep the absolute target index $4$ while restricting the active interval to $[4,8]$.
Implementation in Python, C++, and Java
Each panel contains both complete examples, independent inputs, seeded generators, input validation, diagnostics, and the same sample output. Matrix dimensions are limited to $1\le n\le128$, the round budget to $1\le t\le1000$, and entries to residues in $[0,1000003)$. Quickselect accepts $1$ through $10000$ signed $32$-bit integer values and a valid zero-based rank. Both routines leave caller-owned arrays unchanged.
The matrix task is equality over the stated field. The code does not certify arbitrary integer-matrix equality or approximate floating-point equality. Reducing arbitrary integer inputs modulo one prime without a separate argument could hide a nonzero integer error that is a multiple of that prime.
For safe native arithmetic, the generator uses signed $64$-bit state updates. Each matrix–vector product also uses a $64$-bit multiplication and reduces the accumulator after every term. Its intermediate sum is at most $(q-1)^2+(q-1)\lt2^{63}$; an overflowing $32$-bit product would invalidate the computation before the modular reduction could help.
For a bound $m$, below sets $L=(P-1)-((P-1)\bmod m)$, draws $z=s-1$, rejects $z\ge L$, and returns $z\bmod m$. Uniform independent raw values would make this uniform on $[0,m)$. The recurrence is a reproducibility tool with correlated outputs, so neither independence nor the ideal error or expected-time bound follows merely from using a seed.
Run Python 3 directly, compile C++ with g++ -std=c++14 -O2 main.cpp -o randomized, or compile Java 17 or later with javac Main.java and run java Main. All three print these eleven lines:
good / 4 rounds = ACCEPT, rounds=4, draws=8bad / 1 round = ACCEPT, rounds=1, draws=2bad / 4 rounds = REJECT, rounds=2, draws=4rejecting witness = [0,1]quickselect k=4: value=5, partitions=3, comparisons=26, draws=3partition 1: range=[0,8], pivot index=7, pivot=4, equal=[3,3]partition 2: range=[4,8], pivot index=5, pivot=6, equal=[5,5]partition 3: range=[4,4], pivot index=4, pivot=5, equal=[4,4]work = [1,3,2,4,5,6,8,9,7]input unchanged = 1checks = PASS
The final check intentionally expects the bad product's one-round acceptance: that fixture demonstrates an allowed Monte Carlo error. General testing must establish the one-sided property and its mathematical bound, rather than asserting that every bad product is rejected by every seed.
Complexity, Correctness, and Invariants
For Freivalds, let $D=AB-C$. If $D=0$, then $Dr=0$ for every vector, so a correct product is never rejected. If $D\ne0$, choose a nonzero entry $D_{ij}$ in one nonzero row. Condition on every coordinate of $r$ except $r_j$. The row equation has the form
$$D_{ij}r_j+c=0.$$
The two choices $r_j=0$ and $r_j=1$ cannot both satisfy this equation because their results differ by the nonzero field element $D_{ij}$. A fresh independent fair bit therefore makes the row vanish with probability at most $1/2$, and the whole vector can vanish only if that row does. Thus $\Pr[Dr=0]\le1/2$ for a fixed incorrect product.
With $t$ independent rounds, acceptance requires every projection to miss the error:
$$\Pr[\text{false acceptance}]\le2^{-t},\qquad t\ge\left\lceil\log_2\frac1\delta\right\rceil\ \Longrightarrow\ \Pr[\text{error}]\le\delta.$$
For example, $t=20$ gives an ideal upper bound $2^{-20}=1/1048576$. This bounds the chance that a fixed incorrect input passes the randomized experiment. It is not the posterior probability that an accepted input is wrong; that would also require a model for how inputs are chosen.
One round performs three dense matrix–vector products, each costing $\Theta(n^2)$ field operations. Validation also costs $\Theta(n^2)$. Correct products execute all rounds, taking $\Theta(tn^2)$ time. Incorrect products can reject in one round; under independent ideal rounds, the expected number executed is at most $\sum_{j=0}^{t-1}2^{-j}\lt2$, so their expected total work is $O(n^2)$ with early stopping. The work bound for any input is $O(tn^2)$, and extra vector storage is $O(n)$ beyond the three input matrices.
Quickselect preserves the input multiset and keeps the target's absolute sorted position inside the active interval. Every retained interval is strictly shorter because the nonempty pivot-equality block is either discarded with the other side or contains the returned answer. Its partition phase terminates for every sequence of valid pivot choices and returns an exact selected value.
With uniform independent pivots, a pivot in the middle half of the active sorted positions occurs with constant probability and shrinks any retained side to at most about three quarters of the previous size. The expected number of partitions before such a reduction is constant. Summing the geometrically decreasing scan lengths gives $O(N)$ expected selection work for input length $N$, including duplicates; the first scan already costs $\Omega(N)$. Repeated extreme pivots can instead produce quadratic work.
| Method | Time guarantee | Correctness, space, and assumptions |
|---|---|---|
| Recompute the matrix product with three nested loops | $\Theta(n^3)$ field operations | Exact over the field; comparison can be accumulated without storing another full matrix. This is the straightforward baseline, not a lower bound on all deterministic methods. |
| Freivalds with $t$ rounds | Best $\Theta(n^2)$; worst $\Theta(tn^2)$; bad-input expected $O(n^2)$ with early rejection | One-sided false acceptance at most $2^{-t}$ under independent fair vectors; $O(n)$ extra space. A correct input uses all rounds. |
| Randomized three-way Quickselect | Best and ideal expected $\Theta(N)$; worst $O(N^2)$ partition work | Exact for every valid pivot sequence; expected bound assumes uniform independent pivots. The copied array and recorded trace use $O(N)$ space. |
| Quickselect code with explicit raw sampling | $O(N^2+D)$ worst-case work for actual draw count $D$ | Rejection sampling can consume extra draws; the partition-loop bound alone does not bound that random sampling loop. |
| Sort, then take rank $k$ | Common comparison-sort bound $O(N\log(N+1))$ | Exact and supplies the full order; storage depends on the sorting implementation. |
| Deterministic median-of-medians selection | Worst-case $O(N)$ with the appropriate partition and pivot construction | Exact without random pivot assumptions; a useful fallback when a deterministic linear bound is required. |
The field-operation analysis treats fixed-size modular arithmetic as constant cost. Arbitrarily large integer entries would require bit-complexity analysis instead. Quickselect is iterative and needs no recursive call stack; its copy and six-integer trace records use linear extra space, even on a quadratic-time pivot sequence. Under ideal uniform raw draws, the bounded sampler needs constant expected draws per pivot; the seeded implementation is analyzed separately through its actual draw count.
Freivalds' one-sided guarantee follows from $AB=C\Rightarrow A(Br)=Cr$ for every $r$, while a fixed nonzero difference is hidden by an independent binary vector with probability at most $1/2$. Quickselect's exactness follows from preserving the multiset, correctly partitioning the active interval, and retaining the absolute target rank. Randomness enters the error bound of the first algorithm and the expected-time bound of the second.
A useful conversion principle has limits. If a randomized candidate generator succeeds with probability at least $p\gt0$ per fresh trial and a complete exact verifier recognizes correct outputs, independently generate and verify candidates until one passes. The expected number of trials is at most $1/p$, and expected cost is $O((G+V)/p)$ when generation and verification each have per-trial cost bounded by $G$ and $V$. The verifier must recognize the required outputs; Freivalds' inequality witness does not certify its acceptance verdict.
In the other direction, stopping a Las Vegas computation after a fixed budget and returning an arbitrary answer introduces error on timeout. If $\mathbb E[T]\le\mu$, Markov's inequality gives $\Pr[T\gt c\mu]\le1/c$. Returning UNKNOWN instead preserves zero wrong answers but creates a partial-result interface, which is different from always producing an exact answer within that budget.
Variants, Pitfalls, and Optimizations
The most common amplification mistake is replaying the same random experiment. In the sample, restarting seed $7$ before every one-round call tests $(1,1)^{\mathsf T}$ every time, so every call misses the same error. Continuing to new choices exposes $(0,1)^{\mathsf T}$ next and detects it. Fresh choices are necessary for the independent-round proof; a deterministic pseudorandom stream still needs a separate randomness model before assigning that proof's numerical bound.
Other choices change the guarantee or its cost:
- One-sided versus two-sided repetition: Freivalds accepts only when every round passes because correct products always pass. For a two-sided test with success probability uniformly above $1/2$, independent majority voting can amplify success; applying the all-pass rule to such a test can increase the wrong kind of error.
- Many verification jobs: if every job has false-acceptance probability at most $2^{-t}$, a union bound gives at most $M2^{-t}$ for any false acceptance among $M$ jobs. Independence between jobs is not needed for that union bound, but each job must satisfy its own assumptions.
- Adversarial inputs: the bound is for a product fixed independently of the test vectors. Choosing a nonzero difference after observing the vectors can arrange for those projections to miss it. A replay seed is useful for debugging, while unpredictable production sampling is a separate requirement.
- Arithmetic domain: exact field equalities, integer equalities, and floating-point tolerances are different specifications. A tolerance-based comparison does not inherit the finite-field proof unchanged.
- Rejection sampling: direct remainder reduction of an uneven random range can bias pivots. Reject the unused suffix when uniform bounded samples are required by the model, and account for its work.
- Selection duplicates: retain an entire equality block rather than repeatedly peeling off one pivot-equal item. When every input value is equal, one three-way partition already identifies every valid rank.
- Budgeted selection and fallbacks: stopping early must produce
UNKNOWNor use a separately correct fallback. A claimed worst-case bound for a hybrid requires bounding the work already spent as well as the fallback's work. - Empirical tests: seeing no false acceptances in a small experiment does not prove a tiny error probability. Use exact small-domain enumeration and the algebraic argument to establish the bound, then test implementation behavior independently.
Do not treat an accepted projection as a proof of equality, multiply error probabilities without independence, or call repeated use of the same seed amplification. State the arithmetic domain, use safe intermediate widths, and distinguish an explicit timeout from a wrong answer. For Las Vegas algorithms, a long run can be unfortunate while remaining correct; for Monte Carlo algorithms, a fast completed run can still be wrong.
Practice Problems and Real-World Use
Use an exact product oracle on small matrices to distinguish equal and unequal instances. Equal products must always pass, while any rejection must carry a vector whose two computed projections differ. Enumerate all binary vectors for small nonzero difference matrices to verify that at most half conceal an error; enumerate short independent vector schedules to check amplification exactly.
For Quickselect, compare the returned value with an independently sorted copy for every rank. Check that the copied work array preserves all multiplicities, the caller's array is unchanged, the equality block contains its stated pivot, and every nonterminal step strictly shrinks the target's interval. Include empty or invalid inputs, singletons, all-equal arrays, negative values, integer boundaries, sorted and reversed arrays, and deliberately extreme pivot sequences.
| Problem or application | Idea tested | Difficulty |
|---|---|---|
| Matrix-product checker | Implement one-sided projection testing and verify rejecting witnesses over a specified field. | Intermediate |
| Exact small-domain error census | Enumerate vectors and repeated schedules; distinguish the theoretical probability from observed seed behavior. | Intermediate |
| Median and percentile selection | Use random pivots while preserving an exact rank invariant, including duplicates. | Intermediate |
| Candidate generation with verification | Identify a complete verifier, a per-trial success bound, and the expected retry cost. | Advanced |
| Polynomial identity testing | Transfer the fingerprinting idea to evaluating polynomials over a suitable field; derive its own degree-dependent error bound. | Advanced |
| Random contraction for minimum cut | A valid cut can still be nonminimum; correctness of the optimum claim has a Monte Carlo error probability. | Advanced |
| Deadline-aware randomized service | Separate a verified result, an explicit unknown, and an answer returned with a quantified error budget. | Advanced |
| Reproducible randomized benchmark | Match seeds and draw order across languages while measuring correctness, errors, and work as separate quantities. | Intermediate |
For further study, see the Boston University notes on fingerprinting and Freivalds' technique and the Princeton selection API. For a deeper analysis that distinguishes key comparisons from bit comparisons, see Fill and Nakama's Quickselect paper. The examples here keep mathematical error, exact output correctness, and random work as separately testable claims.