Design and Analysis of AlgorithmsUnit 1014 min read
Recurrence Relations & Randomized Algorithms: Solving Recurrences & Probabilistic Design
Unit 10 of Design and Analysis of Algorithms covers recurrence relations (solving via substitution, recursion tree, and master theorem) and randomized algorithms (Monte Carlo, Las Vegas, and probabilistic primality tests like Miller-Rabin), with real-world ties to cryptography, load balancing, and search engines.
TAKEAWAYS:
- Recurrence relations model divide-and-conquer algorithms (e.g., mergesort, binary search) and are solved via substitution, recursion trees, or the Master Theorem—each method has a distinct use case.
- Randomized algorithms (e.g., Miller-Rabin, quicksort with random pivots) trade determinism for efficiency, often achieving expected O(n log n) time where deterministic versions hit worst-case O(n²).
- The Master Theorem provides a shortcut for solving recurrences of the form by comparing to .
- Monte Carlo algorithms may return wrong answers with probability , while Las Vegas algorithms always give correct results but have random runtime.
- Recursion trees visually decompose recurrences into subproblems, revealing hidden patterns (e.g., geometric series in mergesort).
- Randomization in practice: Google’s PageRank uses probabilistic sampling, and Ncell’s call-routing algorithms rely on randomized load balancing.
1. Recurrence Relations: Modeling Divide-and-Conquer Algorithms
Recurrence relations express the runtime of recursive algorithms in terms of smaller inputs. For example, mergesort’s recurrence is: This means:
- Divide: Split the problem into 2 subproblems of size .
- Conquer: Solve each subproblem recursively ().
- Combine: Merge results in time.
graph TD
A["Divide: Split into 2 subproblems of size n/2"] --> B["Conquer: Solve recursively: 2T(n/2)"]
A --> C["Combine: Merge in O(n) time"]
B --> D["Base Case: T(1) = O(1)"]
C --> E["Total Cost: O(n log n)"]Divide-and-conquer steps for mergesort, showing how the recurrence T(n) = 2T(n/2) + O(n) breaks down.How to Solve Recurrences?
Three methods:
- Substitution Method: Guess a solution (e.g., ) and verify via induction.
- Recursion Tree: Visualize the cost at each level of recursion.
- Master Theorem: Direct formula for recurrences of the form .
1.1 Substitution Method
Example: Solve (mergesort). Guess: . Base Case: For , . Inductive Step: Assume . Then: We need : Thus, holds for .
Visual Trace:
graph TD
A["T(n) = 2T(n/2) + n"] --> B["T(n/2) = 2T(n/4) + n/2"]
A --> C["T(n/2) = 2T(n/4) + n/2"]
B --> D["T(n/4) = 2T(n/8) + n/4"]
C --> E["T(n/4) = 2T(n/8) + n/4"]
D --> F["T(n/8) = O(1)"]
E --> G["T(n/8) = O(1)"]Key Insight: The recursion tree for mergesort has levels, each costing .
1.2 Recursion Tree Method
Example: Solve . Tree Structure:
Level 0: n
Level 1: n/4 + 3n/4 = n
Level 2: n/16 + 3n/16 + 3n/16 + 9n/16 = 2n
Level 3: 4n/64 + 9n/64 + 9n/64 + 27n/64 = 5n/16 + 27n/64 = (20n + 27n)/64 = 47n/64 ≈ 0.73n
...
Total Cost: Sum of a geometric series where each level’s cost decreases by a factor of . Solution: .
Figure: Recursion Tree for
levels = ["Level 0", "Level 1", "Level 2", "Level 3", "..."] costs = [n, n, 2n, 0.73n, "→ Geometric Series"]
The tree shows how costs accumulate across levels.
1.3 Master Theorem
For recurrences of the form , compare to :
- Case 1: If for , then .
- Case 2: If , then .
- Case 3: If and for , then .
Example: Solve .
- Here, , , so .
- .
- Case 2 applies: .
Table: Master Theorem Cases
| Case | Condition | Solution |
|---|---|---|
| Case 1 | ||
| Case 2 | ||
| Case 3 |
2. Randomized Algorithms: Probabilistic Efficiency
Randomized algorithms use randomness to achieve:
- Faster average-case performance (e.g., quicksort with random pivots).
- Simpler correctness proofs (e.g., Monte Carlo methods).
- Probabilistic guarantees (e.g., Las Vegas algorithms).
Types of Randomized Algorithms
| Type | Correctness | Runtime | Example |
|---|---|---|---|
| Monte Carlo | May be wrong | Fixed | Primality testing (probabilistic) |
| Las Vegas | Always correct | Random | Quickselect (randomized pivot) |
| Randomized | Always correct | Expected | Miller-Rabin primality test |
2.1 Monte Carlo vs. Las Vegas
- Monte Carlo: May return incorrect results with small probability (e.g., "Is this number prime?" with 99% confidence).
- Las Vegas: Always correct but runtime is random (e.g., quicksort’s worst case is avoided by random pivots).
Example: Miller-Rabin Primality Test (Las Vegas). Input: Odd integer , accuracy parameter . Output: "Prime" or "Composite" with error probability .
Algorithm Steps:
- Write where is odd.
- Pick a random .
- Check:
- If or for some , then is probably prime.
- Else, is definitely composite.
- Repeat times. If all tests pass, is prime with probability .
Code (Python-like Pseudocode):
def miller_rabin(n, k):
if n <= 1: return False
if n <= 3: return True
if n % 2 == 0: return False
# Write n-1 as 2^s * d
d = n - 1
s = 0
while d % 2 == 0:
d //= 2
s += 1
# Test k times
for _ in range(k):
a = rand(2, n-2)
x = pow(a, d, n)
if x == 1 or x == n - 1: continue
for __ in range(s - 1):
x = pow(x, 2, n)
if x == n - 1: break
else:
return False
return True
Trace for (Carmichael number, should fail):
| Step | Result | ||
|---|---|---|---|
| 1 | 2 | Not 1 or 560 → Composite |
Why Randomization?
- Deterministic primality tests (e.g., AKS) are slow ().
- Miller-Rabin runs in and is used in Ncell’s SIM card authentication and eSewa’s transaction validation.
2.2 Randomized Quicksort
Problem: Quicksort’s worst case is (e.g., already sorted array). Solution: Randomize the pivot selection.
Algorithm:
- Pick a random pivot from the array.
- Partition the array into and .
- Recurse on both partitions.
Expected Runtime: because the probability of worst-case splits is negligible.
Figure: Randomized Quicksort Partitioning
levels = ["Initial Array", "After 1st Partition", "After 2nd Partition", "..."] arrays = [ [3, 8, 7, 1, 9, 4, 5, 2, 6], # Random pivot = 5 ["<5: [3,1,4,2]", "≥5: [8,7,9,5,6]"], # Pivot moved to end ["<8: [3,1,4,2]", "≥8: [7,9,5,6]", "Pivot=8"] ]
Code:
import random
def randomized_quicksort(A, lo, hi):
if lo >= hi: return
p = random.randint(lo, hi)
A[p], A[hi] = A[hi], A[p] # Move pivot to end
pivot = A[hi]
i = lo
for j in range(lo, hi):
if A[j] <= pivot:
A[i], A[j] = A[j], A[i]
i += 1
A[i], A[hi] = A[hi], A[i] # Move pivot to correct position
randomized_quicksort(A, lo, i-1)
randomized_quicksort(A, i+1, hi)
Trace for :
| Step | Pivot | Partitioned Array | Recursive Calls |
|---|---|---|---|
| 1 | 5 | [3,1,4,2], [8,7,9,5,6] | Sort [3,1,4,2], [8,7,9,6] |
| 2 (left) | 2 | [1,2], [3,4] | Sort [1], [3,4] |
| 2 (right) | 6 | [8,7,9], [6] | Sort [8,7,9] |
| 3 | 4 | [3], [4] | Base case |
| 4 | 9 | [7,8], [9] | Base case |
3. Real-World Applications
3.1 Recurrence Relations in Practice
- Google’s PageRank: The algorithm’s convergence is modeled by a recurrence relation involving the adjacency matrix of the web graph.
- Ncell’s Call Routing: The load on base stations is modeled recursively to optimize handoffs between towers.
- Daraz’s Order Processing: The time to process orders is (divide orders into batches, process in parallel).
Example: NTC’s Network Latency Prediction Suppose NTC measures latency for routers as: Using the Master Theorem:
- , , .
- .
- Case 2: . Interpretation: Doubling routers increases latency by a logarithmic factor, guiding NTC’s infrastructure scaling.
3.2 Randomized Algorithms in Nepalese Tech
| Company/Product | Algorithm Used | Purpose |
|---|---|---|
| eSewa | Miller-Rabin (Monte Carlo) | Validate transaction hashes (probabilistic collision resistance). |
| Khalti | Randomized quicksort | Shuffle payment queues to prevent DoS attacks. |
| Pathao | Las Vegas routing | Dynamically reroute drivers to balance load. |
| NEPSE | Randomized sampling | Estimate stock market trends without full data scans. |
| Ncell | Miller-Rabin + AES | Secure SIM card authentication. |
Example: Khalti’s Payment Queue Khalti processes payments in a queue. A deterministic FIFO queue could be exploited for denial-of-service (e.g., spamming small transactions). Instead, Khalti uses a randomized queue (like a priority queue with random priorities) to:
- Assign each payment a random "priority" (e.g., timestamp + random salt).
- Process payments in order of priority. Result: No single user can monopolize the queue, and the system remains on average.
4. Exam Tips
Recurrence Relations
- Master Theorem: Always check which case applies. If is polynomial, compare exponents to .
- Recursion Trees: Draw them for problems like . The tree’s shape reveals the solution (e.g., for balanced splits).
- Substitution: Start with a guess based on the recursion tree. Verify via induction.
Randomized Algorithms
- Miller-Rabin: Know the steps for writing and the loop for checking .
- Quicksort: The key insight is that random pivots make worst-case splits unlikely, not impossible.
- Monte Carlo vs. Las Vegas: Remember that Monte Carlo can lie, but Las Vegas never does—it just might take longer.
Common Pitfalls
- Assuming Case 1/2/3 without verification: Always compute and compare .
- Ignoring base cases: Recurrences like need to solve to .
- Overlooking randomization: In quicksort, the pivot must be truly random (not just "first element") to avoid worst-case behavior.
Worked Exam Questions
Q1: Solve using the Master Theorem. Solution:
- , , so .
- for .
- Case 3 applies: .
Q2: Explain why randomized quicksort has expected time. Solution:
- The probability of a pivot splitting the array into sizes and is .
- The expected number of comparisons is:
- Solving this recurrence gives .
Visual Summary
In the real world
Google’s PageRank Algorithm: Uses randomized sampling to model the web as a Markov chain, where each page’s rank is computed by probabilistically following hyperlinks. This ensures efficient computation of global importance without exhaustive traversal.
Ncell’s Call Routing: Employs randomized load balancing to distribute incoming calls across servers. By randomly selecting a server for each call, the system avoids worst-case congestion, achieving an expected O(n log n) efficiency in routing decisions.
WhatsApp’s End-to-End Encryption: Relies on probabilistic primality testing (Miller-Rabin) to generate large prime numbers for key exchange. This ensures secure communication while maintaining computational efficiency.
Based on the TU BSc CSIT syllabus for Design and Analysis of Algorithms (CSC314), unit 10.
Discussion
Loading…