TL;DR
A randomized algorithm makes some of its decisions by flipping coins while it runs. Its running time, and sometimes its answer, is therefore a random variable. Because the coins are fresh on every run, no fixed input can be built to hit the slow case every time, so you can usually bound the average cost for every input at once.
The two common kinds are the Las Vegas algorithm, which always gives the right answer but whose running time is random, and the Monte Carlo algorithm, which runs in fixed time but may be wrong with a small, known probability.
Where you'll see it: random pivot choice in quicksort, hash tables that pick their hash function at random, primality tests (checks of whether a number is a prime) used to generate cryptographic keys, and the randomized skip list data structure.
Intuition
Start from a question you already know
Suppose you are given a shuffled deck and asked to find the ace of spades by looking through the cards in order. Your method is fixed: start at the top. An opponent who knows your method can shuffle the deck so the ace is last, and you will always do the most work. The fixed method has a worst case that the opponent can always reach.
Now suppose you first shuffle the deck yourself with your own coins. The opponent can no longer arrange the bad case, because your shuffle is not theirs to control. For any single deck, the chance that you hit the worst order is tiny. The question changes from "what is the worst input?" to "what is the average cost over my own coin flips, for this input?" That second question is the one randomized algorithms answer.
Why randomness helps
A deterministic algorithm has a fixed sequence of steps. Its cost is a function of the input, so a malicious or unlucky input can always push it to the worst case. Randomness breaks this link. Two runs on the same input can take different paths. A bad path exists, but it is taken with small probability, and that probability does not depend on who chose the input.
Randomness also gives you simplicity. Many randomized methods are shorter than their best deterministic counterparts, and they are often easier to reason about once you accept the one tool needed: the expected value of the cost.
flowchart LR
A[Input fixed in advance] --> B{Coin flips}
B --> C[Path 1: fast]
B --> D[Path 2: slow]
C --> E[Average cost over coins]
D --> E
E --> F[Bound holds for every input]
The math
Two kinds of randomized algorithm
A randomized algorithm that always returns a correct answer. Its running time is a random variable, and what we usually bound is , the expected running time for each fixed input.
A randomized algorithm that runs in a fixed, bounded time but may return a wrong answer with probability at most some . Errors can be one-sided (it never errs on "no") or two-sided.
Here is the expected value, the average over all the algorithm's coin flips, and is a small error probability. A Las Vegas algorithm trades a random running time for a guaranteed answer. A Monte Carlo algorithm trades a guaranteed running time for a small chance of error.
Analysing expected cost: randomized quicksort
Quicksort sorts a list by choosing a pivot element, partitioning the other elements into those smaller and those larger than the pivot, then sorting the two parts. A fixed pivot rule (say, always the first element) is slow on already sorted input, because every split is as lopsided as possible. Choosing the pivot uniformly at random removes that fixed bad input. The number of comparisons is now a random variable.
The key counting trick: rather than analysing each run, count the pairs. Sort the values into their final order and call them . Two values and are compared at most once, and only when one of them is chosen as a pivot while both are still in the same part. Consider the set . The first of these values to be picked as a pivot decides the matter:
- If the first pivot is or , then and are compared.
- If the first pivot is strictly between them, they are separated and never compared.
Each of the values is equally likely to be first, so
By linearity of expectation (the expected value of a sum is the sum of the expected values, even when the terms depend on each other), the expected number of comparisons is the sum of these probabilities over all pairs. Group the pairs by their gap . There are pairs with gap , so
Put and use the harmonic number :
Since grows like the natural logarithm , the expected cost is about , which is . The worst case, which the random pivot makes extremely unlikely, is .
- worst case
- 2 n ln n (leading term)
Bounding a tail with Markov's inequality
Expected cost alone does not say how often a run is much slower. Markov's inequality gives a crude but useful answer. For a nonnegative random variable and any ,
With , this says the chance of using at least twice the expected comparisons is at most .
Monte Carlo error and repetition
If a one-sided Monte Carlo algorithm errs with probability at most on a "yes" instance, and you run it times independently, the error drops to at most . The error is small after a few rounds, so repetition is the usual way to buy reliability.
Worked examples
Take the list and choose the pivot uniformly at random among the three values.
- Pivot (probability ). Compare with and : 2 comparisons. Parts and . Sorting needs 1 more. Total .
- Pivot (probability ). Compare with and : 2 comparisons. Parts and need nothing. Total .
- Pivot (probability ). Compare with and : 2 comparisons. Parts need 1 more. Total .
- Average over the three equally likely pivots: .
- Check with the formula: . The pair argument and the direct count agree.
Interpretation: on three values the random pivot costs under three comparisons on average, and no run ever needs more than three.
Take a list of distinct values sorted by randomized quicksort.
- .
- .
- So the average run makes about 648 comparisons.
- The worst case is comparisons, which is about 7.6 times the average.
- By Markov's inequality, .
Interpretation: the average is well below the worst case, and the Markov bound says at most half the runs can cost twice the average. The real tail is much smaller, but Markov does not need to know that. Notice the bound is never violated: it holds for every input, because the randomness is the algorithm's, not the input's.
A Hash Table stores keys in buckets. A Hash Function maps each key to a bucket, and two keys that land in the same bucket collide. Suppose 800 keys are stored in buckets.
- A fixed hash function is dangerous. An adversary (someone choosing inputs to hurt the algorithm) who knows it can choose 800 keys that all land in one bucket. A lookup then scans 800 keys.
- Instead, pick the hash function at random from a universal family. For this family, two different keys and collide with probability at most over the random choice.
- Fix a key that is stored. The other 799 keys each collide with with probability at most .
- By linearity of expectation, the expected number of other keys in 's bucket is at most .
- So a lookup examines, on average, under one other key, whatever keys the adversary picks.
Interpretation: the randomness is in the choice of hash function, not in the stored keys. The average cost of a lookup stays bounded for every key set. This is why real systems choose hash functions at random.
Tradeoffs and failure modes
| Situation | Problem | Better choice |
|---|---|---|
| You need a guaranteed correct answer and a bounded worst case | A Las Vegas algorithm has only an expected time bound, and its worst case is still possible | A deterministic algorithm, if one exists at acceptable cost |
| Running time must be fixed, such as in a real-time system | A Las Vegas algorithm can run long on unlucky coins | A Monte Carlo algorithm with a stated error bound |
| Correctness matters and error must be tiny | A single Monte Carlo run has error up to | Repeat times; the error falls to |
| The input is adversarial and the coins are not secret | Coin flips can be predicted if the random source is weak | Use a cryptographically secure source of randomness |
| A tail guarantee is needed, not just an average | Markov's bound is loose and says little about rare slow runs | Use Chebyshev or concentration inequalities |
For example, the Miller–Rabin primality test is a Monte Carlo algorithm. A witness is a number that proves composite (not prime). If is composite, at most one quarter of the possible choices fail to be witnesses. After 20 independent rounds, the chance of wrongly calling a composite number prime is at most .
Failure modes to watch for:
- Bad seeds or weak randomness. The analysis assumes independent fair coins. A predictable generator breaks the guarantee, sometimes badly.
- Averages hiding bad runs. A small expected cost does not promise a small cost on any given run. Check the tail if one slow run is expensive.
- Mistaking one kind for the other. A Las Vegas algorithm that is wrong, or a Monte Carlo algorithm that is claimed to always be right, is a bug in the analysis.
History
Tony Hoare published quicksort in 1961, after working out its partitioning idea around 1959. It was deterministic in its first form, and the fixed-pivot slow case was known from the start. The benefit of picking pivots at random was clear to later analysts, and it became standard practice in the decades that followed.
The vocabulary of Las Vegas and Monte Carlo algorithms was coined in the late 1970s by László Babai. Michael Rabin's 1980 probabilistic primality test made Monte Carlo methods prominent in practical number theory, and the Miller–Rabin test is still in widespread use.
Carter and Wegman introduced universal families of hash functions in 1979. Their result, that a randomly chosen function from the family makes collisions rare for any fixed set of keys, is the basis of the hash table example above. It caught on because it replaces an assumption about the data with an assumption about the algorithm's own coins.
Recap
A randomized algorithm uses coins, so its cost and sometimes its answer are random. The analysis works on the expected cost for each fixed input, using linearity of expectation and simple counting such as the pair argument for quicksort. A Las Vegas algorithm is always correct with a random running time. A Monte Carlo algorithm has fixed running time with small error, and repetition shrinks the error. Markov's inequality turns an expected cost into a crude tail bound.
This leads on to the skip list, which picks each node's height by coin flips, and to tighter tail bounds from Chebyshev's inequality and concentration inequalities.
Check yourself
QuestionA deterministic algorithm always takes the same path on the same input. Why can a randomized algorithm be fast on every input, even though some inputs are slow for the deterministic version?Show answer
The slow path of a deterministic algorithm is fixed by the input, so an adversary who knows the algorithm can always find the slow input. A randomized algorithm's path depends on fresh coin flips, so no single input is tied to a single path. The analysis then bounds the expected cost for each input over the coins. The bad runs still exist, but they become unlikely for every input at once.
QuestionFor randomized quicksort, the three pivots are equally likely. Pivot 2 costs 2 comparisons in total and pivots 1 and 3 each cost 3. What is the expected number of comparisons, and does it match the formula ?Show answer
The expected number is . The formula gives . They match, so the pair-counting argument gives the right answer on this small case.
QuestionIn Example 2, the average randomized quicksort run on 100 values makes about 648 comparisons. Use Markov's inequality to bound the probability that a run makes at least 1000 comparisons.Show answer
Apply Markov with : . This is a valid bound but a weak one, since the true probability is far smaller. Markov uses only the mean, so it cannot distinguish a run that is rarely slow from one that is often slow.
QuestionA Monte Carlo test has error at most per run and you need error at most . Using independent runs, how many rounds are needed?Show answer
We need , so . Since and , we need rounds. Ten rounds give error at most . Nine rounds are not enough.
QuestionA web service stores user sessions in a hash table with a fixed, public hash function. Why could an attacker slow it down, and how does choosing the hash function at random help?Show answer
With a public fixed function, the attacker can compute which keys share a bucket and send only those, so each lookup scans many keys. A random hash function, drawn from a universal family, is unknown to the attacker before the table is built. For any fixed set of keys, the expected number of keys sharing a bucket with a given key stays small, so the attacker cannot force long chains.