DSA Notes
Master randomized algorithms — the difference between Las Vegas and Monte Carlo algorithms, randomized quicksort with expected O(n log n), reservoir sampling for streaming data, randomized selection for kth element, Miller-Rabin primality test, and why randomization defeats adversarial inputs.
What Are Randomized Algorithms?
A randomized algorithm is an algorithm that makes random choices during its execution. Instead of following a fixed deterministic path, it uses random numbers to guide decisions. This randomness provides powerful benefits:
- Break adversarial patterns: An attacker cannot craft a worst-case input because the algorithm's behavior is unpredictable
- Simplify algorithms: Complex deterministic algorithms often have elegant randomized equivalents
- Expected efficiency: Many problems that are hard to solve deterministically in O(n log n) have simple randomized solutions with the same expected complexity
Randomized QuickSort — Las Vegas Algorithm
Why Randomize?
Standard QuickSort chooses a fixed pivot (e.g., last element). An adversary who knows this can create sorted or reverse-sorted input that causes O(n²) performance every time.
Randomized QuickSort picks a random pivot, making adversarial inputs impossible to construct.
Expected Complexity Proof (Informal)
A random pivot splits the array into left and right portions. Consider "good splits": where each portion has between n/4 and 3n/4 elements.
- A random pivot gives a good split with probability ≥ 1/2
- With a good split, we make at least 1/4 progress per level
- Expected levels needed: O(log n)
- Total expected work: O(n log n)
Randomized Selection (QuickSelect) — Las Vegas
Problem: Find the kth smallest element in an unsorted array.
Naive approach: Sort then index — O(n log n) QuickSelect: O(n) expected, O(n²) worst case, but randomization makes worst case astronomically unlikely.
Expected O(n) proof: On average, a random pivot eliminates at least half the elements. Total work: n + n/2 + n/4 + ... = 2n = O(n).
Reservoir Sampling — Uniformly Sample k Items from a Stream
Problem: Given a stream of unknown length n, select k items uniformly at random. You cannot store all n items (n might be huge or unknown).
Why it works: After seeing i+1 elements, each element has k/(i+1) probability of being in the reservoir. Mathematical induction proves this invariant holds at every step.
Applications: Online analytics, A/B testing, sampling social media feeds, distributed computing where you can't hold all data.
Miller-Rabin Primality Test — Monte Carlo
Problem: Is the number n prime?
Naive: Trial division up to √n — O(√n) — too slow for large n (cryptographic primes are 2048 bits = hundreds of digits).
Miller-Rabin: Probabilistic test — O(k log² n) for k rounds. After k rounds, probability of a composite being declared prime is at most 4^(-k).
Random Walk Algorithms
Applications: Search algorithms, physics simulations, financial modeling, network analysis.
Randomized Hashing to Prevent DoS
Python's built-in dict uses hash randomization (PYTHONHASHSEED) for exactly this reason — to prevent adversarial inputs from degrading hash map performance.
When to Use Randomized Algorithms
USE randomized algorithms when
✅ Adversarial inputs are possible (use randomized quicksort)
✅ Streaming data of unknown/large size (reservoir sampling)
✅ Exact computation is too slow (Miller-Rabin vs trial division)
✅ Approximate answers are acceptable (Monte Carlo integration)
✅ Deterministic alternatives are extremely complex (skip lists)
DON'T use when
❌ Output must be deterministically correct every time
❌ Reproducing exact results is required (debugging, testing)
❌ Worst-case guarantees are mandatory (use deterministic alternatives)
Summary
| Algorithm | Type | Expected Time | Correctness |
|---|---|---|---|
| Randomized QuickSort | Las Vegas | O(n log n) | Always correct |
| QuickSelect | Las Vegas | O(n) | Always correct |
| Reservoir Sampling | Las Vegas | O(n) | Always correct |
| Miller-Rabin (k rounds) | Monte Carlo | O(k log² n) | Error ≤ 4^(-k) |
| Random Walk | — | O(n) | — |
Randomized algorithms are a fundamental tool in a programmer's toolkit. QuickSelect, randomized hashing, and reservoir sampling appear in production systems every day. Understanding the distinction between Las Vegas (always correct, random time) and Monte Carlo (bounded time, probabilistic correctness) is essential for choosing the right approach.
*Next: Computational Geometry*
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Randomized Algorithms — Las Vegas, Monte Carlo, and Probabilistic Techniques.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Data Structures & Algorithms topic.
Search Terms
data-structures-algorithms, data structures & algorithms, data, structures, algorithms, advanced, topics, randomized
Related Data Structures & Algorithms Topics