Simple Algorithm
Algorithms & Data Structures · Optimized · 22 min

Randomized Algorithms

Coin flips that make algorithms simpler, faster, or both.

Checking that AB=CAB = C for two 1000×10001000 \times 1000 matrices by recomputing the product costs about 10910^9 multiplications. Multiply both sides by a random vector of 0s and 1s instead: 3×1063 \times 10^6 multiplications, and a wrong CC slips through with probability at most 1/21/2, or at most 2−202^{-20}, about one in a million, after 20 independent tries.

What you’ll learn

  • Distinguish Las Vegas from Monte Carlo algorithms, and expected running time (over the algorithm's coins, for every input) from average-case time (over random inputs); convert one kind of algorithm into the other.
  • Amplify success by independent repetition: a one-sided error δ\delta becomes δk\delta^k after kk runs.
  • Compute expected costs with indicator variables and linearity of expectation, including quicksort's 2(n+1)Hn−4n2(n+1)H_n - 4n expected comparisons.
  • Implement and prove Freivalds's matrix-product check, the Fisher–Yates shuffle and reservoir sampling, and recognize their classic biased imitations.
  • Recognize when randomization pays (adversarial inputs, cheap verification, huge streams) and what it cannot do.

Two kinds of luck

A randomized algorithm flips coins as it runs, so on one fixed input its running time, and possibly its answer, are random variables. Two flavors matter:

  • A Las Vegas algorithm is always correct; only its running time is random. Quicksort with random pivots is the standard example.
  • A Monte Carlo algorithm always finishes within a time bound, but its answer is wrong with some small probability. Freivalds's check below, the Miller–Rabin primality test and Karger's min-cut algorithm are Monte Carlo.

The two flavors convert into each other. Markov's inequality says that a nonnegative random variable rarely exceeds a multiple of its mean, which turns Las Vegas into Monte Carlo: run the algorithm for 2 E[T]2\,\E[T] steps, and report "failed" if it has not finished.

DerivationMarkov’s inequality and the Las Vegas cutoff
  1. Pr⁡[T≥a]  =  E[1[T≥a]]  ≤  E[T/a]  =  E[T]a\Pr[T \ge a] \;=\; \E\big[\mathbf 1[T \ge a]\big] \;\le\; \E[T/a] \;=\; \frac{\E[T]}{a}

    For a nonnegative random variable TT and a>0a > 0, the indicator of the event T≥aT \ge a is at most T/aT / a pointwise. Take expectations:

  2. Pr⁡[T≥2 E[T]]  ≤  12,E[runs until success]  =  1p\Pr\big[T \ge 2\,\E[T]\big] \;\le\; \tfrac12, \qquad \E[\text{runs until success}] \;=\; \frac{1}{p}

    With a=2 E[T]a = 2\,\E[T], the cut-off run fails with probability at most 1/21/2, on every input. In the other direction, a Monte Carlo algorithm that succeeds with probability pp and whose answers can be verified quickly becomes Las Vegas: repeat until the answer checks out, an expected 1/p1/p runs.

Check your understanding

A Las Vegas algorithm has expected running time 10 seconds on every input. You stop it after 40 seconds and report failure. What can you guarantee about the probability of failure, knowing nothing else about the distribution?

  1. At most 1/21/2
  2. At most e−4e^{-4}
  3. At most 1/41/4
  4. It is 0, since 40 seconds is four times the expected time
Show the answer

C. At most 1/41/4

Markov's inequality gives Pr⁡[T≥40]≤10/40=1/4\Pr[T \ge 40] \le 10/40 = 1/4, and with no other information nothing better can be guaranteed: TT could be 0 with probability 3/43/4 and 40 with probability 1/41/4. Restarting the algorithm with fresh coins instead of waiting gives exponentially small failure: two independent 20-second attempts fail together with probability at most (1/2)2(1/2)^2.

Freivalds: checking is cheaper than computing

You are given n×nn \times n matrices AA, BB and a claimed product CC. Recomputing ABAB costs Θ(n3)\Theta(n^3) with the schoolbook method, and about n2.37n^{2.37} with the fastest known algorithms. Freivalds (1977) checks the claim with three matrix–vector products instead: pick a random r∈{0,1}nr \in \{0, 1\}^n and compare A(Br)A(Br) with CrCr, in O(n2)O(n^2) time.

DerivationProof: the principle of deferred decisions
  1. (Dr)i  =  dij rj  +  ∑k≠jdik rk  =  dij rj+s(Dr)_i \;=\; d_{ij}\, r_j \;+\; \sum_{k \ne j} d_{ik}\, r_k \;=\; d_{ij}\, r_j + s

    Let D=AB−C≠0D = AB - C \ne 0, and pick an entry dij≠0d_{ij} \ne 0. The test passes only if Dr=0Dr = 0, which requires in particular row ii of DrDr to vanish:

  2. Pr⁡[Dr=0]  ≤  Pr⁡[(Dr)i=0]  ≤  12\Pr[Dr = 0] \;\le\; \Pr\big[(Dr)_i = 0\big] \;\le\; \tfrac12

    Fix all coordinates of rr except rjr_j first, which fixes ss. Of the two equally likely values of rjr_j, at most one gives dijrj+s=0d_{ij} r_j + s = 0, because dij≠0d_{ij} \ne 0 makes the two values of dijrjd_{ij} r_j different. Averaging over ss keeps the bound:

python
import random

def freivalds(A, B, C, trials=20):
    """False: certainly A @ B != C. True: equal, or unequal with probability <= 2**-trials."""
    n = len(A)
    for _ in range(trials):
        r = [random.randint(0, 1) for _ in range(n)]
        Br = [sum(B[i][j] * r[j] for j in range(n)) for i in range(n)]       # O(n^2)
        ABr = [sum(A[i][j] * Br[j] for j in range(n)) for i in range(n)]     # O(n^2)
        Cr = [sum(C[i][j] * r[j] for j in range(n)) for i in range(n)]       # O(n^2)
        if ABr != Cr:
            return False
    return True

A, B = [[1, 2], [3, 4]], [[5, 6], [7, 8]]
print(freivalds(A, B, [[19, 22], [43, 50]]), freivalds(A, B, [[19, 22], [43, 51]]))   # True False

With a single wrong entry the bound is tight: the error goes unseen exactly when the matching coordinate of rr is 0. In 20,000 single trials on a 30×3030 \times 30 instance with one wrong entry, the test caught it 50.2% of the time; with 20 trials per check it was never fooled in 200 checks.

Predict before you look

How many independent Freivalds trials make the probability of accepting a wrong product at most 10−910^{-9}?

Show the answer

30

You need 2−k≤10−92^{-k} \le 10^{-9}, that is k≥9log⁡210≈29.9k \ge 9 \log_2 10 \approx 29.9, so 30 trials (2−30≈9.3×10−102^{-30} \approx 9.3 \times 10^{-10}; 29 trials only reach 1.9×10−91.9 \times 10^{-9}). The cost is 30×3n230 \times 3 n^2 multiplications, still far below n3n^3 for large nn. Repetition shrinks a one-sided error exponentially, because all kk independent trials must fail together.

Linearity of expectation

Linearity of expectation, E[X+Y]=E[X]+E[Y]\E[X + Y] = \E[X] + \E[Y], holds for any random variables, independent or not. Combined with indicator variables (1 if an event happens, else 0, with expectation equal to the event's probability), it computes expected costs that look hopeless to compute directly.

Fixed points. Shuffle nn cards uniformly. Let XiX_i indicate that card ii stays in place, so E[Xi]=1/n\E[X_i] = 1/n. The number of fixed points X=∑iXiX = \sum_i X_i has E[X]=n⋅1/n=1\E[X] = n \cdot 1/n = 1, for every nn, although the XiX_i are dependent. (Averaged over all 720 orders of 6 cards, exactly 1.)

DerivationRandomized quicksort: expected comparisons
  1. E[X]  =  ∑i<jPr⁡[zi and zj are compared]\E[X] \;=\; \sum_{i<j} \Pr[z_i \text{ and } z_j \text{ are compared}]

    Name the keys in sorted order z1<z2<⋯<znz_1 < z_2 < \cdots < z_n. Two keys are compared at most once, and only when one of them is the pivot. Let XijX_{ij} indicate that ziz_i and zjz_j (i<ji < j) are ever compared; the total is X=∑i<jXijX = \sum_{i<j} X_{ij}.

  2. Pr⁡[zi and zj are compared]  =  2j−i+1\Pr[z_i \text{ and } z_j \text{ are compared}] \;=\; \frac{2}{j - i + 1}

    The keys zi,…,zjz_i, \dots, z_j stay together in one subarray until a pivot is chosen among them. If that first pivot is ziz_i or zjz_j, the two are compared; if it lies strictly between, they are separated forever. Each of the j−i+1j - i + 1 keys is equally likely to be first:

  3. E[X]  =  ∑d=1n−1(n−d) 2d+1  =  2(n+1)Hn−4n  ≈  2nln⁡n  ≈  1.39 nlog⁡2n\E[X] \;=\; \sum_{d=1}^{n-1} (n-d)\,\frac{2}{d+1} \;=\; 2(n+1)H_n - 4n \;\approx\; 2n \ln n \;\approx\; 1.39\, n \log_2 n

    Group the pairs by the distance d=j−id = j - i (there are n−dn - d of each) and simplify with Hn=1+12+⋯+1nH_n = 1 + \tfrac12 + \cdots + \tfrac1n:

Predict before you look

You shuffle a 52-card deck uniformly at random. On average, how many cards end up in their original position?

Show the answer

1

Each card stays put with probability 1/521/52, and linearity adds 52 such expectations: 52⋅152=152 \cdot \tfrac{1}{52} = 1. The answer is 1 for a deck of any size. Remarkably, the probability that no card stays put tends to 1/e≈0.3681/e \approx 0.368.

The same reasoning shows that quickselect with random pivots makes an expected linear number of comparisons on every input (see Selection & Order Statistics), and that a random binary search tree has expected depth O(log⁡n)O(\log n) (see Random BSTs & Treaps). Expectations, however, do not say how often a run is far above average; Tail Bounds for Algorithms turns them into "with high probability" statements.

Shuffling and sampling, exactly

Many randomized algorithms start by putting the input in random order or by drawing a random sample, and both are easy to get subtly wrong. The Fisher–Yates shuffle (1938), in Durstenfeld's in-place form (1964), fills positions from the right, each with a uniformly random element of those not yet placed:

python
import random

def shuffle(a):
    """Fisher-Yates: every permutation has probability exactly 1/n!."""
    for i in range(len(a) - 1, 0, -1):
        j = random.randint(0, i)             # uniform over 0..i, inclusive
        a[i], a[j] = a[j], a[i]

def reservoir_sample(stream, k):
    """A uniform random k-subset of a stream of unknown length, in O(k) memory."""
    sample = []
    for t, x in enumerate(stream, start=1):  # t = items seen so far
        if t <= k:
            sample.append(x)
        else:
            j = random.randrange(t)          # uniform over 0..t-1
            if j < k:
                sample[j] = x                # keep x with probability k / t
    return sample

Both checked empirically: 120,000 shuffles of three items gave each of the 6 orders a frequency between 0.165 and 0.168, and each of 10 stream items landed in a 3-item reservoir with frequency 0.296–0.303 (expected 0.3).

DerivationReservoir sampling keeps every item with probability k/t
  1. Pr⁡[xt+1∈sample]  =  kt+1\Pr[x_{t+1} \in \text{sample}] \;=\; \frac{k}{t+1}

    Claim: after t≥kt \ge k items, each of them is in the sample with probability k/tk/t (and the sample is a uniform kk-subset). It holds for t=kt = k, since all items are kept. Item t+1t+1 enters with probability k/(t+1)k/(t+1), as the code chooses j<kj < k among t+1t+1 values.

  2. Pr⁡[xi∈sample after t+1]  =  kt⋅(1−1t+1)  =  kt+1\Pr[x_i \in \text{sample after } t+1] \;=\; \frac{k}{t} \cdot \Big(1 - \frac{1}{t+1}\Big) \;=\; \frac{k}{t+1}

    An earlier item survives step t+1t+1 unless the new item enters and replaces its slot, which happens with probability kt+1⋅1k=1t+1\frac{k}{t+1} \cdot \frac{1}{k} = \frac{1}{t+1}. By induction:

Reservoir sampling, Waterman's "Algorithm R" as described by Vitter (1985), reads the stream once and never needs its length. Vitter's Algorithm Z goes further: it draws how many items to skip before the next replacement, so when skipping is cheap, as with records in a file, its expected time is O(k(1+log⁡(N/k)))O(k(1 + \log(N/k))) for NN items, optimal up to a constant factor.

Recognizing it

Randomization is the right move when:

  • Someone else picks the input. A fixed rule (the last element as pivot, a known hash function) has inputs that defeat it; an adversary who cannot see your coins cannot aim. Contests hack predictable hash maps with anti-hash tests, and the web saw the same attack as hash flooding.
  • Checking is cheaper than computing. Matrix products, polynomial identities and string equality can be tested at a random point in far less time than recomputing.
  • The data is too big to keep. Sample it (reservoir sampling) or summarize it (sketches, see Universal Hashing & Sketches).
  • The statement says "expected" or "probability", or asks for an estimate rather than an exact count.
Problem, in briefRandom ingredientCost
Sort or select on data an adversary may have ordereda uniformly random pivotO(nlog⁡n)O(n \log n) or O(n)O(n) expected, on every input
A hash map facing keys chosen to collidea hash function drawn at random when the program startsO(1)O(1) expected per operation
Is the claimed product C=ABC = AB correct?a random 0/1 vector (Freivalds)O(n2)O(n^2) per trial, error at most 1/21/2 per trial
Are two long strings, or two substrings, equal?polynomial hashing at a random base modulo a primeO(1)O(1) per comparison after O(n)O(n) preprocessing
A uniform sample of kk lines from a log of unknown lengthreservoir samplingO(n)O(n) time, O(k)O(k) memory
Each random ingredient replaces either a worst case that depends on the input or a computation that is more expensive than a check.
cpp
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <random>
#include <unordered_map>
#include <vector>

std::mt19937_64 rng(std::chrono::steady_clock::now().time_since_epoch().count());

struct SplitMixHash {                                // a hash that hacked tests cannot predict
    static uint64_t splitmix64(uint64_t x) {
        x += 0x9e3779b97f4a7c15ULL;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ULL;
        x = (x ^ (x >> 27)) * 0x94d049bb133111ebULL;
        return x ^ (x >> 31);
    }
    size_t operator()(uint64_t x) const {
        static const uint64_t seed = rng();          // drawn once per run
        return splitmix64(x + seed);
    }
};

int main() {
    std::vector<int> a = {5, 3, 8, 1, 9, 2};
    std::shuffle(a.begin(), a.end(), rng);           // not std::random_shuffle, removed in C++17
    std::uniform_int_distribution<int> die(1, 6);    // unbiased, unlike rng() % 6 in general
    std::unordered_map<uint64_t, int, SplitMixHash> seen;
    seen[die(rng)]++;
}

Contest idioms: seed a 64-bit Mersenne Twister from the clock, shuffle with std::shuffle, draw ranges with a distribution, and give unordered_map a hash with a random seed so a prepared test cannot force collisions.

Common bugs.

  • Modulo bias: rand() % n favors small values unless nn divides the generator's range, and RAND_MAX may be only 32,767.
  • A fixed or guessable seed: the same "random" choices on every run, which is exactly what an anti-hash test exploits.
  • The naive shuffle, or random.randint(0, n - 1) where Fisher–Yates needs randint(0, i).
  • Dependent repetitions: amplification needs fresh randomness in every trial.
  • Floating-point probabilities compared with ==.
Check your understanding

A logging service must keep a uniformly random sample of 100 lines from a stream whose length is unknown and may reach billions, using memory for about 100 lines. Which approach fits?

  1. Keep every 1,000th line
  2. Store the whole stream, then shuffle it with Fisher–Yates and take the first 100
  3. Keep the first 100 lines
  4. Reservoir sampling with a reservoir of 100 lines
Show the answer

D. Reservoir sampling with a reservoir of 100 lines

Reservoir sampling keeps line tt with probability 100/t100/t, replacing a random slot, and leaves every line seen so far in the sample with probability 100/t100/t, using only the reservoir's memory.

Key takeaways

  • Las Vegas algorithms are always correct with random running time (randomized quicksort); Monte Carlo algorithms have bounded time and a small error probability (Freivalds, Miller–Rabin, Karger). Expected time is over the coins, for every input.
  • Markov's inequality turns Las Vegas into Monte Carlo (stop at 2 E[T]2\,\E[T], fail with probability at most 1/21/2); a fast verifier turns Monte Carlo into Las Vegas; kk independent runs shrink a one-sided error δ\delta to δk\delta^k.
  • Freivalds checks AB=CAB = C in O(n2)O(n^2) per trial with one-sided error at most 1/21/2: verifying can be far cheaper than computing.
  • Indicator variables and linearity of expectation give expected costs without independence: one expected fixed point in a random permutation, 2(n+1)Hn−4n2(n+1)H_n - 4n comparisons in randomized quicksort.
  • Fisher–Yates and reservoir sampling are exactly uniform; the swap-anywhere shuffle is not. Randomize when an adversary picks the input, when checking is cheaper than computing, or when the data is too large to keep, but do not expect coins to beat a lower bound such as Ω(nlog⁡n)\Omega(n \log n) comparisons for sorting.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A Monte Carlo algorithm never errs when the true answer is "no", and answers "yes" correctly with probability at least 1/21/2. How many independent runs, answering "yes" if any run says "yes", bring the error below 1/10001/1000?

  1. 3
  2. 10
  3. 500
  4. 1000
Show the answer

B. 10

An error requires all kk runs to miss a true "yes", which has probability at most 2−k2^{-k}. 2−10=1/1024<1/10002^{-10} = 1/1024 < 1/1000, while 2−9=1/5122^{-9} = 1/512 is not enough.

Question 2

In Freivalds's test with r∈{0,1}nr \in \{0, 1\}^n, why does AB≠CAB \neq C go undetected with probability at most 1/21/2?

  1. Because half of all vectors rr are zero
  2. Because ABAB and CC must differ in at least half of their entries
  3. Because for a nonzero entry dijd_{ij} of AB−CAB - C, once the other coordinates of rr are fixed, at most one of the two values of rjr_j makes row ii of (AB−C)r(AB - C)r vanish
  4. Because matrix multiplication is associative, so A(Br)=(AB)rA(Br) = (AB)r
Show the answer

C. Because for a nonzero entry dijd_{ij} of AB−CAB - C, once the other coordinates of rr are fixed, at most one of the two values of rjr_j makes row ii of (AB−C)r(AB - C)r vanish

This is the principle of deferred decisions: condition on every coordinate except rjr_j; the remaining coin decides the outcome, and at most one of its two values hides the difference. Associativity explains why the test is fast and why it never rejects a correct CC, not why it catches errors.

Question 3

Randomized quicksort sorts 16 distinct keys. What is the expected number of comparisons, for any input order?

  1. 120
  2. About 51
  3. About 64, that is nlog⁡2nn \log_2 n
  4. Exactly 45
Show the answer

B. About 51

2(n+1)Hn−4n=34⋅H16−64≈34×3.381−64≈50.92(n+1)H_n - 4n = 34 \cdot H_{16} - 64 \approx 34 \times 3.381 - 64 \approx 50.9. The asymptotic form 1.39 nlog⁡2n1.39\, n \log_2 n is accurate only for large nn.

Question 4

A shuffle runs for i in range(n): j = random.randrange(n); a[i], a[j] = a[j], a[i]. Why can it not be uniform for n=3n = 3?

  1. It is uniform: every element gets swapped with a random position
  2. Its 33=273^3 = 27 equally likely runs cannot be split evenly among the 3!=63! = 6 orders, because 6 does not divide 27
  3. It never leaves an element in its original position
  4. Python's random number generator is biased toward small values
Show the answer

B. Its 33=273^3 = 27 equally likely runs cannot be split evenly among the 3!=63! = 6 orders, because 6 does not divide 27

Each run is one of 27 equally likely sequences of choices, so every order has probability (some count)/27, which cannot equal 1/6. In fact three orders get 5/27 and three get 4/27. Fisher–Yates draws jj from 0..i0..i instead, giving exactly n!n! equally likely sequences.

Go deeper

Further reading

  • R. Motwani & P. Raghavan, Randomized Algorithms (Cambridge University Press, 1995).
  • M. Mitzenmacher & E. Upfal, Probability and Computing, 2nd ed. (Cambridge University Press, 2017).
  • R. Freivalds, "Probabilistic machines can use less running time," in Information Processing 77: Proceedings of IFIP Congress 77 (North-Holland, 1977), 839–842.
  • J. S. Vitter, "Random sampling with a reservoir," ACM Transactions on Mathematical Software 11(1) (1985), 37–57.