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 times with independent coins drives the error probability down exponentially.
Randomized quicksort
Pick the pivot uniformly at random. Elements (the -th and -th smallest) are compared exactly when one of them is the first pivot chosen among , which happens with probability . By linearity over indicator variables,
for every input: no bad input exists, only unlucky coin flips, and those are rare.
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 matrices , , , is ? Multiplying costs about operations. Instead pick a random 0/1 vector and compare with , which takes . If , the test catches it with probability at least ; repeating 20 times leaves an error probability below .
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 : probability .
Miller–Rabin primality testing
Fermat's little theorem says for prime (Inverses, Fermat and Euler). Miller–Rabin strengthens this test so that for any composite , at least of the bases expose it. With 40 random bases, a composite slips through with probability at most . This is how RSA key generation finds large primes.
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 per run. How many independent runs make the error probability below ?
Answer
15 runs.
Solution
needs .
Exercise 2: Comparison probability
In randomized quicksort, what is the probability that the smallest and largest of elements are ever compared?
Answer
.
Solution
They are compared only if one of them is the first pivot chosen among all elements: probability .
Exercise 3: Power of two choices (code)
Throw balls into 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 ; two choices give about , an exponential improvement.
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…
- is always correct, with random running time
- is always fast but sometimes wrong
- uses no randomness
- only works on random inputs
Randomized quicksort's expected number of comparisons is …
- only for random inputs
- for every input
- only for sorted inputs
- only in the best case