Randomized Algorithms
A randomized algorithm makes random choices while it runs. Las Vegas algorithms are always correct but take a random amount of time; Monte Carlo algorithms run in fixed time but may be wrong with a small, known probability that repetition shrinks.
What Randomized Algorithms Are
Randomized algorithms make some of their choices by flipping coins. For a fixed input, the running time or the answer can then vary from run to run, and the analysis is over those coin flips, not over a guess about which inputs are likely.
The payoff is that no single input is bad every time. A deterministic method always has some input that hits its worst case, and an adversary who knows the method can supply it. In the tracer, a left-to-right search for an a in bbbbaaaa always needs 5 probes, while random probes need 2 on average for every arrangement.
- Randomness is inside the algorithm, not assumed about the input
- Guarantees are probabilities over the coin flips
Las Vegas and Monte Carlo Algorithms
Las Vegas algorithms always return a correct answer; only their running time is random. Random pivot choice in quick sort and quickselect is the classic case: always sorted, O(n log n) expected time, O(n²) in very unlucky runs. Monte Carlo algorithms always finish within a fixed time but may answer wrongly with a bounded probability, like the Miller–Rabin primality test.
A Monte Carlo algorithm becomes Las Vegas if its answer can be checked cheaply: check, and rerun on failure. A Las Vegas algorithm becomes Monte Carlo by stopping after a time limit and guessing.
| Las Vegas | Monte Carlo | |
|---|---|---|
| Answer | Always correct | Correct with high probability |
| Running time | Random; analysed as expected time | Fixed bound |
| Example | Random pivot quicksort, random probing | Miller–Rabin, Karger's min cut, Freivalds' check |
| Make it safer by | Nothing needed for correctness | Repeating with fresh random choices |
- Las Vegas: gamble on time
- Monte Carlo: gamble on correctness
Randomized Algorithm Examples
Random probing: find an a in an array that is half a's: each probe succeeds with probability 1/2, so the expected number of probes is 2 and more than k probes happens with probability (1/2)ᵏ. Primality testing: the Fermat test checks aⁿ⁻¹ ≡ 1 (mod n) for a random base a (modular arithmetic); Miller–Rabin strengthens it so that each round is fooled with probability at most 1/4.
Hashing: a randomly chosen hash function keeps an adversary from forcing collisions (hash tables); random hashes are also behind Bloom filters and string hashing. Structures: skip lists and treaps use coin flips to stay balanced in expectation. Karger's algorithm finds a minimum cut by contracting random edges; one run succeeds with probability at least 2 / (n(n − 1)), so it is repeated many times.
- Searching, primality, hashing, balancing, cuts
Terms, operations, and practical uses
Guarantees
- Las VegasAlways correct; the running time is random and analysed as an expectation.
- Monte CarloFixed running time; wrong with a bounded probability, such as 1/4 per Miller–Rabin round.
- Expected running timeAverage over the algorithm's coin flips for the worst input, not over random inputs.
Probability
- One-sided errorOnly one kind of answer can be wrong, e.g. 'probably prime'. A 'composite' answer is certain.
- Amplificationk independent runs that each fail with probability p all fail with probability pᵏ.
- Carmichael numberA composite like 561 that passes the Fermat test for every coprime base.
Fair randomness
- Modulo biasr % k is uneven when the generator's range is not a multiple of k; reject the tail instead.
- Fisher–Yates shuffleSwap a[i] with a random a[j], j in 0 … i, for i from n − 1 down: every order has probability 1/n!.
- Reservoir samplingKeep the i-th stream item with probability k/i; each item ends in the sample with probability k/n.
Code in Python, C++ and Java
import random
def fisher_yates(a, pick):
for i in range(len(a) - 1, 0, -1):
j = pick(i)
a[i], a[j] = a[j], a[i]
return a
fixed = iter([1, 0, 1])
print("Shuffled:", ", ".join(map(str, fisher_yates([1, 2, 3, 4], lambda i: next(fixed)))))
rng = random.Random(42)
counts = {}
for _ in range(60000):
order = tuple(fisher_yates([1, 2, 3], lambda i: rng.randint(0, i)))
counts[order] = counts.get(order, 0) + 1
print("Orders of [1, 2, 3] seen:", len(counts), "each close to 10000:", all(9500 < c < 10500 for c in counts.values()))#include <functional>
#include <iostream>
#include <map>
#include <random>
#include <vector>
using namespace std;
vector<int> fisherYates(vector<int> a, const function<int(int)>& pick) {
for (int i = (int)a.size() - 1; i > 0; i--) swap(a[i], a[pick(i)]);
return a;
}
int main() {
vector<int> fixed = {1, 0, 1};
int k = 0;
vector<int> s = fisherYates({1, 2, 3, 4}, [&](int) { return fixed[k++]; });
cout << "Shuffled: ";
for (size_t i = 0; i < s.size(); i++) cout << (i ? ", " : "") << s[i];
cout << "\n";
mt19937 rng(42);
map<vector<int>, int> counts;
for (int r = 0; r < 60000; r++)
counts[fisherYates({1, 2, 3}, [&](int i) { return uniform_int_distribution<int>(0, i)(rng); })]++;
bool even = true;
for (auto& [order, c] : counts) even = even && c > 9500 && c < 10500;
cout << "Orders of [1, 2, 3] seen: " << counts.size() << " each close to 10000: " << (even ? "True" : "False") << "\n";
}import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.function.IntUnaryOperator;
public class Main {
static int[] fisherYates(int[] a, IntUnaryOperator pick) {
for (int i = a.length - 1; i > 0; i--) {
int j = pick.applyAsInt(i);
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return a;
}
public static void main(String[] args) {
int[] fixed = {1, 0, 1};
int[] k = {0};
int[] s = fisherYates(new int[] {1, 2, 3, 4}, i -> fixed[k[0]++]);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length; i++) sb.append(i > 0 ? ", " : "").append(s[i]);
System.out.println("Shuffled: " + sb);
Random rng = new Random(42);
Map<String, Integer> counts = new HashMap<>();
for (int r = 0; r < 60000; r++)
counts.merge(Arrays.toString(fisherYates(new int[] {1, 2, 3}, i -> rng.nextInt(i + 1))), 1, Integer::sum);
boolean even = counts.values().stream().allMatch(c -> c > 9500 && c < 10500);
System.out.println("Orders of [1, 2, 3] seen: " + counts.size() + " each close to 10000: " + (even ? "True" : "False"));
}
}Step through it
Running on bbbbaaaa, n = 341, n = 561
Shrinking the Error by Repeating
If one Monte Carlo run is wrong with probability at most p, then k independent runs are all wrong with probability at most pᵏ. Miller–Rabin with 20 random bases errs with probability below (1/4)²⁰, under one in a trillion. This is amplification, and it only works when each run has a real bound: the plain Fermat test is fooled by every base coprime to a Carmichael number such as 561 = 3 × 11 × 17, so repeating it never helps there.
For one-sided errors (only 'probably prime' can be wrong), a single 'composite' answer is final. Two-sided errors are combined by majority vote over several runs. Runs must use independent random choices; reusing the same seed repeats the same mistake.
- k runs: error ≤ pᵏ
- Needs independence and a per-run bound
Fair Shuffling and Sampling
- Fisher–Yates: for i = n − 1 down to 1
- Pick j uniformly from 0 … i (i itself included)
- Swap a[i] and a[j]
Modulo bias: turning a random number from 0 to 7 into 0 to 2 with r % 3 gives outcome 2 a chance of 2/8 instead of 1/3, because 8 is not a multiple of 3. Reject values from the uneven tail (6 and 7) and draw again; use the library's bounded-range function where one exists.
Fisher–Yates shuffle: for i from n − 1 down to 1, swap a[i] with a[j] for j chosen uniformly from 0 … i. Each of the n! orders comes out with probability exactly 1/n!. Choosing j from 0 … n − 1 instead gives nⁿ equally likely runs, which cannot split evenly over n! orders, so some orders appear more often. Reservoir sampling picks one item uniformly from a stream of unknown length: keep item i with probability 1/i, replacing the current pick. For k items, keep item i with probability k/i and replace a random slot.
- Reject, don't take %, for uneven ranges
- Shrinking range in Fisher–Yates
Analysing Expected Running Time
Expected running time averages over the algorithm's own coin flips for the worst input, which is different from average-case analysis, where the input is assumed random. The usual tools are linearity of expectation (the expected sum is the sum of expectations, even for dependent parts) and tail bounds that show long runs are rare.
Random pivot quicksort makes about 2n ln n ≈ 1.39 n log₂ n comparisons in expectation for every input, because any two elements are compared only if one of them is the first pivot chosen from the range between them. The worst case remains O(n²), but its probability on large inputs is vanishingly small. See also amortised analysis, which bounds total cost without probability.
- Expected over coin flips, worst over inputs
- Linearity of expectation does most of the work
Seeds, Testing and Security
Let callers pass a seed or a random generator, and log the seed with any failure so the run can be replayed. Use fixed seeds in unit tests and many seeds in stress tests. Statistical checks (does each shuffle order appear about equally often?) catch gross bias but do not prove uniformity; that comes from the argument above.
Ordinary pseudo-random generators are predictable. If an attacker can see outputs or guess the seed, they can rebuild the bad input the randomness was meant to avoid, for example hash-flooding a server. Use a cryptographically secure generator wherever an adversary is involved.
- Log the seed with every failure
- Secure generator against adversaries