TExcelTAD
Home › Randomized Algorithms & Probabilistic Analysis › Las Vegas and Monte Carlo Algorithms

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 AA be a randomized algorithm and xx an input.

  • AA is Las Vegas if on every input it halts with the correct answer (with probability 1), and its expected running time E[TA(x)]\mathbb{E}[T_A(x)] is bounded by some function f(∣x∣)f(\lvert x \rvert). The expectation is over the coins only; the bound must hold for the worst input. Randomized Quicksort and Randomized Quickselect are the standard examples.
  • AA is Monte Carlo if its running time is bounded by f(∣x∣)f(\lvert x \rvert) on every run, and on every input it answers correctly with probability at least 1−ε1 - \varepsilon. 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 1/21/2; co-RP is the mirror image; BPP allows two-sided error with success probability at least 2/32/3; ZPP contains the problems with a polynomial expected-time Las Vegas algorithm. A classical fact is ZPP=RP∩co-RP\text{ZPP} = \text{RP} \cap \text{co-RP}, proved by the two conversions below.

A first example: finding a common element

An array of length nn 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 n/2n/2 probes in the worst case (an adversary puts all the as at the end). Random probing does better.

text
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 FAIL

Each probe succeeds with probability p≥1/2p \ge 1/2 independently, so the Las Vegas version makes a geometric number of probes with mean 1/p≤21/p \le 2, whatever the arrangement. The Monte Carlo version makes at most kk probes and fails with probability (1−p)k≤2−k(1 - p)^k \le 2^{-k}.

python · try it yourself
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 kk 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 E[T]≤f(n)\mathbb{E}[T] \le f(n). Run it, and if it has not finished after c⋅f(n)c \cdot f(n) steps, stop and answer "fail" (or any guess). By Markov's inequality (Markov's and Chebyshev's Inequalities),

Pr⁡[T≥c⋅f(n)]≤E[T]c⋅f(n)≤1c.\Pr[T \ge c \cdot f(n)] \le \frac{\mathbb{E}[T]}{c \cdot f(n)} \le \frac{1}{c}.

So the truncated algorithm is Monte Carlo with running time c⋅f(n)c \cdot f(n) and error at most 1/c1/c. With c=2c = 2, a Las Vegas decision procedure becomes an algorithm with one-sided error at most 1/21/2 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 2−42^{-4}, not 1/21/2. 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 pp in time TAT_A, and checking costs TVT_V, then "run, check, repeat until the check passes" never gives a wrong answer, and the number of rounds is geometric with mean 1/p1/p:

E[time]=TA+TVp.\mathbb{E}[\text{time}] = \frac{T_A + T_V}{p}.

For decision problems in RP∩co-RP\text{RP} \cap \text{co-RP} 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 pp, find a quadratic non-residue, a number aa that is not a square modulo pp. No deterministic polynomial-time algorithm is known without unproven hypotheses, but exactly half of 1,…,p−11, \ldots, p - 1 are non-residues, and Euler's criterion a(p−1)/2≡−1(modp)a^{(p-1)/2} \equiv -1 \pmod p verifies a candidate with one modular exponentiation (Quadratic Residues). So "guess and verify" is a Las Vegas algorithm with 2 expected guesses.

python · try it yourself
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, Pr⁡[T>t]=(1−p)t\Pr[T > t] = (1 - p)^t. The program compares that exact tail with what Markov's inequality promises.

python · try it yourself
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 1/t1/t, 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.

cpp · try it yourself
#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?

  1. Its running time is fixed and its answer may be wrong
  2. Its answer is always correct and its running time is a random variable with bounded expectation
  3. It is correct on random inputs only
  4. It always runs in worst-case polynomial time and is always correct

A Las Vegas algorithm has expected running time f(n)f(n). It is stopped after 4f(n)4f(n) steps. What error probability does Markov's inequality guarantee?

  1. At most 1/161/16
  2. At most 1/41/4
  3. At most 1/21/2
  4. Nothing can be said

A Monte Carlo algorithm succeeds with probability 1/31/3 in time TAT_A, and its answer can be checked in time TVT_V. What is the expected running time of the Las Vegas algorithm "repeat until the check passes"?

  1. TA+TVT_A + T_V
  2. 3(TA+TV)3(T_A + T_V)
  3. (TA+TV)/3(T_A + T_V)/3
  4. 9TA9T_A

What does the probability in the analysis of a randomized algorithm range over?

  1. A distribution of inputs
  2. The algorithm's own random choices, for a fixed worst-case input
  3. The compiler's choices
  4. Both inputs and coins, averaged