Level 5 — MasteryAlgorithm Paradigms

Algorithm Paradigms

90 minutes60 marksprintable — key stays hidden on paper

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 nn activities, activity ii has start time sis_i and finish time fif_i (with si<fis_i < f_i), 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 O(nlogn)O(n \log n). 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 (fisi)\sum (f_i - s_i) 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 nn delivery cells indexed 1..n1..n. Cell ii has an integer reward rir_i (possibly negative). The courier may collect cell ii's reward only if it does not collect cell i1i-1's reward (no two adjacent cells). Let M(n)M(n) be the maximum total reward obtainable.

(a) Write the recurrence for M(i)M(i) with base cases, and explain the optimal substructure and overlapping subproblems properties as they apply here. (6)

(b) Give an O(n)O(n) tabulation algorithm and reduce its space to O(1)O(1). State and justify both time and space complexities. (5)

(c) For the reward array r=[3,2,7,10,1,8]r = [3,\,2,\,7,\,10,\,-1,\,8], compute M(6)M(6) 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 ii. (6)


Question 3 — Bit manipulation meets probability (18 marks)

(a) The classic XOR trick: an array of length 2k+12k+1 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 (aa=0a \oplus a = 0, a0=aa \oplus 0 = a, commutativity, associativity). (6)

(b) Give an expression using only bitwise operators that isolates the lowest set bit of an integer x>0x>0, and prove it is correct by reasoning about the binary representation of xx and x-x (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 12\ge \tfrac12 (and never errs on primes). If we run tt 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 tt, and find the smallest tt guaranteeing error probability 103\le 10^{-3}. 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 \ge 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 O(nlogn)O(n\log n); the single linear scan is O(n)O(n), so total O(nlogn)O(n\log n). (1)

(b) (9 marks) Greedy-choice lemma: Let a1a_1 be the activity with the earliest finish time. Then there exists an optimal solution that includes a1a_1. (1)

Proof by exchange: Let OO be any optimal solution, ordered by finish time, with first activity aja_j. If aj=a1a_j = a_1 done. Otherwise since a1a_1 has the minimum finish time, fa1fajf_{a_1} \le f_{a_j}. (2) Form O=(O{aj}){a1}O' = (O \setminus \{a_j\}) \cup \{a_1\}. Feasibility: a1a_1 finishes no later than aja_j, and every other activity in OO started after fajfa1f_{a_j} \ge f_{a_1}, so no new overlap is created — OO' is a valid non-overlapping set. (3) Cardinality: O=O|O'| = |O|, so OO' is also optimal and contains a1a_1. (1) Induction: Having fixed a1a_1, the remaining problem is activity selection on activities that start after fa1f_{a_1} — the same problem on a smaller set. By induction the greedy choices on the subproblem are optimal, and combined with a1a_1 give a globally optimal set. Hence greedy is optimal. (2)

(c) (6 marks) Counter-example (durations objective): three activities A=[0,5]A=[0,5] (duration 5), B=[1,2]B=[1,2] (1), C=[2,3]C=[2,3] (1). (2) Earliest-finish-first picks BB then CC (finishes 2, then 3), total duration 1+1=21+1 = 2; it cannot then add AA (overlaps). (2) But choosing {A}\{A\} alone gives duration 5>25 > 2. 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): M(i)=max(M(i1),  M(i2)+ri)M(i) = \max\big(M(i-1),\; M(i-2) + r_i\big) Base cases: M(0)=0M(0)=0, M(1)=max(0,r1)M(1)=\max(0, r_1). (Allowing to skip negative rewards.) (3) Optimal substructure: an optimal choice for cells 1..i1..i either excludes ii (reduces to optimal on 1..i11..i-1) or includes ii (then i1i-1 excluded, reduces to optimal on 1..i21..i-2); the overall optimum is built from optima of these subproblems. (2) Overlapping subproblems: a naive recursion recomputes M(i2)M(i-2) inside both M(i1)M(i-1) and M(i)M(i), 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 O(n)O(n): one pass, O(1)O(1) work per cell. (2) Space O(1)O(1): only two rolling variables kept instead of the full M[]M[\cdot] table, because M(i)M(i) depends only on the two previous values. (3)

(c) (5 marks) r=[3,2,7,10,1,8]r = [3,2,7,10,-1,8] (1-indexed).

  • M(0)=0M(0)=0
  • M(1)=max(0,3)=3M(1)=\max(0,3)=3
  • M(2)=max(M(1),M(0)+2)=max(3,2)=3M(2)=\max(M(1),\,M(0)+2)=\max(3,2)=3
  • M(3)=max(M(2),M(1)+7)=max(3,10)=10M(3)=\max(M(2),\,M(1)+7)=\max(3,10)=10
  • M(4)=max(M(3),M(2)+10)=max(10,13)=13M(4)=\max(M(3),\,M(2)+10)=\max(10,13)=13
  • M(5)=max(M(4),M(3)1)=max(13,9)=13M(5)=\max(M(4),\,M(3)-1)=\max(13,9)=13
  • M(6)=max(M(5),M(4)+8)=max(13,21)=21M(6)=\max(M(5),\,M(4)+8)=\max(13,21)=\mathbf{21}

M(6)=21M(6)=21. (4) Selected cells: indices 1, 3, 6 → rewards 3+10+8=213+10+8 = 21 (non-adjacent). (1)

(d) (6 marks) Induction on ii. Base: M(0)=0M(0)=0 and M(1)=max(0,r1)M(1)=\max(0,r_1) are optimal by inspection (empty vs single). (1) Hypothesis: M(k)M(k) is optimal for all k<ik<i. (1) Step: Consider any optimal selection SS over 1..i1..i. Case 1: iSi\notin S. Then SS is a valid selection over 1..i11..i-1, so its value M(i1)\le M(i-1). (1) Case 2: iSi\in S. Then i1Si-1\notin S (adjacency), so S{i}S\setminus\{i\} is a valid selection over 1..i21..i-2 with value M(i2)\le M(i-2); hence val(S)M(i2)+ri\text{val}(S) \le M(i-2)+r_i. (2) Thus every optimal SS has value max(M(i1),M(i2)+ri)\le \max(M(i-1), M(i-2)+r_i), and both branches are achievable, so equality holds: M(i)=max(M(i1),M(i2)+ri)M(i)=\max(M(i-1),M(i-2)+r_i). (1)


Question 3

(a) (6 marks) Let the multiset be values where each of {v1,,vk}\{v_1,\dots,v_k\} appears twice and uu appears once. XOR is commutative and associative, so we may reorder freely. (2) Group the pairs: each pair contributes vjvj=0v_j \oplus v_j = 0. (2) Total =(v1v1)(vkvk)u=00u= (v_1\oplus v_1)\oplus\dots\oplus(v_k\oplus v_k)\oplus u = 0\oplus 0 \oplus\dots\oplus u. Using a0=aa\oplus 0 = a repeatedly, the result is uu. Hence the XOR of all elements equals the unique value. (2)

(b) (6 marks) Expression: x & (-x) (equivalently x & (~x + 1)). (2) Proof: Write xx in binary; let its lowest set bit be at position pp, so x=A10px = A\,1\,0^{p} where 0p0^p are pp trailing zeros and AA is the higher bits. In two's complement x=x+1-x = \sim x + 1. Complementing flips all bits; adding 1 propagates a carry through the trailing zeros of xx (which are ones in x\sim x) up to position pp. (2) Result: below position pp, both xx and x-x have zeros; at position pp both have a 1; above position pp, the bits of x-x are the complement of xx's. ANDing: positions <p<p give 0, position pp gives 11, positions >p>p give AiAi=0A_i \wedge \overline{A_i} = 0. So x & -x =2p= 2^p, exactly the lowest set bit. (2)

(c) (6 marks) Each trial errs (says "prime" for a composite) with probability 12\le \tfrac12; trials independent. All tt trials wrong ⇒ wrong final answer, so P(error)(12)t=2t.P(\text{error}) \le \left(\tfrac12\right)^t = 2^{-t}. (2) Require 2t103tlog21000=3log2109.9662^{-t} \le 10^{-3} \Rightarrow t \ge \log_2 1000 = 3\log_2 10 \approx 9.966, so smallest integer t=10t = \mathbf{10}. (Check: 210=1/1024<1032^{-10}=1/1024 < 10^{-3}; 29=1/512>1032^{-9}=1/512 > 10^{-3}.) (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)"}
]