Randomized Algorithms
Coin flips that make algorithms simpler, faster, or both.
Checking that for two matrices by recomputing the product costs about multiplications. Multiply both sides by a random vector of 0s and 1s instead: multiplications, and a wrong slips through with probability at most , or at most , 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 becomes after runs.
- Compute expected costs with indicator variables and linearity of expectation, including quicksort's 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 steps, and report "failed" if it has not finished.
For a nonnegative random variable and , the indicator of the event is at most pointwise. Take expectations:
With , the cut-off run fails with probability at most , on every input. In the other direction, a Monte Carlo algorithm that succeeds with probability and whose answers can be verified quickly becomes Las Vegas: repeat until the answer checks out, an expected runs.
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?
- At most
- At most
- At most
- It is 0, since 40 seconds is four times the expected time
Show the answer
C. At most
Markov's inequality gives , and with no other information nothing better can be guaranteed: could be 0 with probability and 40 with probability . Restarting the algorithm with fresh coins instead of waiting gives exponentially small failure: two independent 20-second attempts fail together with probability at most .
Freivalds: checking is cheaper than computing
You are given matrices , and a claimed product . Recomputing costs with the schoolbook method, and about with the fastest known algorithms. Freivalds (1977) checks the claim with three matrix–vector products instead: pick a random and compare with , in time.
Let , and pick an entry . The test passes only if , which requires in particular row of to vanish:
Fix all coordinates of except first, which fixes . Of the two equally likely values of , at most one gives , because makes the two values of different. Averaging over keeps the bound:
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 FalseWith a single wrong entry the bound is tight: the error goes unseen exactly when the matching coordinate of is 0. In 20,000 single trials on a 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.
How many independent Freivalds trials make the probability of accepting a wrong product at most ?
Show the answer
30
You need , that is , so 30 trials (; 29 trials only reach ). The cost is multiplications, still far below for large . Repetition shrinks a one-sided error exponentially, because all independent trials must fail together.
Linearity of expectation
Linearity of expectation, , 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 cards uniformly. Let indicate that card stays in place, so . The number of fixed points has , for every , although the are dependent. (Averaged over all 720 orders of 6 cards, exactly 1.)
Name the keys in sorted order . Two keys are compared at most once, and only when one of them is the pivot. Let indicate that and () are ever compared; the total is .
The keys stay together in one subarray until a pivot is chosen among them. If that first pivot is or , the two are compared; if it lies strictly between, they are separated forever. Each of the keys is equally likely to be first:
Group the pairs by the distance (there are of each) and simplify with :
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 , and linearity adds 52 such expectations: . The answer is 1 for a deck of any size. Remarkably, the probability that no card stays put tends to .
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 (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:
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 sampleBoth 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).
Claim: after items, each of them is in the sample with probability (and the sample is a uniform -subset). It holds for , since all items are kept. Item enters with probability , as the code chooses among values.
An earlier item survives step unless the new item enters and replaces its slot, which happens with probability . 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 for 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 brief | Random ingredient | Cost |
|---|---|---|
| Sort or select on data an adversary may have ordered | a uniformly random pivot | or expected, on every input |
| A hash map facing keys chosen to collide | a hash function drawn at random when the program starts | expected per operation |
| Is the claimed product correct? | a random 0/1 vector (Freivalds) | per trial, error at most per trial |
| Are two long strings, or two substrings, equal? | polynomial hashing at a random base modulo a prime | per comparison after preprocessing |
| A uniform sample of lines from a log of unknown length | reservoir sampling | time, memory |
#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() % nfavors small values unless divides the generator's range, andRAND_MAXmay 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 needsrandint(0, i). - Dependent repetitions: amplification needs fresh randomness in every trial.
- Floating-point probabilities compared with
==.
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?
- Keep every 1,000th line
- Store the whole stream, then shuffle it with Fisher–Yates and take the first 100
- Keep the first 100 lines
- Reservoir sampling with a reservoir of 100 lines
Show the answer
D. Reservoir sampling with a reservoir of 100 lines
Reservoir sampling keeps line with probability , replacing a random slot, and leaves every line seen so far in the sample with probability , 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 , fail with probability at most ); a fast verifier turns Monte Carlo into Las Vegas; independent runs shrink a one-sided error to .
- Freivalds checks in per trial with one-sided error at most : 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, 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 comparisons for sorting.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A Monte Carlo algorithm never errs when the true answer is "no", and answers "yes" correctly with probability at least . How many independent runs, answering "yes" if any run says "yes", bring the error below ?
- 3
- 10
- 500
- 1000
Show the answer
B. 10
An error requires all runs to miss a true "yes", which has probability at most . , while is not enough.
In Freivalds's test with , why does go undetected with probability at most ?
- Because half of all vectors are zero
- Because and must differ in at least half of their entries
- Because for a nonzero entry of , once the other coordinates of are fixed, at most one of the two values of makes row of vanish
- Because matrix multiplication is associative, so
Show the answer
C. Because for a nonzero entry of , once the other coordinates of are fixed, at most one of the two values of makes row of vanish
This is the principle of deferred decisions: condition on every coordinate except ; 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 , not why it catches errors.
Randomized quicksort sorts 16 distinct keys. What is the expected number of comparisons, for any input order?
- 120
- About 51
- About 64, that is
- Exactly 45
Show the answer
B. About 51
. The asymptotic form is accurate only for large .
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 ?
- It is uniform: every element gets swapped with a random position
- Its equally likely runs cannot be split evenly among the orders, because 6 does not divide 27
- It never leaves an element in its original position
- Python's random number generator is biased toward small values
Show the answer
B. Its equally likely runs cannot be split evenly among the 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 from instead, giving exactly equally likely sequences.
Go deeper
- Karger’s Min-Cut Algorithm · Random edge contractions, and the Karger–Stein speedup.
- Primality Testing · Fermat, Miller–Rabin and the AKS theorem.
- Tail Bounds for Algorithms · Markov, Chebyshev and Chernoff: from “on average” to “with high probability”.
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.