Search

Search papers and lessons

Randomized Algorithms

Level 3 · 13 min read

A randomized algorithm flips coins while it runs, so its cost is a random variable. Because no input can fool the coins, it often runs fast on every input, and its average cost is easy to bound.

On this page

  • Colour = topic mix
  • Discrete math
  • Calculus
  • Probability
  • Algorithms
  • Sign in to see your progress

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

Definition: Las Vegas algorithm

A randomized algorithm that always returns a correct answer. Its running time TT is a random variable, and what we usually bound is E[T]\mathbb{E}[T], the expected running time for each fixed input.

Definition: Monte Carlo algorithm

A randomized algorithm that runs in a fixed, bounded time but may return a wrong answer with probability at most some ε<1\varepsilon \lt 1. Errors can be one-sided (it never errs on "no") or two-sided.

Here E[⋅]\mathbb{E}[\cdot] is the expected value, the average over all the algorithm's coin flips, and ε\varepsilon 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 CC 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 z1<z2<⋯<znz_1 \lt z_2 \lt \dots \lt z_n. Two values ziz_i and zjz_j 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 {zi,…,zj}\{z_i, \dots, z_j\}. The first of these values to be picked as a pivot decides the matter:

  • If the first pivot is ziz_i or zjz_j, then ziz_i and zjz_j are compared.
  • If the first pivot is strictly between them, they are separated and never compared.

Each of the j−i+1j - i + 1 values is equally likely to be first, so

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

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 d=j−id = j - i. There are n−dn - d pairs with gap dd, so

E[C]=∑d=1n−1(n−d)⋅2d+1.\mathbb{E}[C] = \sum_{d=1}^{n-1} (n-d) \cdot \frac{2}{d+1}.

Put k=d+1k = d + 1 and use the harmonic number Hn=1+12+⋯+1nH_n = 1 + \tfrac{1}{2} + \dots + \tfrac{1}{n}:

E[C]=∑k=2n2(n+1−k)k=2(n+1)(Hn−1)−2(n−1)=2(n+1)Hn−4n.\begin{aligned} \mathbb{E}[C] &= \sum_{k=2}^{n} \frac{2(n+1-k)}{k} \\ &= 2(n+1)(H_n - 1) - 2(n-1) \\ &= 2(n+1)H_n - 4n. \end{aligned}

Since HnH_n grows like the natural logarithm ln⁡n\ln n, the expected cost is about 2nln⁡n2n \ln n, which is O(nlog⁡n)O(n \log n). The worst case, which the random pivot makes extremely unlikely, is n(n−1)/2n(n-1)/2.

20406080100010002000300040005000ncomparisons
  • worst case
  • 2 n ln n (leading term)
The worst case grows as n squared; the random-pivot average grows as n log n. The dashed curve is only the leading term, so it sits above the exact average (about 648 at n = 100, against a worst case of 4950).

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 XX and any a>0a \gt 0,

Pr⁡[X≥a]≤E[X]a.\Pr[X \ge a] \le \frac{\mathbb{E}[X]}{a}.

With a=2 E[C]a = 2\,\mathbb{E}[C], this says the chance of using at least twice the expected comparisons is at most 1/21/2.

Monte Carlo error and repetition

If a one-sided Monte Carlo algorithm errs with probability at most ε\varepsilon on a "yes" instance, and you run it kk times independently, the error drops to at most εk\varepsilon^k. The error is small after a few rounds, so repetition is the usual way to buy reliability.

Worked examples

Example
Example 1: sorting three values, by hand

Take the list [1,2,3][1, 2, 3] and choose the pivot uniformly at random among the three values.

  1. Pivot 11 (probability 1/31/3). Compare 11 with 22 and 33: 2 comparisons. Parts [ ][\,] and [2,3][2, 3]. Sorting [2,3][2, 3] needs 1 more. Total 33.
  2. Pivot 22 (probability 1/31/3). Compare 22 with 11 and 33: 2 comparisons. Parts [1][1] and [3][3] need nothing. Total 22.
  3. Pivot 33 (probability 1/31/3). Compare 33 with 11 and 22: 2 comparisons. Parts [1,2][1, 2] need 1 more. Total 33.
  4. Average over the three equally likely pivots: E[C]=(3+2+3)/3=8/3≈2.67\mathbb{E}[C] = (3 + 2 + 3)/3 = 8/3 \approx 2.67.
  5. Check with the formula: 2(n+1)H3−4n=8⋅116−12=443−12=832(n+1)H_3 - 4n = 8 \cdot \tfrac{11}{6} - 12 = \tfrac{44}{3} - 12 = \tfrac{8}{3}. 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.

Example
Example 2: the textbook case, n = 100

Take a list of n=100n = 100 distinct values sorted by randomized quicksort.

  1. H100≈5.1874H_{100} \approx 5.1874.
  2. E[C]=2(101)(5.1874)−4(100)≈1047.85−400=647.85\mathbb{E}[C] = 2(101)(5.1874) - 4(100) \approx 1047.85 - 400 = 647.85.
  3. So the average run makes about 648 comparisons.
  4. The worst case is 100⋅99/2=4950100 \cdot 99 / 2 = 4950 comparisons, which is about 7.6 times the average.
  5. By Markov's inequality, Pr⁡[C≥2×648]=Pr⁡[C≥1296]≤1/2\Pr[C \ge 2 \times 648] = \Pr[C \ge 1296] \le 1/2.

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.

Example
Example 3: a hash table with a random hash function

A Hash Table stores keys in mm 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 m=1000m = 1000 buckets.

  1. 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.
  2. Instead, pick the hash function at random from a universal family. For this family, two different keys xx and yy collide with probability at most 1/m1/m over the random choice.
  3. Fix a key xx that is stored. The other 799 keys each collide with xx with probability at most 1/10001/1000.
  4. By linearity of expectation, the expected number of other keys in xx's bucket is at most 799/1000=0.799799 / 1000 = 0.799.
  5. 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

SituationProblemBetter choice
You need a guaranteed correct answer and a bounded worst caseA Las Vegas algorithm has only an expected time bound, and its worst case is still possibleA deterministic algorithm, if one exists at acceptable cost
Running time must be fixed, such as in a real-time systemA Las Vegas algorithm can run long on unlucky coinsA Monte Carlo algorithm with a stated error bound
Correctness matters and error must be tinyA single Monte Carlo run has error up to ε\varepsilonRepeat kk times; the error falls to εk\varepsilon^k
The input is adversarial and the coins are not secretCoin flips can be predicted if the random source is weakUse a cryptographically secure source of randomness
A tail guarantee is needed, not just an averageMarkov's bound is loose and says little about rare slow runsUse Chebyshev or concentration inequalities

For example, the Miller–Rabin primality test is a Monte Carlo algorithm. A witness is a number that proves nn composite (not prime). If nn 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 (1/4)20≈9×10−13(1/4)^{20} \approx 9 \times 10^{-13}.

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 n=3n = 3 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 2(n+1)Hn−4n2(n+1)H_n - 4n?Show answer

The expected number is (3+2+3)/3=8/3(3 + 2 + 3)/3 = 8/3. The formula gives 2⋅4⋅116−12=443−12=832 \cdot 4 \cdot \tfrac{11}{6} - 12 = \tfrac{44}{3} - 12 = \tfrac{8}{3}. 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 a=1000a = 1000: Pr⁡[C≥1000]≤648/1000=0.648\Pr[C \ge 1000] \le 648/1000 = 0.648. 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 1/41/4 per run and you need error at most 10−610^{-6}. Using independent runs, how many rounds are needed?Show answer

We need (1/4)k≤10−6(1/4)^k \le 10^{-6}, so 4k≥1064^k \ge 10^6. Since 49=2621444^9 = 262144 and 410=10485764^{10} = 1048576, we need k=10k = 10 rounds. Ten rounds give error at most (1/4)10≈9.5×10−7(1/4)^{10} \approx 9.5 \times 10^{-7}. 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.

Sources