TExcelTAD
Home › Probability Theory › Randomized Algorithms

Randomized Algorithms

A randomized algorithm flips coins as part of its logic. Randomness can make an algorithm simpler, faster on every input (not just on average over inputs), or immune to adversarial inputs. The analysis uses exactly the tools of this course: expectation, indicators, independence and tail bounds.

Two kinds

  • Las Vegas algorithms are always correct; their running time is random. Randomized quicksort is the classic example.
  • Monte Carlo algorithms always run fast; their answer is correct with high probability. Primality tests and Freivalds' matrix check are examples. Repeating a Monte Carlo algorithm kk times with independent coins drives the error probability down exponentially.

Randomized quicksort

Pick the pivot uniformly at random. Elements zi<zjz_i < z_j (the ii-th and jj-th smallest) are compared exactly when one of them is the first pivot chosen among zi,…,zjz_i, \ldots, z_j, which happens with probability 2j−i+1\frac{2}{j - i + 1}. By linearity over indicator variables,

E[comparisons]=∑i<j2j−i+1=2(n+1)Hn−4n≈2nln⁡nE[\text{comparisons}] = \sum_{i < j} \frac{2}{j - i + 1} = 2(n+1)H_n - 4n \approx 2n \ln n

for every input: no bad input exists, only unlucky coin flips, and those are rare.

python · try it yourself
import random
import math

rng = random.Random(1)
def quicksort(a, counter):
    if len(a) <= 1:
        return a
    pivot = a[rng.randrange(len(a))]
    counter[0] += len(a) - 1
    return (quicksort([x for x in a if x < pivot], counter) + [x for x in a if x == pivot]
            + quicksort([x for x in a if x > pivot], counter))

n = 2000
H = sum(1 / k for k in range(1, n + 1))
for name, data in [("random", rng.sample(range(n), n)), ("sorted", list(range(n))), ("reversed", list(range(n, 0, -1)))]:
    counts = []
    for _ in range(20):
        c = [0]
        assert quicksort(data, c) == sorted(data)
        counts.append(c[0])
    print(f"{name:8s} input: average comparisons {sum(counts) / 20:.0f}")
print("theory 2(n+1)H_n - 4n =", round(2 * (n + 1) * H - 4 * n))
random   input: average comparisons 24890
sorted   input: average comparisons 24677
reversed input: average comparisons 24772
theory 2(n+1)H_n - 4n = 24730

Freivalds' algorithm: checking a product

Given n×nn \times n matrices AA, BB, CC, is AB=CAB = C? Multiplying costs about n3n^3 operations. Instead pick a random 0/1 vector r\mathbf{r} and compare A(Br)A(B\mathbf{r}) with CrC\mathbf{r}, which takes O(n2)O(n^2). If AB≠CAB \ne C, the test catches it with probability at least 1/21/2; repeating 20 times leaves an error probability below 10−610^{-6}.

python · try it yourself
import numpy as np

rng = np.random.default_rng(2)
n = 300
A = rng.integers(0, 10, (n, n))
B = rng.integers(0, 10, (n, n))
C = A @ B
C_bad = C.copy()
C_bad[123, 45] += 1                             # one wrong entry

def freivalds(A, B, C, rounds=20):
    for _ in range(rounds):
        r = rng.integers(0, 2, n)
        if not np.array_equal(A @ (B @ r), C @ r):
            return False
    return True

print("correct product accepted:", freivalds(A, B, C))
print("wrong product accepted:  ", freivalds(A, B, C_bad))
caught = sum(not freivalds(A, B, C_bad, rounds=1) for _ in range(2000))
print("single-round detection rate:", caught / 2000)
correct product accepted: True
wrong product accepted:   False
single-round detection rate: 0.5115

With one wrong entry at row 123, column 45, a single round detects it exactly when r45=1r_{45} = 1: probability 1/21/2.

Miller–Rabin primality testing

Fermat's little theorem says ap−1≡1(modp)a^{p-1} \equiv 1 \pmod p for prime pp (Inverses, Fermat and Euler). Miller–Rabin strengthens this test so that for any composite nn, at least 3/43/4 of the bases aa expose it. With 40 random bases, a composite slips through with probability at most 4−404^{-40}. This is how RSA key generation finds large primes.

python · try it yourself
import random

def miller_rabin(n, rounds, rng):
    if n < 4:
        return n in (2, 3)
    if n % 2 == 0:
        return False
    d, s = n - 1, 0
    while d % 2 == 0:
        d, s = d // 2, s + 1
    for _ in range(rounds):
        x = pow(rng.randrange(2, n - 1), d, n)
        if x in (1, n - 1):
            continue
        for _ in range(s - 1):
            x = x * x % n
            if x == n - 1:
                break
        else:
            return False
    return True

rng = random.Random(3)
print("561 (a Carmichael number):", miller_rabin(561, 20, rng))
print("2^61 - 1:", miller_rabin(2 ** 61 - 1, 20, rng))
print("2^61 + 1:", miller_rabin(2 ** 61 + 1, 20, rng))
big = rng.getrandbits(256) | (1 << 255) | 1
while not miller_rabin(big, 40, rng):
    big += 2
print("a 256-bit probable prime ends in ...", str(big)[-12:])
561 (a Carmichael number): False
2^61 - 1: True
2^61 + 1: False
a 256-bit probable prime ends in ... 480840474719

In software

Randomization is everywhere in systems: random pivots and hash seeds defeat adversarial inputs (hash-flooding attacks), random load balancing ("power of two choices") keeps queues short, consistent hashing spreads keys, Bloom filters and HyperLogLog trade exactness for memory, and randomized backoff resolves contention. The DSA course implements quicksort step by step.

Exercises

Exercise 1: Repeating a Monte Carlo test

A test wrongly accepts a bad input with probability at most 1/41/4 per run. How many independent runs make the error probability below 10−910^{-9}?

Answer

15 runs.

Solution

4−k<10−94^{-k} < 10^{-9} needs k>9/log⁡104≈14.95k > 9/\log_{10}4 \approx 14.95.

Exercise 2: Comparison probability

In randomized quicksort, what is the probability that the smallest and largest of nn elements are ever compared?

Answer

2/n2/n.

Solution

They are compared only if one of them is the first pivot chosen among all nn elements: probability 2n−1+1\frac{2}{n - 1 + 1}.

Exercise 3: Power of two choices (code)

Throw n=10,000n = 10{,}000 balls into nn bins: (a) each ball into a random bin; (b) each ball picks two random bins and goes into the less loaded one. Compare the maximum loads.

Answer

About 7 for (a) and only about 3 for (b).

Solution

One choice gives maximum load about ln⁡nln⁡ln⁡n\frac{\ln n}{\ln \ln n}; two choices give about ln⁡ln⁡nln⁡2\frac{\ln \ln n}{\ln 2}, an exponential improvement.

python · try it yourself
import random

rng = random.Random(4)
n = 10_000
one = [0] * n
two = [0] * n
for _ in range(n):
    one[rng.randrange(n)] += 1
    a, b = rng.randrange(n), rng.randrange(n)
    two[a if two[a] <= two[b] else b] += 1
print("one choice max load:", max(one), "  two choices max load:", max(two))
one choice max load: 7   two choices max load: 3

Going further: the Randomized Algorithms course in the Algorithm Theory track covers Chernoff bounds, Karger's min-cut, hashing, Markov-chain mixing and derandomization.

Test yourself

A Las Vegas algorithm is one that…

  1. is always correct, with random running time
  2. is always fast but sometimes wrong
  3. uses no randomness
  4. only works on random inputs

Randomized quicksort's expected number of comparisons is O(nlog⁡n)O(n \log n)…

  1. only for random inputs
  2. for every input
  3. only for sorted inputs
  4. only in the best case