"Sometimes the smartest move is to flip a coin. Randomness can dodge worst-case inputs an adversary would exploit, and let you sample an answer when computing the exact one is impossible. Giving up a little certainty buys a lot of speed."
Randomness as a Tool, Not a Bug
You usually want determinism — but deliberately injecting randomness is a genuine algorithmic strategy with two superpowers. First, it defeats adversarial inputs: a fixed-pivot quicksort has a worst case an attacker can trigger with sorted data, but a random pivot can't be predicted, so the O(n²) case becomes astronomically unlikely regardless of input. (This is also why Python salts string hashes — to stop crafted hash collisions.) Second, it enables sampling: when computing an exact answer is infeasible, a random sample gives a good estimate fast.
Two Flavors of Randomized Algorithm
- Las Vegas: always returns the correct answer, but the runtime is random. Randomized quicksort is the classic — the output is always sorted; only the speed depends on luck (and is excellent in expectation). You never get a wrong answer, just occasionally a slower run.
- Monte Carlo: runs in fixed time but may be wrong with small, controllable probability. The Miller-Rabin primality test says 'probably prime' with an error you can drive below any threshold by repeating. You trade a tiny chance of error for guaranteed speed.
Knowing which guarantee you have — always-right-maybe-slow versus always-fast-maybe-wrong — tells you whether a randomized algorithm is safe for your use.
The Gem: Reservoir Sampling
The most elegant randomized algorithm is reservoir sampling: pick a uniformly-random item from a stream of unknown, possibly enormous length, in O(1) space and one pass. The trick: keep the current pick; when the i-th item arrives, replace your pick with it with probability 1/i. When the stream ends, every item — first or billionth — had an equal chance of being chosen, provably. It's how you sample a random line from a file too big to hold in memory, or a random log entry from an endless feed. One variable, one pass, perfect uniformity, no idea how long the stream is. Pure randomized magic.