Las Vegas and Monte Carlo Algorithms
A randomized algorithm reads its input and also a supply of independent random bits. For a fixed input, its running time and its output are then random variables, and the analysis is about their distribution over the algorithm's own coin flips, never over the inputs. There are two ways to let randomness in. A Las Vegas algorithm is always right but its running time is random. A Monte Carlo algorithm has a bounded running time but may be wrong with small probability. This lesson defines both, shows how to turn one into the other, and fixes the vocabulary that the rest of the course uses.
Two contracts
Let be a randomized algorithm and an input.
- is Las Vegas if on every input it halts with the correct answer (with probability 1), and its expected running time is bounded by some function . The expectation is over the coins only; the bound must hold for the worst input. Randomized Quicksort and Randomized Quickselect are the standard examples.
- is Monte Carlo if its running time is bounded by on every run, and on every input it answers correctly with probability at least . For decision problems the error can be one-sided (wrong only on "yes" inputs, or only on "no" inputs) or two-sided. Miller-Rabin has one-sided error: "composite" is always right.
The complexity classes named after these contracts are useful shorthand. RP contains the decision problems with a polynomial-time Monte Carlo algorithm that never accepts a "no" input and accepts a "yes" input with probability at least ; co-RP is the mirror image; BPP allows two-sided error with success probability at least ; ZPP contains the problems with a polynomial expected-time Las Vegas algorithm. A classical fact is , proved by the two conversions below.
A first example: finding a common element
An array of length holds the value a in at least half of its positions, and some other values elsewhere. We want any index holding a. A deterministic algorithm needs about probes in the worst case (an adversary puts all the as at the end). Random probing does better.
FIND-LAS-VEGAS(A) FIND-MONTE-CARLO(A, k)
0 repeat 0 for j = 0 to k - 1
1 i = RANDOM(0, n - 1) 1 i = RANDOM(0, n - 1)
2 if A[i] == a 2 if A[i] == a
3 return i 3 return i
4 return FAILEach probe succeeds with probability independently, so the Las Vegas version makes a geometric number of probes with mean , whatever the arrangement. The Monte Carlo version makes at most probes and fails with probability .
import random
n = 1000
A = ["b"] * (n // 2) + ["a"] * (n // 2) # the worst arrangement for a left-to-right scan
def find_las_vegas(A, rng):
probes = 0
while True:
probes += 1
i = rng.randrange(len(A))
if A[i] == "a":
return i, probes
def find_monte_carlo(A, k, rng):
for j in range(k):
i = rng.randrange(len(A))
if A[i] == "a":
return i
return None
rng = random.Random(1)
runs = 20000
counts = [find_las_vegas(A, rng)[1] for _ in range(runs)]
print(f"Las Vegas: mean probes {sum(counts) / runs:.3f}, longest run {max(counts)} probes")
for k in [1, 2, 5, 10]:
fails = sum(find_monte_carlo(A, k, rng) is None for _ in range(runs))
print(f"Monte Carlo with k = {k:2}: failure rate {fails / runs:.4f}, bound 2^-k = {2 ** -k:.4f}")
print("deterministic left-to-right scan:", A.index("a") + 1, "probes")Las Vegas: mean probes 2.009, longest run 14 probes
Monte Carlo with k = 1: failure rate 0.4988, bound 2^-k = 0.5000
Monte Carlo with k = 2: failure rate 0.2525, bound 2^-k = 0.2500
Monte Carlo with k = 5: failure rate 0.0308, bound 2^-k = 0.0312
Monte Carlo with k = 10: failure rate 0.0012, bound 2^-k = 0.0010
deterministic left-to-right scan: 501 probes
The Las Vegas runs average 2 probes, but a few runs are long: the running time has a geometric tail. The Monte Carlo runs never exceed probes, and the price is a failure rate that halves with every extra probe.
From Las Vegas to Monte Carlo: stop the clock
Suppose a Las Vegas algorithm has . Run it, and if it has not finished after steps, stop and answer "fail" (or any guess). By Markov's inequality (Markov's and Chebyshev's Inequalities),
So the truncated algorithm is Monte Carlo with running time and error at most . With , a Las Vegas decision procedure becomes an algorithm with one-sided error at most in each direction, which puts ZPP inside both RP and co-RP. Markov's inequality is crude: for the geometric probe count above, the real probability of needing more than 4 probes is , not . The Amplification by Repetition lesson shows a better way to make the error tiny.
From Monte Carlo to Las Vegas: verify and retry
The other direction needs a verifier: a fast deterministic check that a proposed answer is correct. If a Monte Carlo algorithm succeeds with probability in time , and checking costs , then "run, check, repeat until the check passes" never gives a wrong answer, and the number of rounds is geometric with mean :
For decision problems in the two one-sided algorithms play the role of the verifier: run both until one of them gives an answer it is never wrong about.
A natural number-theoretic example: given an odd prime , find a quadratic non-residue, a number that is not a square modulo . No deterministic polynomial-time algorithm is known without unproven hypotheses, but exactly half of are non-residues, and Euler's criterion verifies a candidate with one modular exponentiation (Quadratic Residues). So "guess and verify" is a Las Vegas algorithm with 2 expected guesses.
import random
def non_residue(p, rng):
tries = 0
while True:
tries += 1
a = rng.randrange(1, p)
if pow(a, (p - 1) // 2, p) == p - 1: # Euler's criterion: a is not a square mod p
return a, tries
rng = random.Random(5)
for p in [10007, 1000003, 2**61 - 1]:
results = [non_residue(p, rng) for _ in range(2000)]
mean = sum(t for _, t in results) / len(results)
print(f"p = {p}: first answer {results[0][0]}, mean tries {mean:.3f}")
p = 10007
squares = {x * x % p for x in range(1, p)}
print("check by brute force for p = 10007:", len(squares), "residues,", p - 1 - len(squares), "non-residues")p = 10007: first answer 5875, mean tries 1.943
p = 1000003: first answer 126513, mean tries 1.951
p = 2305843009213693951: first answer 642614724749517098, mean tries 2.034
check by brute force for p = 10007: 5003 residues, 5003 non-residues
How the running time is distributed
For a Las Vegas algorithm the expected running time is the headline number, but the tail matters too: how likely is a run much longer than average? For the probe-until-success algorithm the tail is geometric, . The program compares that exact tail with what Markov's inequality promises.
import random
rng = random.Random(3)
p, runs = 0.5, 50000
T = []
for _ in range(runs):
t = 1
while rng.random() >= p:
t += 1
T.append(t)
mean = sum(T) / runs
print(f"mean {mean:.3f} (exact 1/p = {1 / p})")
print(" t Pr[T > t] measured exact (1-p)^t Markov E[T]/t")
for t in [2, 4, 8, 12, 16]:
measured = sum(x > t for x in T) / runs
print(f"{t:2} {measured:18.5f} {(1 - p) ** t:13.5f} {min(1, mean / t):13.5f}")mean 1.992 (exact 1/p = 2.0)
t Pr[T > t] measured exact (1-p)^t Markov E[T]/t
2 0.24682 0.25000 0.99604
4 0.06232 0.06250 0.49802
8 0.00400 0.00391 0.24901
12 0.00024 0.00024 0.16601
16 0.00002 0.00002 0.12451
Markov's bound decays only like , the true tail exponentially. Most Las Vegas algorithms in this course have such exponential tails, and the next section of the course provides the tools to prove them.
In C++
The two probing algorithms with a fixed-seed std::mt19937. Indices are drawn as rng() % n, which has a negligible bias and gives the same numbers with every standard library. The generator differs from Python's, so the measured rates differ slightly from the Python run.
#include <cstdio>
#include <random>
#include <vector>
std::mt19937 rng(1);
int find_las_vegas(const std::vector<char>& a, int& probes) {
probes = 0;
for (;;) {
++probes;
int i = static_cast<int>(rng() % a.size());
if (a[i] == 'a') return i;
}
}
int find_monte_carlo(const std::vector<char>& a, int k) {
for (int j = 0; j < k; ++j) {
int i = static_cast<int>(rng() % a.size());
if (a[i] == 'a') return i;
}
return -1; // FAIL
}
int main() {
const int n = 1000, runs = 20000;
std::vector<char> a(n, 'b');
for (int i = n / 2; i < n; ++i) a[i] = 'a';
long long total = 0;
int longest = 0, probes = 0;
for (int r = 0; r < runs; ++r) {
find_las_vegas(a, probes);
total += probes;
if (probes > longest) longest = probes;
}
std::printf("Las Vegas: mean probes %.3f, longest run %d probes\n", double(total) / runs, longest);
for (int k : {1, 2, 5, 10}) {
int fails = 0;
for (int r = 0; r < runs; ++r) fails += find_monte_carlo(a, k) < 0;
std::printf("Monte Carlo with k = %2d: failure rate %.4f, bound %.4f\n", k, double(fails) / runs, 1.0 / (1 << k));
}
}Las Vegas: mean probes 1.998, longest run 14 probes
Monte Carlo with k = 1: failure rate 0.4990, bound 0.5000
Monte Carlo with k = 2: failure rate 0.2542, bound 0.2500
Monte Carlo with k = 5: failure rate 0.0323, bound 0.0312
Monte Carlo with k = 10: failure rate 0.0011, bound 0.0010
Test yourself
Which statement describes a Las Vegas algorithm?
- Its running time is fixed and its answer may be wrong
- Its answer is always correct and its running time is a random variable with bounded expectation
- It is correct on random inputs only
- It always runs in worst-case polynomial time and is always correct
A Las Vegas algorithm has expected running time . It is stopped after steps. What error probability does Markov's inequality guarantee?
- At most
- At most
- At most
- Nothing can be said
A Monte Carlo algorithm succeeds with probability in time , and its answer can be checked in time . What is the expected running time of the Las Vegas algorithm "repeat until the check passes"?
What does the probability in the analysis of a randomized algorithm range over?
- A distribution of inputs
- The algorithm's own random choices, for a fixed worst-case input
- The compiler's choices
- Both inputs and coins, averaged