Algorithm Paradigms
Level 5 — Mastery (cross-domain: math + coding + proof) Time limit: 90 minutes Total marks: 60
Instructions: Answer all three questions. Show all reasoning. Pseudocode or Python is acceptable; asymptotic claims must be justified. Proofs must be rigorous.
Question 1 — Greedy correctness & the exchange argument (20 marks)
Consider the Activity Selection Problem: given activities, activity has start time and finish time (with ), select a maximum-size subset of mutually non-overlapping activities.
(a) State the greedy strategy (which activity to pick first) and give clean pseudocode running in . Justify the time complexity. (5)
(b) Prove, using a formal exchange argument, that the "earliest finish time first" greedy always produces an optimal solution. Your proof must state the greedy-choice lemma precisely and show why exchanging preserves feasibility and does not decrease cardinality. (9)
(c) Now change the objective: maximize the total duration of selected non-overlapping activities. Show by explicit counter-example (give concrete numbers) that "earliest finish first" is no longer optimal, and name the algorithmic paradigm that does solve this variant optimally. (6)
Question 2 — DP design, recurrence & complexity (22 marks)
A courier must travel across a line of delivery cells indexed . Cell has an integer reward (possibly negative). The courier may collect cell 's reward only if it does not collect cell 's reward (no two adjacent cells). Let be the maximum total reward obtainable.
(a) Write the recurrence for with base cases, and explain the optimal substructure and overlapping subproblems properties as they apply here. (6)
(b) Give an tabulation algorithm and reduce its space to . State and justify both time and space complexities. (5)
(c) For the reward array , compute by filling the DP table. Show every intermediate value and state which cells are selected. (5)
(d) Prove the recurrence's correctness by induction on . (6)
Question 3 — Bit manipulation meets probability (18 marks)
(a) The classic XOR trick: an array of length contains every integer of some set exactly twice, except one value that appears once. Prove that XOR-ing all elements yields exactly the unique value. Your proof must use the algebraic properties of XOR (, , commutativity, associativity). (6)
(b) Give an expression using only bitwise operators that isolates the lowest set bit of an integer , and prove it is correct by reasoning about the binary representation of and (two's complement). (6)
(c) A Monte Carlo primality-style estimator repeatedly draws a random "witness"; each independent trial correctly reports "composite" for a composite input with probability (and never errs on primes). If we run independent trials and declare "prime" only when all trials say "prime", express the probability of a wrong answer on a composite input as a function of , and find the smallest guaranteeing error probability . Contrast this error profile with a Las Vegas algorithm. (6)
Answer keyMark scheme & solutions
Question 1
(a) (5 marks) Greedy strategy: sort activities by finish time ascending; repeatedly pick the next activity whose start time finish time of the last chosen activity. (2)
sort activities by f ascending # O(n log n)
last_finish = -inf ; count = 0
for (s, f) in activities: # O(n)
if s >= last_finish:
select it; count += 1
last_finish = f
return count
(2) Complexity: sorting dominates at ; the single linear scan is , so total . (1)
(b) (9 marks) Greedy-choice lemma: Let be the activity with the earliest finish time. Then there exists an optimal solution that includes . (1)
Proof by exchange: Let be any optimal solution, ordered by finish time, with first activity . If done. Otherwise since has the minimum finish time, . (2) Form . Feasibility: finishes no later than , and every other activity in started after , so no new overlap is created — is a valid non-overlapping set. (3) Cardinality: , so is also optimal and contains . (1) Induction: Having fixed , the remaining problem is activity selection on activities that start after — the same problem on a smaller set. By induction the greedy choices on the subproblem are optimal, and combined with give a globally optimal set. Hence greedy is optimal. (2)
(c) (6 marks) Counter-example (durations objective): three activities (duration 5), (1), (1). (2) Earliest-finish-first picks then (finishes 2, then 3), total duration ; it cannot then add (overlaps). (2) But choosing alone gives duration . So earliest-finish is not optimal for the weighted/duration objective. (1) The paradigm that solves weighted interval scheduling optimally is Dynamic Programming (sort by finish, DP with binary search for last compatible interval). (1)
Question 2
(a) (6 marks) Recurrence (house-robber form): Base cases: , . (Allowing to skip negative rewards.) (3) Optimal substructure: an optimal choice for cells either excludes (reduces to optimal on ) or includes (then excluded, reduces to optimal on ); the overall optimum is built from optima of these subproblems. (2) Overlapping subproblems: a naive recursion recomputes inside both and , so the same subproblems recur exponentially often — motivating memoization/tabulation. (1)
(b) (5 marks)
prev2 = 0 # M(0)
prev1 = max(0, r[1]) # M(1)
for i in 2..n:
cur = max(prev1, prev2 + r[i])
prev2 = prev1 ; prev1 = cur
return prev1
Time : one pass, work per cell. (2) Space : only two rolling variables kept instead of the full table, because depends only on the two previous values. (3)
(c) (5 marks) (1-indexed).
. (4) Selected cells: indices 1, 3, 6 → rewards (non-adjacent). (1)
(d) (6 marks) Induction on . Base: and are optimal by inspection (empty vs single). (1) Hypothesis: is optimal for all . (1) Step: Consider any optimal selection over . Case 1: . Then is a valid selection over , so its value . (1) Case 2: . Then (adjacency), so is a valid selection over with value ; hence . (2) Thus every optimal has value , and both branches are achievable, so equality holds: . (1)
Question 3
(a) (6 marks) Let the multiset be values where each of appears twice and appears once. XOR is commutative and associative, so we may reorder freely. (2) Group the pairs: each pair contributes . (2) Total . Using repeatedly, the result is . Hence the XOR of all elements equals the unique value. (2)
(b) (6 marks)
Expression: x & (-x) (equivalently x & (~x + 1)). (2)
Proof: Write in binary; let its lowest set bit be at position , so where are trailing zeros and is the higher bits. In two's complement . Complementing flips all bits; adding 1 propagates a carry through the trailing zeros of (which are ones in ) up to position . (2)
Result: below position , both and have zeros; at position both have a 1; above position , the bits of are the complement of 's. ANDing: positions give 0, position gives , positions give . So x & -x , exactly the lowest set bit. (2)
(c) (6 marks) Each trial errs (says "prime" for a composite) with probability ; trials independent. All trials wrong ⇒ wrong final answer, so (2) Require , so smallest integer . (Check: ; .) (2) Contrast: This is Monte Carlo — fixed/bounded running time but a small probability of an incorrect answer (one-sided error here). A Las Vegas algorithm is always correct; its randomness affects only the running time, which becomes a random variable (e.g., expected-time bound). Trade-off: Monte Carlo risks correctness for guaranteed time; Las Vegas guarantees correctness at the cost of variable time. (2)
[
{"claim":"M(6)=21 for house-robber recurrence on [3,2,7,10,-1,8]",
"code":"r=[3,2,7,10,-1,8]\nfrom sympy import Max\nM=[0, Max(0,r[0])]\nfor i in range(2,7):\n M.append(Max(M[i-1], M[i-2]+r[i-1]))\nresult = (M[6]==21)"},
{"claim":"Selected non-adjacent cells 1,3,6 give reward 21",
"code":"r=[3,2,7,10,-1,8]\nresult = (r[0]+r[2]+r[5]==21)"},
{"claim":"Smallest t with 2**-t <= 1e-3 is 10",
"code":"vals=[t for t in range(1,20) if 2**(-t)<=1e-3]\nresult = (min(vals)==10)"},
{"claim":"lowest set bit x & (-x) equals 2**p for sample x=待 e.g. 12 -> 4",
"code":"x=12\nresult = ((x & (-x))==4)"}
]