CS 6515 Final: hands-on notes

Final exam: Thu Dec 10, 2026, 2:00 PM · cumulative (Units 1–3, Lec 1–21) · goal 100/100 · 155 problems (11 tied to a ★ flagged point) · 112 recall questions · 87 figures · 19 lecture insights

0 · Start here

How this page worksEvery topic is retrieve → refresh → recall → do problems. You answer warm-up questions from memory first (fine to miss), read a short refresher, check yourself, then spend most of the time on problems with hidden solutions. Rate every problem and recall question Got it / Shaky / Missed; the Redo queue collects your Missed and Shaky items for the next day's review.
Daily loop
  1. Open the Redo queue and redo yesterday's Missed/Shaky items first (15 min).
  2. Follow today's row in the plan. Per topic: warm-up → refresher → summary card → recall check → problems (short → calc → guided → design).
  3. Write answers on paper (front of the page only, no calculator), then open the solution. Check every rubric item, not just the final answer.
  4. End of day: press ⧉ Copy my misses in the Redo queue and paste it into the chat. I add targeted drills and update PROGRESS.md.
Where things are
  • §1 Redo queue · §2 Final format · §3 Gap list (what you never got tested on) · §4 Plan
  • §5–11 Exam craft: rules + time strategy, answer frames per problem type, black-box catalogue, technique chooser, notation, short-answer track
  • §15–17 Your weak spots: every rubric deduction → mini-lesson + drills, final-check lists, 5-minute end-of-exam routine
  • §20–29 Unit 1 · §30–39 Unit 2 · §40–49 Unit 3 + Lec 20–21 · §50+ cross-unit drills and mocks
  • Locked (AI-free) mocks are not on this page: the papers are in final-notes/mocks/; tell me when you've attempted one and I'll grade it.

0.1 Build status

This page is rebuilt at every milestone. Parts marked “building…” are still being written.

PartProblemsStatus
My weak spots17✓
Exam craft & short-answer track52✓
Unit 1a · Lec 1–550✓
Unit 1b · Lec 6–836✓
Unit 2a · LP & duality0building…
Unit 2b · Convexity, GD, approximation0building…
Unit 3 · Randomized, NP, Lec 20–210building…
Cross-unit drills & mocks0building…

1 · Redo queue

Everything you rated Missed (red) or Shaky (orange), oldest first. Ratings are saved in this browser only (laptop and iPad don't sync), so press Copy my misses and paste the text into the chat to keep me in sync.

Re-rating rule When you redo an item, re-rate it. Only rate Got it when you solved it cold, on time and complete (every rubric item). That is the mastery standard; "I recognized the answer" is Shaky.

2 · The final's format (evidence so far)

▸ Collapsed: click to expand▾ Click to collapse
Not confirmed yet Nothing in the course folder describes the final itself. Until you confirm, the notes assume about 2.5–3 hours, two pages of notes, no calculator, the same rules as every midterm. Tell me the real length and notes allowance and I'll update the time budgets (§5) and the cheat sheet.
EvidenceWhat it saysSource
Exam 1, 2, 3 covers70 minutes, 100 points; “Bringing two pages of notes is permitted. No books, calculators, or other electronic devices”; “Write only on the FRONT of each sheet. Backs will not be scanned.”; may cite standard algorithms/theorems from class; “You may use a stated claim from an earlier part even if you did not prove it.”Exam 1A p1 Exam 2 p1 Exam 3 p1
Midterm layoutQ1 = 40 points of short answers (T/F, select-all, MC, small calculations; 1–2 line justification), then 2–3 long problems worth 60 points.Exams 1–3
Unit 1 practice exam“Bringing one page of notes is permitted.”Practice Exam Unit 1 p1
Official final practice set8 short answers (induction bug, augmenting paths, IS on trees vs NP-hard, LP duality, reductions, MST cut property, greedy knapsack, MDP) + long problems covering D&C, tree DP, max-flow modeling, LP formulation + duality, randomized algorithm, convex optimization: every unit appears, Unit 1 most.final-practice-problems/Fall26_CS6515_4.pdf

The detailed evidence file is final-notes/exam_format_evidence.md.

3 · Gap list: what you've never been tested on (taught in full depth)

▸ Collapsed: click to expand (3 subsections)▾ Click to collapse

These topics get the full understanding-first treatment on top of the normal refresher. The detailed list with sources is in final-notes/gap_list.md.

3.1 Unit 2 content Exam 2 didn't test

  • LP modeling from a word problem; equivalent forms (Lec 9; HW3 #10–12). The final practice set has an LP long problem.
  • LP geometry, vertices, the three outcomes; why LPs are poly-time solvable (Lec 9).
  • Writing the dual of a given LP by S-O-B and deriving it by bounding (Lec 10). Exam 2 asked only duality facts.
  • Max-flow = min-cut via LP duality: path LP, dual edge lengths, threshold rounding (Lec 10, notes p12–14).
  • Separation theorem and the strong-duality proof via Farkas (Lec 11).
  • Zero-sum games / minimax via LP duality (Lec 11; HW3 #13).
  • GD with bounded gradients (DG/√T, average iterate); strongly convex + smooth rate (1−α/β)T; HW3 strongly convex + G; non-convex stationarity (Lec 12–13; HW4 #16).
  • Greedy-degree VC is O(ln n); VC LP rounding at 1/2; VC dual = fractional matching (Lec 14–15).
  • Directed edge-disjoint paths greedy (Lec 14; connects to Lec 21).
  • Facility location (LP, Lj, Bj, 6-approximation): off Exam 2, fair game now.
  • Load balancing, metric TSP via MST doubling, Steiner tree; PTAS/FPTAS; integrality gaps.

3.2 Lec 20–21 (Lec 21 was never tested)

  • Lec 20 (Nov 12): self-reducibility (IS optimization ⇄ decision ⇄ search), 3SAT → IS, how reductions transfer algorithms and hardness.
  • Lec 21 (Nov 17): maximum directed edge-disjoint paths: the √m short-path greedy and its charging proof, the fallback, and the hardness reduction from 2-disjoint paths via the layered/triangular construction (YES/NO lemmas, size, why no m−1/2+ε-approximation). Taught in §46–47.

3.3 Your rubric weak spots

From your graded exams, raw points lost per pattern (105.5 points in total, before curves): DP write-up 15 · both directions of iff/correspondence 14 · counterexamples/tight instances 12 · using the earlier part/hint in proof chains 12 · flow/ILP/reduction formulations with named components 12 · expectation calculations 11.5 · strongest lower+upper bounds 9.5 · complementary slackness/Farkas select-all 9 · existence proof 6 · off-by-one constants 2.5 · unfinished calculation 2. Each one has a mini-lesson and drills in §15–16.

4 · The plan: Fri Dec 4 → Thu Dec 10, 2 PM

▸ Collapsed: click to expand (1 subsections)▾ Click to collapse

Assumes 3–4 h on weekdays and 5–6 h on Sat/Sun (tell me if that's off). Total 1520 min ≈ 25.3 h. Dedicated topic time: Unit 1 450 min (30%), Unit 2 210 min (14%), Unit 3 120 min (8%), plus 740 min (49%) of mixed retrieval, spaced review and timed mocks. Unit 1 gets the most because the final practice set leans on it and it was your lowest exam (raw 50.5/100).

DayBlocks (in order)
Fri Dec 4 (evening)
125 min ≈ 2.1 h
Day 0: re-learn Unit 1 first (refresher → recall → problems); no cold redos yet
  • Learn + problems 25 min: §20 Proof techniques: warm-up, read, recall check, then U1A.1–U1A.5
  • Learn + problems 35 min: §21 Asymptotics + recurrences: master theorem table, then U1A.8–U1A.14
  • Learn + problems 35 min: §22 Divide & conquer + median of medians, incl. Exam 1A Q2 (peak) redo U1A.16–17
  • Learn + problems 25 min: §23 DP part 1: recipe + contiguous sum + LCS (U1A.27–28)
  • Report to Claude 5 min: Copy my misses → paste in the chat (they seed Saturday's Redo queue)
Sat Dec 5
320 min ≈ 5.3 h
Unit 1 rest → then Exam 1 lost parts cold as a check
  • Spaced review 15 min: Redo queue: Friday's Missed/Shaky
  • Learn + problems 40 min: §23 DP part 2: Exam 1A Q3 redo (U1A.31), tree DP, balancing
  • Learn + problems 30 min: §24 Knapsack, FPTAS, MDPs (Exam 1A Q1c, Q1d redos)
  • Learn + problems 35 min: §25–26 Graph search + shortest paths (Exam 1A Q1f redo)
  • Learn + problems 25 min: §27 MST (cut/cycle property)
  • Learn + problems 25 min: §28 Matchings
  • Learn + problems 45 min: §29 Max-flow/min-cut + flow modeling (Exam 1A Q4 redo)
  • Learn + problems 30 min: §15–16 Weak spots: the Unit 1 deductions (DP, IFF, BOUNDS) + their drills
  • Retrieve 45 min: START_HERE §1, Exam 1 rows only: redo the lost parts cold, now that the material is back
  • Retrieve 15 min: START_HERE §2 quiz, Unit 1 questions only; check the key
  • Retrieve 15 min: End-of-day mixed recall: 10 recall questions from today, interleaved
Sun Dec 6
330 min ≈ 5.5 h
Unit 2 + untested-Unit-2 gaps; evening Exam 1B
  • Spaced review 15 min: Redo queue: Saturday's Missed/Shaky
  • Retrieve 10 min: START_HERE §2 quiz, Unit 2 questions only (cold, to see what's left from Exam 2)
  • Learn + problems 95 min: §30–34 LP modeling, duality (S-O-B, CS), Farkas, flow-LP, games (gap parts in full)
  • Learn + problems 50 min: §35–36 Convexity + all GD theorems + projected GD (Exam 2 Q3 redo)
  • Learn + problems 55 min: §37–39 Approximation, facility location, LP rounding (Exam 2 Q2/Q4 redo)
  • Retrieve 20 min: §11 Short-answer track: 15 T/F + select-all items (Units 1–2)
  • Timed mock 70 min: Exam 1 Section B, timed 70 min, AI-free (final-notes/mocks/)
  • Report to Claude 15 min: Paste your Exam 1B answers/score claims; I grade against the locked key
Mon Dec 7
225 min ≈ 3.8 h
Unit 3 + Lec 20–21 + technique choosing
  • Spaced review 15 min: Redo queue: Sunday's misses + Exam 1B misses
  • Learn + problems 75 min: §40–45 Unit 3 refreshers + problems (probability, Karger, prob. method, rounding, NP, reductions)
  • Learn + problems 45 min: §46–47 Lec 20 self-reduction + Lec 21 edge-disjoint paths (√m greedy, hardness): full depth
  • Learn + problems 25 min: §06 Answer frames + §09 Technique chooser drills
  • Retrieve 25 min: §11 Short-answer track: 20 mixed items, all units
  • Retrieve 25 min: Cross-unit interleaved set (§50+)
  • Retrieve 15 min: End-of-day mixed recall
Tue Dec 8
220 min ≈ 3.7 h
Official final practice set, timed and AI-free
  • Spaced review 15 min: Redo queue (warm-up only)
  • Timed mock 150 min: Final practice set (final-notes/mocks/Final_Practice_Set.pdf), timed, no AI, no notes except the cheat sheet
  • Report to Claude 10 min: Tell me you're done; I grade it against the locked solutions
  • Learn + problems 45 min: Redo every lost part; targeted drills I add for those topics
Wed Dec 9
225 min ≈ 3.8 h
Mock A + redo queue + cheat sheet; sleep
  • Spaced review 15 min: Redo queue
  • Timed mock 120 min: Mock A, timed, with the cheat sheet
  • Report to Claude 15 min: Grade Mock A with me
  • Spaced review 45 min: Redo queue: everything still Missed/Shaky
  • Cheat sheet 20 min: Read the cheat sheet once, front to back, so you know where everything is
  • Retrieve 10 min: §17 Final-check lists + 5-minute end-of-exam routine
Thu Dec 10 (morning)
75 min ≈ 1.2 h
Light warm-up only; exam 2:00 PM
  • Retrieve 30 min: Summary cards: one pass through the recall questions you rated Shaky
  • Spaced review 30 min: Redo queue only (no new material)
  • Retrieve 15 min: §05 Exam rules + time budget + §17 final checks
Cut first if you're short on time
  • Reading refreshers for topics where you got every warm-up right: go straight to the problems.
  • Extra problems on topics you've rated Got it twice.
  • Unit 3 deep-dive reading (you scored 88 on Exam 3): keep its problems, skip the long explanations.
  • The cross-unit set on Monday (the mocks interleave anyway).
Never cut
  • The 15-minute redo queue at the start of every day.
  • The final practice set, timed, on Tuesday, and grading it.
  • Weak-spot drills: DP frame, both directions, both bounds, counterexamples.
  • The short-answer track (your biggest loss: Exam 1 Q1 26.5/40, Exam 2 Q1 25/40).
  • Sleep on Wednesday night. No all-nighter.

4.1 Why study this way

TechniqueEvidenceHow the notes use it
Retrieval practice (testing yourself)Rated “high utility” in Dunlosky et al. (2013); the testing effect beats re-reading for delayed retention (Roediger & Karpicke, 2006).Warm-ups before every refresher, recall checks after, problems with hidden solutions.
Spaced (distributed) practiceAlso “high utility” in Dunlosky et al. (2013); meta-analysis by Cepeda et al. (2006).Redo queue each morning; misses resurface on later days.
Interleaving problem typesMixing problem types improves the ability to choose the right method (Rohrer & Taylor, 2007); “moderate utility” in Dunlosky et al.Mixed end-of-day recall, technique chooser, cross-unit sets, mocks.
Worked example → problemWorked examples help when knowledge is rusty (worked-example effect, Sweller and colleagues); fade into independent problems.Each refresher has one fully worked example, then you solve.
Timed exam-format practicePracticing under test conditions transfers to the test format (transfer-appropriate processing).Exam 1B (Sun), final practice set (Tue), Mock A (Wed), all timed and AI-free.
SleepSleep after learning supports memory consolidation; all-nighters hurt recall and reasoning.Wednesday ends early; Thursday morning is light review only.

5 · Exam clock and the two-pass method exam craft · calibrated on your three midterms (70 min / 100 pts each)

▸ Collapsed: click to expand (1 subsections)▾ Click to collapse
The idea in one sentencePoints come from finished, framed answers, so budget minutes by points, write every part's frame first, and never let one part eat another part's time. Your two biggest losses (E1 Q3b 10 pts, Q4c 8 pts) were blank because time ran out.

The final's length isn't known yet (see §2). The midterms ran at 0.7 min per point: a 5-point short answer got 3.5 min, a 20-point problem 14 min. Keep 10 min out of the budget (3 to read the paper, 7 to check at the end), then divide what's left by the points.

Exam lengthPointsmin / point5-pt short40-pt short block20-pt long30-pt long
120 min1001.15.5442233
150 min1001.47562842
150 min1500.934.7371928
170 min1001.68643248
180 min1501.135.7452334

All times in minutes; 10 min reserved in every row.

Q1 short answers (40 pts)59long A (20)87long B (20)115long C (20)1431500scan 3check 7Example: 150 minutes, 100 points, 10 minutes reserved ⇒ 1.4 min per pointPass 1 inside every long problem: write the frame for every part (headers, (⇒)/(⇐), DP lines)Pass 2: fill in. Stuck past 1.5 × budget? Mark it, move on, come back after the last problem.
Exam clock for one plausible final format (the real length is unknown: recompute with the cover's numbers).
How to read this figure One plausible format drawn to scale: each bar is a block of the paper, its width the minutes it gets, and the numbers under the bars are the clock times at which you should be moving on. The two lines underneath are the method that keeps a long problem from swallowing the next one.

5.1 The two-pass method

  1. Read (3 min). Read every question once. Write the minute you must leave each one in the margin. Note which parts are "prove the earlier claim" vs "use it".
  2. Short answers first, in order, at the budget. A T/F you can't settle in budget: write your best guess plus one line of reasoning (partial credit exists for the justification), circle it, move on.
  3. Pass 1 in each long problem: frames for all parts. Write the headers you'll need: the 6 DP lines, (⇒) and (⇐), "Vertices / Edges / Capacities / Read-off", "Target: … Given facts to use: …". Frames alone earn rubric points (E1 Q3a gave 3 of 6 for a partial state).
  4. Pass 2: fill in the frames, easiest part first. Earlier parts you can't prove can still be used in later parts: say "by part (a)".
  5. 1.5× rule. At 1.5 times a part's budget, stop, write one line of what you'd do next, and move on. Come back after the last problem.
  6. Check (7 min) with the list in §10: both bounds, both directions, k vs k+1, every constraint, final answers bold.
Your clock failures
  • Exam 1: Q3b (10) and Q4c (8) blank, Q3c (2) rushed: 20 points lost to time with Q1 done first and slowly.
  • Exam 2 Q4.4 (5) blank: the tight-instance part came last; it needed 3 minutes.
Recall check
A 150-minute, 100-point final: how long for a 20-point long problem?
(150 − 10)/100 = 1.4 min per point, so 28 minutes.
What do you write in pass 1 of a "prove the reduction is correct" part?
The two headers (⇒) and (⇐), each with "Given: … Build: … Check: same size/value". Then fill in.

6 · Answer frames and the black-box catalogue exam craft · one frame per long-question type, built from the official rubrics

▸ Collapsed: click to expand (2 subsections)▾ Click to collapse
The idea in one sentenceEvery long question on the midterms was graded against a fixed list of components, so write the components as headers first and fill them in: a frame turns "I know this" into the rubric's points.

6.1 The frames

Question typeFrame: the headers to write firstWhere you lost points
DP1 State in words (prefix, limit) · 2 Ranges · 3 Every base case · 4 Recurrence by cases on the last decision + why each case is right · 5 Fill order · 6 Answer cell, time, spaceE1 Q3: 15 pts (empty recurrence, base cases, answer cell, order)
Divide & conquerAlgorithm (base case, split, which half/parts recurse, combine) · Invariant the recursion keeps · Correctness (why the kept part still contains an answer) · Recurrence T(n) = … · Solve it (master theorem, show a, b, d)E1 Q2: existence argument, m vs m+1
Flow modelVertices (named in the problem's words) · Edges with capacities + a reason each · s, t · Algorithm and runtime · Read-off rule · (⇒) solution → flow, same value · (⇐) integral flow → solution, same valueE1 Q4b–c: 14 pts
LP / ILP formulationVariables with meaning · Objective · Every constraint family ("for every element e: …") · Integrality / bounds · Why a feasible solution ↔ a valid choiceE2 Q4.1: 4 pts (only the objective)
DualPrimal in standard form · One dual variable per primal constraint, sign from S-O-B · One dual constraint per primal variable · Objective · Weak duality one-liner(drilled in Unit 2, §30–34)
Proof chain (GD, approximation analysis)Target written out · Given facts to use: hint, earlier parts, definitions (smoothness, convexity) · Chain of numbered inequalities, each with its reason · Count terms (k vs k+1)E2 Q3b–c, Q4.3: 12 pts
Approximation algorithmAlgorithm · Feasibility · Lower bound on OPT (min) / upper bound (max) · ALG ≤ c·(that bound) · Runtime · Tight instance if asked (a family in n, k or Δ)E2 Q2b–c, Q4.4: 8.5 pts
RandomizedRandom variable defined · Indicators + linearity → E[·] as a number · Markov / boosting with independence stated · Derandomization: how each conditional expectation is computedE1 Q1d, E3 Q1f, Q2c: 11.5 pts
NP-hardness reductionDirection: known hard A ≤p new X · Construction (every part of the instance: U, sets, k′) · Polynomial size/time · (⇒) yes-instance of A → yes-instance of X · (⇐) yes-instance of X → yes-instance of A · X ∈ NP if "complete"E3 Q3: 8 pts
ExistenceExtremal choice (max, min, longest, first/last) · Check every neighbour/boundary case · ConcludeE1 Q2a: 6 pts
T/FVerdict · True: the one-line reason (theorem name + why it applies) · False: the smallest counterexample with numbers before/afterE1 Q1f, E2 Q1b: 10 pts
Strongest boundsLower = … because … · Upper = … because … · Compare with any extra fact and keep the stronger · Integrality roundingE1 Q1c, E2 Q1f: 9 pts
Traps
  • A frame left with an empty slot still loses that slot's points: tick every header before moving on.
  • "Similarly" for the second direction of an iff earns nothing: write it out.

6.2 Black-box catalogue: what you may cite without proof

"You may refer to standard algorithms from class" (cover of every paper). Cite by name with input, output and runtime; don't re-prove.

Black boxInput → outputRuntime / guarantee
Merge sortarray → sortedO(n log n)
Median of medians (select)array, k → k-th smallestO(n) worst case
Karatsuba / Strassenn-bit numbers / n×n matrices → productO(nlog₂3) / O(nlog₂7)
BFS / DFSgraph, s → distances in edges / reachability, components, topological order (DAG)O(n + m)
Dijkstragraph, w ≥ 0, s → shortest distances + treeO((n + m) log n)
Kruskal / Primconnected weighted undirected graph → MSTO(m log n)
Bipartite matching (augmenting paths)bipartite graph → maximum matchingO(n(n + m))
Ford–Fulkerson / Edmonds–Karpnetwork, integer capacities → integral max flow + min cutO(m·|f*|) / O(nm²)
0/1 knapsack DPn items, capacity B → optimumO(nB) (pseudo-polynomial); value-indexed O(n·Σv)
Knapsack FPTASitems, ε → ≥ (1 − ε)OPTO(n³/ε)
LP solverLP → optimal vertex, or infeasible / unboundedpolynomial time
(Projected) gradient descentconvex f (, convex K) → ε-approximate minimizerrates in Unit 2 (DG/√T, βD²/2T, (1 − α/β)T)
VC via maximal matchinggraph → vertex cover2-approx, O(n + m)
VC LP rounding (x ≥ ½)weighted graph → vertex cover2-approx
Set cover rounding (x ≥ 1/f)elements in ≤ f sets → coverf-approx
Karger contractionmultigraph → a min cut≥ 2/(n(n−1)) per run; boost by repetition
Random assignment for MAX-SATformula → assignmentE ≥ (1 − 2−k)m for clauses of size ≥ k
2-SAT2-CNF → satisfying assignment or "no"O(n + m) (implication graph + SCC)
Known NP-completeSAT, 3SAT, Independent Set, Clique, Vertex Cover, Set Cover, Subset Sum / Knapsack (decision), 2 directed disjoint pathsreduce from these
Traps
  • Citing a black box on an input it doesn't accept: Dijkstra with negative edges; MST on a directed graph; FF's integrality with fractional capacities.
  • Citing "FF is polynomial": it's pseudo-polynomial; say Edmonds–Karp if you need polynomial.
Recall check
The six lines of the DP frame?
State in words · ranges · base cases · recurrence with case justification · fill order · answer cell + time/space.
The seven headers of a flow model?
Vertices · edges + capacities (with reasons) · s, t · algorithm + runtime · read-off · (⇒) · (⇐).
In an NP-hardness proof, which way does the reduction go?
From the known NP-hard problem to the new one: A ≤p X.

7 · Hand-arithmetic drills exam craft · no calculator on the final · EC.1–12

▸ Collapsed: click to expand▾ Click to collapse
The idea in one sentenceThe numeric parts of Unit 2–3 questions (a GD step, a projection, an iteration count, an expectation, a bound on OPT) are short but unforgiving: one sign or count error loses the part, so practise them until they're mechanical.
Warm-up: try from memory first
ln 2, ln 10, ln 100, e−1, e−2 to two digits?
0.69, 2.30, 4.61, 0.37, 0.14.
The inequality that turns (1 − p)k into something you can solve for k?
1 − p ≤ e−p, so (1 − p)k ≤ e−pk; then e−pk ≤ δ ⇔ k ≥ ln(1/δ)/p.
Mechanical rules
  • GD step: xt+1 = xt − η∇f(xt) (minus!). β = largest second derivative / Hessian eigenvalue, α = smallest.
  • Projection onto a half-plane aᵀx ≤ b: if violated, subtract ((aᵀy − b)/‖a‖²)·a. Onto a box: clip each coordinate. Then check every other constraint.
  • Iteration counts: bounded gradient T ≥ (DG/ε)²; smooth T ≥ βD²/(2ε); strongly convex T ≥ (β/α)ln(gap₀/ε). Round up.
  • Expectations: Σ prob × value; indicators + linearity; Geometric(p) has mean 1/p (counting the success).
  • Bounds on OPT: feasibility gives one side, the guarantee the other, extra facts (LP, matching, dual) may tighten; integer objective ⇒ round inward.
Minimization (ALG ≤ c·OPT): lower bounds come from the guarantee, LP, dual; upper bound = ALGdual value⌈LP*⌉ALG / cALGOPT lies in [max(ALG/c, ⌈LP*⌉, dual), ALG]Maximization (ALG ≥ OPT/c): lower bound = ALG; upper bounds from the guarantee, LP, dualALGOPT ≤ c·ALG⌊LP*⌋dual valueOPT lies in [ALG, min(c·ALG, ⌊LP*⌋, dual)]
Strongest bounds on OPT: take the largest lower bound and the smallest upper bound; the shaded band is OPT's range when the guarantee is the binding fact (positions schematic).
How to read this figure Each axis is the number line of possible OPT values. The shaded band is where OPT can be. For a minimization problem the algorithm's value is always an upper bound and every lower bound (guarantee, LP, dual) pushes the left end; for maximization the roles flip. The strongest answer is the narrowest band.
✍ EC.1Three GD steps by hand, and reading off α, β New drillcalculation
Source: New drill written for these notes
f(x₁, x₂) = (x₁ − 1)² + 2x₂². Start at x₀ = (3, 1) and run unconstrained gradient descent with η = 1/4.
  1. Compute ∇f(x₀), x₁, x₂, x₃.
  2. Give the smoothness β and strong-convexity α of f.
  3. Check the descent lemma at η = 1/β: is f(x₁) ≤ f(x₀) − ‖∇f(x₀)‖²/(2β)?
Show solution
  1. ∇f(x) = (2(x₁ − 1), 4x₂), so ∇f(x₀) = (4, 4). x₁ = (3, 1) − ¼(4, 4) = (2, 0). ∇f(x₁) = (2, 0), so x₂ = (2, 0) − ¼(2, 0) = (3/2, 0). ∇f(x₂) = (1, 0), so x₃ = (5/4, 0).
  2. The Hessian is diag(2, 4) at every point. β = largest eigenvalue = 4, α = smallest = 2. So η = 1/4 is exactly the safe step 1/β.
  3. f(x₀) = 6, ‖∇f(x₀)‖² = 32, so the right side is 6 − 32/8 = 2. f(x₁) = 1 ≤ 2: yes. The x₂-coordinate hit 0 in one step because η = 1/4 is exactly 1/(its curvature 4).
Rubric: what earns the points
  • gradient formula
  • each iterate computed with x − η∇f
  • β and α from the Hessian eigenvalues
  • descent-lemma inequality checked numerically
Where partial credit is lost
  • Subtracting η·∇f with the wrong sign (Exam 2 rubric: “Improper gradient descent” cost 3 of 10).
  • Reading β off the coefficient (2) instead of the second derivative (4).
✍ EC.2One projected GD step onto a triangle New drillcalculation
Source: New drill written for these notes
Minimize f(x) = ½‖x − (5, 3)‖² over K = {x ∈ ℝ² : x₁, x₂ ≥ 0, x₁ + x₂ ≤ 2}. From x₀ = (1, 1) take one projected GD step with η = 1/2.
Show solution

∇f(x) = x − (5, 3), so ∇f(x₀) = (−4, −2). Unprojected point y = x₀ − ½(−4, −2) = (3, 2). It violates x₁ + x₂ ≤ 2 (3 + 2 = 5).

Project onto the line x₁ + x₂ = 2 along its normal (1, 1): subtract ((5 − 2)/2)(1, 1) = (3/2, 3/2), giving (3/2, 1/2). Both coordinates are ≥ 0, so this is also the closest point of K: x₁ = (3/2, 1/2) (brute-force checked on a grid in calc_ec.py).

Rubric: what earns the points
  • gradient at x₀
  • unprojected point
  • notice infeasibility
  • Euclidean projection with the normal direction
  • check every constraint at the final point
Where partial credit is lost
  • Stopping at the unprojected point (Exam 2 Q1d rubric: “Failing to project” −2).
  • Projecting by clipping each coordinate separately: that is the projection onto a box, not onto x₁ + x₂ ≤ 2.
  • Forgetting to check the projected point against the other constraints (x ≥ 0).
✍ EC.3Iteration counts for the three main GD theorems New drillcalculation
Source: New drill written for these notes
How many steps T suffice for additive error ε in each case? (No calculator: ln 1000 ≈ 6.91.)
  1. f convex, ‖∇f‖ ≤ G = 5, ‖x₀ − x*‖ ≤ D = 4, ε = 1/2, η = D/(G√T), average iterate.
  2. f convex and β-smooth with β = 6, D = 2, ε = 1/10, η = 1/β, last iterate.
  3. f α-strongly convex and β-smooth with α = 2, β = 8, f(x₀) − f* = 50, ε = 1/20, η = 1/β.
Show solution
  1. DG/√T ≤ ε ⇔ T ≥ (DG/ε)² = (20/(1/2))² = 1600.
  2. βD²/(2T) ≤ ε ⇔ T ≥ βD²/(2ε) = 6·4/(2/10) = 120.
  3. (1 − α/β)^T·50 ≤ e^{−Tα/β}·50 ≤ ε ⇔ T ≥ (β/α)·ln(50/ε) = 4·ln 1000 ≈ 4·6.91 = 27.63, so T = 28.

Order of magnitude: 1/ε² vs 1/ε vs log(1/ε). That ordering is itself a classic short-answer question.

Rubric: what earns the points
  • name the theorem and check its hypotheses
  • set bound ≤ ε and solve for T
  • round up
  • say which iterate the bound is for
Where partial credit is lost
  • Using the smooth bound βD²/(2T) for a function that is only G-bounded (wrong theorem: check hypotheses first).
  • Forgetting to round T up to an integer.
  • Using 1 − α/β without converting to e^{−α/β} when a log is needed.
✍ EC.4Step size and error for the bounded-gradient theorem New drillcalculation
Source: New drill written for these notes
f convex, ‖∇f‖ ≤ G = 2, ‖x₀ − x*‖ ≤ D = 3. You will run T = 400 steps with a constant step size. Give the step size the theorem prescribes and the guaranteed error. For which point is the guarantee?
Show solution

η = D/(G√T) = 3/(2·20) = 3/40. Error f(x̄) − f* ≤ DG/√T = 6/20 = 3/10.

The guarantee is for the average x̄ = (1/T)Σ_{t<T} x_t (or the best iterate seen), not the last iterate. Source: Part 2 typed notes p32 (Lec 12).

Rubric: what earns the points
  • η formula
  • error formula
  • average (or best) iterate stated
Where partial credit is lost
  • Claiming the bound for the last iterate (a T/F favourite).
  • √400 = 20, not 200.
✍ EC.5Markov in both directions, and Las Vegas → Monte Carlo New drillcalculation
Source: New drill written for these notes
(a) X ≥ 0 with E[X] = 5. Bound Pr[X ≥ 20] and Pr[X < 20]. What does Markov say about Pr[X ≥ 4]? (b) A Las Vegas algorithm has expected running time n². Turn it into a Monte Carlo algorithm that runs at most c·n² steps and fails with probability ≤ 1/4. What c?
Show solution

(a) Pr[X ≥ 20] ≤ 5/20 = 1/4; hence Pr[X < 20] ≥ 3/4. For a = 4 the bound is 5/4 ≥ 1: nothing (Markov is useless at or below the mean).

(b) Stop after c·n² steps and output “fail”. Fail ⇔ running time T ≥ c·n², and Markov gives Pr[T ≥ c·n²] ≤ n²/(c·n²) = 1/c. So c = 4.

Rubric: what earns the points
  • Markov stated with X ≥ 0
  • complement for the lower side
  • useless case recognised
  • LV→MC: failure event = time exceeds the cap
Where partial credit is lost
  • Applying Markov to a variable that can be negative.
  • Writing Pr[X ≥ 4] ≤ 5/4 as if it were informative.
✍ EC.6Two-step MDP: expected value of each first action New drillcalculation
Source: New drill written for these notes
Horizon T = 2, start state s. At s: action a pays 1 and moves to u with probability 1/3, to v with probability 2/3; action b pays 1 and moves to v with probability 1. At u: action c pays 6, action d pays 2. At v: c pays 1, d pays 3. Give the optimal policy and the expected total reward of each first action.
Show solution

Step 1 (one step left, t = 1): V(u, 1) = max(6, 2) = 6 (choose c); V(v, 1) = max(1, 3) = 3 (choose d).

Step 2 (two steps left): Q(s, a) = 1 + (1/3)·6 + (2/3)·3 = 5. Q(s, b) = 1 + 1·3 = 4.

Policy: a at s; then c at u and d at v. Optimal expected reward 5. Both actions pay 1 now: only the look-ahead separates them.

Rubric: what earns the points
  • V(·, 1) at every reachable state
  • Q for each first action as Σ prob × value
  • full policy (first action and second-step choices)
  • optimal value
Where partial credit is lost
  • Exam 1 Q1d rubric: policy 3 pts, expectation for action a 1.5, for action b 1.5. Give both expectations, not only the winner.
  • Forgetting the second-step choice at each state (a policy says what to do at u and at v).
✍ EC.7Geometric: expected draws until the first success New drillcalculation
Source: New drill written for these notes
A box has 30 tickets, 6 of them winning. You draw uniformly with replacement until you get a winner. Expected number of draws? Probability you need more than 3 draws?
Show solution

Each draw wins with p = 6/30 = 1/5, independently, so the number of draws is Geometric(p): E = 1/p = 5.

More than 3 draws ⇔ the first three all lose: (4/5)³ = 64/125.

Rubric: what earns the points
  • identify p
  • Geometric ⇒ E = 1/p
  • tail as (1 − p)^k
Where partial credit is lost
  • Exam 3 Q1f (−5): count all draws including the successful one, so E = 1/p, not (1 − p)/p and not the number of losers.
✍ EC.8Knapsack FPTAS numbers New drillcalculation
Source: New drill written for these notes
n = 10 items, all fit alone, V_max = 500, ε = 1/5. (a) Give K and the scaled value of an item with v = 317. (b) Bound the largest scaled value and Σv̂. (c) How much value can rounding lose in total, and why is that ≤ ε·OPT?
Show solution

(a) K = ε·V_max/n = (1/5)(500)/10 = 10; v̂ = ⌊317/10⌋ = 31.

(b) v̂_i ≤ V_max/K = n/ε = 50, so Σv̂ ≤ n²/ε = 500; the value-indexed DP fills O(n·Σv̂) = O(n³/ε) ≈ 5000 cells.

(c) Each item loses < K, so any set loses < nK = 100 = ε·V_max. Every item fits alone, so OPT ≥ V_max, hence the loss is ≤ ε·OPT and the output is ≥ (1 − ε)OPT.

Rubric: what earns the points
  • K = εV_max/n
  • scaled values
  • bound on Σv̂ and DP size
  • loss < nK = εV_max ≤ εOPT
Where partial credit is lost
  • Missing the one fact the proof needs: V_max ≤ OPT (every item fits alone).
  • Using K = εV_max (forgetting the 1/n).
✍ EC.9How many repetitions? (boosting) New drillcalculation
Source: New drill written for these notes
A Monte Carlo algorithm succeeds with probability p on each independent run, and you can recognise the best output (e.g. keep the largest independent set found). How many runs k make the failure probability ≤ δ? Do: (a) p = 1/2, δ = 1/1000; (b) p = 1/3, δ = 1/100 (ln 100 ≈ 4.61, ln 1.5 ≈ 0.405); (c) p = 1/4, δ = 1/100 using the e^{−pk} shortcut.
Show solution

All k runs fail with probability (1 − p)^k. Need (1 − p)^k ≤ δ ⇔ k ≥ ln(1/δ)/ln(1/(1 − p)).

  1. (1/2)^k ≤ 1/1000 ⇔ k ≥ log₂ 1000 ≈ 9.97 ⇒ k = 10.
  2. k ≥ 4.61/0.405 ≈ 11.36 ⇒ k = 12.
  3. (1 − p)^k ≤ e^{−pk} ≤ δ ⇔ k ≥ ln(1/δ)/p = 4·4.61 ⇒ k = 19 (the exact formula gives 17; both are correct answers, the shortcut is simply looser).
Rubric: what earns the points
  • independent runs, output the best
  • failure = all runs fail = (1 − p)^k
  • solve for k and round up
Where partial credit is lost
  • Multiplying success probabilities instead of failure probabilities.
  • Not saying the runs are independent and how the final answer is chosen (Exam 3 Q1g asked to describe the algorithm and justify the probability).
✍ EC.10Karger on 6 vertices New drillcalculation
Source: New drill written for these notes
Karger's contraction algorithm on a 6-vertex graph. Lower-bound the probability one run outputs a fixed min cut. How many runs make the failure probability ≤ e^{−2} ≈ 0.135?
Show solution

One run: ≥ 2/(n(n − 1)) = 2/30 = 1/15. N runs all fail with probability ≤ (1 − 1/15)^N ≤ e^{−N/15}; N = 30 gives ≤ e^{−2}.

Rubric: what earns the points
  • one-run bound 2/(n(n−1))
  • independent repetitions
  • (1 − p)^N ≤ e^{−pN}
Where partial credit is lost
  • Using 1/n² instead of 2/(n(n − 1)) is fine as a bound but say which one you use.
✍ EC.11Expected satisfied clauses and one derandomization step New drillcalculation
Source: New drill written for these notes
φ = (x₁) ∧ (¬x₁ ∨ x₂) ∧ (x₁ ∨ x₂ ∨ x₃) ∧ (¬x₂ ∨ x₃ ∨ x₄). Each variable is True with probability ½ independently. (a) E[# satisfied]. (b) Compute E_T = E[Y | x₁ = T] and E_F = E[Y | x₁ = F], and say which value the method of conditional expectations picks.
Show solution

(a) A clause with k distinct-variable literals fails with probability 2^{−k}: E = ½ + ¾ + ⅞ + ⅞ = 3.

(b) Per clause, given x₁: probability 1 if a fixed literal is true; otherwise 1 − 2^{−f} with f = number of free literals. x₁ = T: 1 + ½ + 1 + ⅞ = 27/8. x₁ = F: 0 + 1 + ¾ + ⅞ = 21/8. Check: (E_T + E_F)/2 = 3 = E[Y]. Pick x₁ = True.

Rubric: what earns the points
  • indicator per clause + linearity
  • per-clause conditional probability rule
  • E_T and E_F values
  • average identity and the choice
Where partial credit is lost
  • Exam 3 Q2c (−3): you must say how each conditional expectation is computed (the per-clause rule + linearity), not only that it can be.
✍ EC.12Strongest bounds on OPT (minimization) New drillcalculation
Source: New drill written for these notes
A 3-approximation for a minimization problem with integer objective returns a solution of cost 45. The LP relaxation has optimum 12.5. Give the strongest lower and upper bounds on OPT.
Show solution

Upper: the returned solution is feasible, so OPT ≤ 45. Lower: the guarantee 45 ≤ 3·OPT gives OPT ≥ 15; the relaxation gives OPT ≥ 12.5, so OPT ≥ 13 (integer). The larger lower bound wins: 15 ≤ OPT ≤ 45.

Rubric: what earns the points
  • feasibility ⇒ one side
  • guarantee ⇒ other side
  • compare with the extra fact (LP) and keep the stronger
Where partial credit is lost
  • Exam 1 Q1c / Exam 2 Q1f: one side missing costs half the points. Always give both sides and say which fact is weaker.

8 · Proof-technique refresher exam craft · the six templates every long question uses

▸ Collapsed: click to expand▾ Click to collapse
The idea in one sentenceAlmost every proof on these exams is one of six templates; recognising which one is asked lets you write its skeleton immediately and spend your time on the one real idea.
TemplateSkeletonTriggerDrill
InductionClaim P(n) stated · base case(s) checked · "assume P(k) for [all] k < n" · step that uses the hypothesis on a smaller instance · concluderecurrences, DP correctness, algorithm invariantsU1A.4, §20
Contradiction / first failureSuppose the claim fails · take the first (or smallest) failure · derive that something earlier also failed or a bound is brokengreedy correctness, DijkstraU1B.10
ExtremalPick the max / min / longest / last object · check it has the property, case by case on boundaries"prove there exists"WS.8–WS.11
ExchangeTake an optimal solution that differs from greedy · swap one element toward greedy's choice · show it is no worse · repeatMST, greedy schedules§27.1
Both directions(⇒) given a solution of A, build one of B with the same value; check every constraint · (⇐) the reverse"if and only if", flow/reduction correctness, "max flow = max …"WS.5–WS.7
Chain of inequalitiesTarget written · numbered steps, each citing a fact (hint, earlier part, definition) · last step = targetGD rates, approximation ratios, MarkovWS.15–WS.17
Worked example: which template? "Prove that any graph whose vertices all have degree ≥ 2 contains a cycle." Existence ⇒ extremal: take a longest path v₁…vℓ; v₁ has a second neighbour u ≠ v₂. If u is off the path, u v₁…vℓ is longer (contradiction); so u = vt for some t ≥ 3, and v₁…vtv₁ is a cycle.
Traps
  • Induction whose step silently needs n ≥ 2 while the base is n = 1: check the first step after the base explicitly.
  • "By contradiction" without saying which assumption breaks.
  • A chain where one step has no reason: graders deduct there.
Recall check
Which template proves "a DAG has a source"?
Extremal: take a longest path; its first vertex has no in-edge (else a cycle or a longer path).
What must each direction of a correspondence proof preserve?
Feasibility (every constraint) and the value/size.

9 · Technique chooser exam craft · from the problem's wording to the tool and its frame

▸ Collapsed: click to expand▾ Click to collapse
The idea in one sentenceThe wording of a design question nearly always names its tool ("assign with capacities" → flow, "expected" → indicators, "show no poly algorithm" → reduction); ask the trigger questions in order and the first yes gives you the frame from §6.
Ask these in order; the first “yes” names the main tool (problems may chain two tools).Asked to show it is NP-hard / no poly algorithm?Reduction FROM a known NP-hardyesnoRandom choices, “expected”, “with probability”?Indicators + linearity, Markov, boostyesno“Approximation”, “within a factor”, NP-hard optimum?Approx: bound OPT, or ILP → LP → roundyesnoMinimize a function of real vectors, gradient, step η?Convexity check + GD theoremyesnoLinear objective, linear constraints, “dual”, certificate?LP model; dual by S-O-ByesnoAssign / match with capacities, disjoint paths, cuts?Max-flow model + both directionsyesnoOptimal value over sequences, subsets, budgets?DP: subproblem, recurrence, orderyesnoFaster than the obvious scan; split the input in parts?D&C + recurrence + master theoremyesnoA locally best choice seems safe (MST, light edge)?Greedy + exchange / cut propertyyesNone fits? Re-read the output asked for, then try a small example by hand.
Technique chooser: the trigger question on the left, the tool and its answer frame (§06) on the right.
How to read this figure Read top to bottom. Each left box is a question about the problem statement; answer "yes" and follow the arrow right to the tool to use, whose frame is in §6.1. Answer "no" and go down one row. Problems late in the paper often chain two tools (e.g. LP relaxation, then randomized rounding).
Words in the questionToolNotes section
"subsets of a sequence", "at most k", "budget", "optimal over orders"DP§23–24
"faster than O(n²)", "sorted", "find any peak / k-th"Divide & conquer§22
"assign", "each at most bj", "disjoint paths", "cut"Max flow / matching§29
"linear", "certificate", "dual", "no solution exists"LP / duality / FarkasUnit 2 (§30–34)
"step size", "smooth", "convex", "gradient"GD theoremsUnit 2 (§35–39)
"within a factor", "approximation", "relax"Bound OPT; ILP → LP → roundUnit 2 (§35–39)
"expected", "with probability", "random"Indicators, Markov, boosting, conditional expectationsUnit 3 (§40–49)
"NP-hard", "no polynomial algorithm unless P = NP"Reduction from a known NP-complete problemUnit 3 (§40–49)
Recall check
"Each nurse works at most 3 shifts, each shift needs 2 nurses": which tool?
Max flow: s → nurse (cap 3), nurse → available shift (cap 1), shift → t (cap 2); all shifts staffed ⇔ max flow = 2·#shifts.
"Prove the problem has no polynomial-time algorithm unless P = NP": which way does the reduction go?
From a known NP-hard problem to this one.

10 · Exam rules, final check and notation exam craft · from the midterm covers and rubrics

▸ Collapsed: click to expand (3 subsections)▾ Click to collapse

10.1 What the covers say

  • Midterms: "Bringing two pages of notes is permitted. No books, calculators, or other electronic devices are permitted." The final practice set repeats "No books, calculators, or other electronic devices".
  • "You may refer to standard algorithms from class": cite by name (§6.2).
  • Short answers: "Give a short justification (1–2 lines unless a proof or calculation is requested); a counterexample suffices for a false statement."
  • Select-all items lost points per wrong option (Exam 3: −2.5 for one wrong option, −5 for two): justify each option on its own.

10.2 The 7-minute final check (one line per error pattern)

TagCheck
BOUNDSEvery "bounds on OPT" answer has a lower and an upper side, each with its reason.
IFFEvery "if and only if" / reduction / flow proof has both (⇒) and (⇐) written out.
DPEvery DP has all six lines (state, ranges, base cases, recurrence + cases, order, answer + runtime).
FORMEvery model names all its parts (vertices/edges/capacities/s/t/read-off; or variables/objective/constraints/integrality; or U/sets/k′/runtime).
CHAINEvery proof chain uses the hint and the earlier parts it was given; term counts (k vs k+1) checked.
CEXEvery False has a concrete counterexample with numbers; every tight instance is a family for all n / k / Δ.
PROBEvery expectation is a number (or a formula) with the Σ prob × value written; "how to compute" stated.
CALC / OFF1The last number answers the question as asked (projected? feasible? integer?); constants match the target (Δ vs Δ + 1, m vs m + 1).
LPComplementary slackness used in the right direction: slack ⇒ partner = 0; tight ⇏ positive.

10.3 Notation used in these notes

SymbolMeaning
n, mnumber of vertices, edges (or items, constraints: stated each time)
OPT, ALGoptimal value; value returned by the algorithm
c-approximationmin: ALG ≤ c·OPT (c ≥ 1); max: ALG ≥ OPT/c (some texts write ALG ≥ c·OPT with c ≤ 1: check the paper's convention)
f*, x*optimal value / optimal point (in flow: f* = a max flow)
Gfresidual graph of flow f
c(X, V∖X)capacity of the s–t cut with source side X
A ≤p BA reduces to B in polynomial time (B is at least as hard as A)
η, β, α, G, Dstep size; smoothness; strong convexity; gradient bound; ‖x₀ − x*‖
M △ M′symmetric difference of two matchings
V*(s, t)optimal expected reward from state s with t steps left (MDP)
Pr, E, 𝟙[·]probability, expectation, indicator

11 · Short-answer track exam craft · 40 mixed T/F, select-all and one-liners across all units · EC.13–52

▸ Collapsed: click to expand▾ Click to collapse
The idea in one sentenceThe 40-point short-answer block rewards a verdict plus the single reason that settles it; these 40 items mix every unit so you practise switching topics as the real block does.
How to answer a short item (each 4–5 points)
  1. Verdict first (True / False / letters).
  2. True: name the theorem or fact and why it applies here (one line).
  3. False: the smallest counterexample, with numbers before and after.
  4. Select-all: one line per option, including the ones you don't select.
Budget: about 5 minutes each at the midterm rate (§5). Do them in sets of 10, timed, and rate each one.

These are new items, not taken from the final practice set; that set stays AI-free mock material (see START_HERE).

✍ EC.13Master theorem, tie case New drillshort answer
Source: New drill written for these notes
T(n) = 4T(n/2) + Θ(n²) solves to Θ(n² log n).

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
True. a = 4, b = 2, d = 2: log_b a = 2 = d, so every level costs Θ(n²) over Θ(log n) levels.
Where partial credit is lost
  • Writing only “master theorem” without the comparison d vs log_b a.
✍ EC.14LP: unbounded primal New drillshort answer
Source: New drill written for these notes
If a maximization LP is unbounded, its dual is infeasible.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
True. Weak duality: any dual-feasible y would give cᵀx ≤ bᵀy for every primal x, an upper bound that contradicts unboundedness.
Where partial credit is lost
  • Confusing with the converse (next drill).
✍ EC.15Markov select-all New drillshort answer
Source: New drill written for these notes
X ≥ 0 is integer-valued with E[X] = 3.

Select ALL that are always true, and justify each option in one line.

  1. Pr[X ≥ 6] ≤ 1/2.
  2. Pr[X ≥ 1] ≥ 1/2.
  3. Some outcome has X ≥ 3.
  4. Pr[X ≤ 3] > 0.
Show solution
A, C, D. A: Markov 3/6. B: false, X = 300 w.p. 1/100 and 0 otherwise has mean 3 but Pr[X ≥ 1] = 1/100. C and D: an average of values cannot exceed all of them or be below all of them (probabilistic method).
Where partial credit is lost
  • Exam 3 select-all rubric: −2.5 for one wrong option, −5 for two. Justify each option separately.
✍ EC.16Uneven recursion New drillshort answer
Source: New drill written for these notes
T(n) = T(n/4) + T(n/2) + Θ(n) solves to Θ(n log n).

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
False. 1/4 + 1/2 = 3/4 < 1: level costs shrink geometrically (n, ¾n, (¾)²n, …), sum ≤ 4n, so Θ(n).
Where partial credit is lost
  • Pattern-matching to “two recursive calls ⇒ n log n”. Check whether the fractions sum to < 1, = 1, or > 1.
✍ EC.17Dual infeasible New drillshort answer
Source: New drill written for these notes
If the dual of an LP is infeasible, the primal is unbounded.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
False. Both can be infeasible: max x₁ s.t. x₁ − x₂ ≤ −1, −x₁ + x₂ ≤ −1 (x free) is infeasible (add the rows: 0 ≤ −2), and so is its dual (checked by LP solver in calc_ec.py).
Where partial credit is lost
  • Forgetting the fourth case of the duality table (infeasible/infeasible).
✍ EC.18Geometric in disguise New drillshort answer
Source: New drill written for these notes
A bag has 12 balls, 3 red. Draw with replacement until red. Expected number of draws?
Show solution
4. Each draw is red with p = 3/12 = 1/4 independently, so the count is Geometric(1/4) with mean 1/p = 4.
Where partial credit is lost
  • Answering 3 (the expected number of non-red draws) when the question counts all draws.
✍ EC.19MoM with groups of 9 New drillshort answer
Source: New drill written for these notes
Median of medians with groups of 9 still runs in linear time.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
True. Half of the n/9 medians are ≥ the pivot and each brings 5 elements ≥ it: ≥ 5/18·n on each side, so the recursion is T(n/9) + T(13/18·n) + Θ(n) and 1/9 + 13/18 = 5/6 < 1.
Where partial credit is lost
  • Not deriving the kept fraction (Exam 1A Q1g asked for both fractions with justification).
✍ EC.20Complementary slackness select-all New drillshort answer
Source: New drill written for these notes
x*, y* are optimal for max cᵀx, Ax ≤ b, x ≥ 0 and its dual.

Select ALL that are always true, and justify each option in one line.

  1. If x*₁ > 0, the first dual constraint is tight.
  2. If y*₂ > 0, primal row 2 is tight.
  3. If primal row 3 is tight, then y*₃ > 0.
  4. If the first dual constraint is slack, then x*₁ = 0.
Show solution
A, B, D. A, B, D are complementary slackness (positive variable ⇒ its partner constraint tight; slack constraint ⇒ partner variable 0). C is false: max x₁ s.t. x₁ ≤ 1, x₁ + x₂ ≤ 1 has both rows tight at (1, 0), and y = (1, 0) is dual optimal with y₂ = 0.
Where partial credit is lost
  • Exam 2 Q1b (−5): “tight ⇒ positive” is the trap; only “slack ⇒ zero” follows.
✍ EC.21Pseudo-polynomial New drillshort answer
Source: New drill written for these notes
An O(n·W) algorithm for subset sum with target W is a polynomial-time algorithm.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
False. W is written in log W bits; O(nW) = O(n·2^{log W}) is exponential in the input length (pseudo-polynomial).
Where partial credit is lost
  • Measuring input size by the number of items only.
✍ EC.22Convexity of a max New drillshort answer
Source: New drill written for these notes
f(x) = max(x, 2x − 1) is convex on ℝ.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
True. A pointwise maximum of convex (here affine) functions is convex: each chord lies above both lines, hence above their max.
Where partial credit is lost
  • Confusing with min, which is not convex (min{x, 0}).
✍ EC.23Union bound New drillshort answer
Source: New drill written for these notes
For any events A₁, …, Aₙ that are pairwise independent, Pr[A₁ ∪ ⋯ ∪ Aₙ] = Σ Pr[Aᵢ].

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
False. Two fair coins, A = first heads, B = second heads: independent, but Pr[A ∪ B] = 3/4 < ½ + ½. Equality needs disjoint events; in general only ≤ (union bound).
Where partial credit is lost
  • Practice Exam 3 1(d): the “=” version is false, the “≤” version is the union bound.
✍ EC.24Unique MST New drillshort answer
Source: New drill written for these notes
If all edge weights of a connected graph are distinct, the MST is unique.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
True. Each edge Prim adds is the unique light edge of the current cut (S, V∖S), so by the cut property it lies in every MST; these n − 1 edges are a spanning tree, so every MST equals it.
Where partial credit is lost
  • “Some MST” vs “every MST”: uniqueness needs the strict version of the cut property.
✍ EC.25Smoothness of x⁴ New drillshort answer
Source: New drill written for these notes
f(x) = x⁴ is β-smooth on ℝ for some finite β.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
False. f″(x) = 12x² is unbounded, so f′ is not Lipschitz: |f′(x) − f′(0)| = 4|x|³ exceeds β|x| once x² > β/4.
Where partial credit is lost
  • Convex ⇏ smooth. Check the second derivative on the whole domain.
✍ EC.26Las Vegas to Monte Carlo New drillshort answer
Source: New drill written for these notes
A Las Vegas algorithm with expected time n² can be stopped after 10n² steps to give a Monte Carlo algorithm that errs with probability ≤ 1/10.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
True. It errs only if its time T ≥ 10n²; Markov gives Pr[T ≥ 10n²] ≤ n²/(10n²) = 1/10.
Where partial credit is lost
  • Forgetting that time is nonnegative (that is what licenses Markov).
✍ EC.27Heaviest edge New drillshort answer
Source: New drill written for these notes
The heaviest edge of a connected weighted graph is never in an MST.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
False. If it is a bridge (e.g. the graph is a tree), every spanning tree contains it. True version: the unique heaviest edge on a cycle is in no MST.
Where partial credit is lost
  • Dropping the “on a cycle” hypothesis.
✍ EC.28Strongly convex but not smooth New drillshort answer
Source: New drill written for these notes
f(x) = x² + eˣ is 2-strongly convex on ℝ but not β-smooth for any β.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
True. f″(x) = 2 + eˣ ≥ 2 everywhere (so α = 2), but f″ is unbounded as x → ∞, so no finite β works.
Where partial credit is lost
  • Mixing up which bound (lower: α, upper: β) each property controls.
✍ EC.29Approximation preserved by complement? New drillshort answer
Source: New drill written for these notes
Since S is independent ⇔ V∖S is a vertex cover, a 2-approximation for Vertex Cover yields a 2-approximation for Independent Set (output the complement).

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
False. Perfect matching on n = 10 vertices: OPT VC = 5, so returning all 10 vertices is a valid 2-approximate cover, but its complement is ∅ while OPT IS = 5. Lec 20: complementation preserves exact optima, not ratios.
Where partial credit is lost
  • Lec 20 warning, verbatim: “A reduction transfers only the properties proved about it.”
✍ EC.30BFS with equal weights New drillshort answer
Source: New drill written for these notes
If every edge weight equals 5, BFS from s gives the shortest-path distances (times 5).

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
True. Every path's weight is 5 × its number of edges, so minimizing weight = minimizing edge count, which BFS does in O(n + m).
Where partial credit is lost
  • Saying “need Dijkstra”: correct but slower and misses the point.
✍ EC.31GD theorem: which iterate? New drillshort answer
Source: New drill written for these notes
f convex with ‖∇f‖ ≤ G and ‖x₀ − x*‖ ≤ D, η = D/(G√T). The bound DG/√T holds for…

Select ALL that are always true, and justify each option in one line.

  1. the last iterate x_T
  2. the average x̄ = (1/T)Σ_{t<T} x_t
  3. the best iterate argmin_t f(x_t)
  4. every iterate
Show solution
B, C. The proof bounds the average of f(x_t), then uses convexity (Jensen) for x̄; the best iterate is at most the average value (Part 2 notes p32). Not the last iterate: on |x| with fixed η the iterates bounce between ±0.5 forever.
Where partial credit is lost
  • Choosing A; that is the smooth theorem (η = 1/β), which does cover the last iterate.
✍ EC.32Max flow saturates the source? New drillshort answer
Source: New drill written for these notes
In every maximum flow, every edge leaving s is saturated.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
False. s → a capacity 10, a → t capacity 1: max flow 1, edge (s, a) carries 1 of 10.
Where partial credit is lost
  • Confusing with: edges leaving the min-cut side X (reachable set in the final residual graph) are saturated.
✍ EC.33Every graph has a big cut New drillshort answer
Source: New drill written for these notes
Every graph with 13 edges has a cut containing at least 7 edges.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
True. A uniformly random cut has E[#crossing] = 13/2 (each edge crosses w.p. ½, linearity). Some outcome is ≥ the mean, and cut sizes are integers, so some cut has ≥ ⌈6.5⌉ = 7.
Where partial credit is lost
  • Stopping at “≥ 6.5” without using integrality.
✍ EC.34PTAS vs FPTAS New drillshort answer
Source: New drill written for these notes
If a problem has a PTAS, it has an FPTAS.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
False. A PTAS may run in time like n^{1/ε} (polynomial for each fixed ε, not in 1/ε); an FPTAS must be poly(n, 1/ε). The implication goes only the other way.
Where partial credit is lost
  • Practice exam (Fall 2025) Q7: same definitional trap.
✍ EC.35Fractional max flow New drillshort answer
Source: New drill written for these notes
With integer capacities, every maximum flow is integral.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
False. s→a (1), a→b (1), a→c (1), b→t (1), c→t (1): sending ½ along each branch is a maximum flow of value 1. The integrality theorem says an integral max flow exists (Ford–Fulkerson finds one).
Where partial credit is lost
  • Over-stating the integrality theorem. In a flow reduction say “take an integral maximum flow (exists by integrality)”.
✍ EC.36Reductions select-all New drillshort answer
Source: New drill written for these notes
B is NP-complete, B ≤p C, and C ∈ NP.

Select ALL that are always true, and justify each option in one line.

  1. C is NP-hard.
  2. C is NP-complete.
  3. If C ∈ P then P = NP.
  4. Every problem A ∈ NP satisfies A ≤p B.
Show solution
All four. A: hardness flows forward along B ≤p C (B is NP-hard). B: NP-hard and in NP. C: an NP-hard problem in P puts all of NP in P (Lec 20 Theorem). D: definition of B being NP-hard.
Where partial credit is lost
  • Missing D because it does not mention C: read every option on its own.
✍ EC.37Dijkstra select-all New drillshort answer
Source: New drill written for these notes
Dijkstra's algorithm with a binary heap on a directed graph…

Select ALL that are always true, and justify each option in one line.

  1. runs in O((n + m) log n)
  2. is correct if some edges have weight 0
  3. is correct with one negative edge as long as there is no negative cycle
  4. settles vertices in nondecreasing order of distance
Show solution
A, B, D. A: Lec 6 p4. B: the proof needs only nonnegative weights. C: s→a 2, s→b 3, b→a −2 settles a at 2 though dist(a) = 1. D: the extract-min order (with nonnegative weights).
Where partial credit is lost
  • Not producing the 3-vertex counterexample for C.
✍ EC.38Karger on a cycle New drillshort answer
Source: New drill written for these notes
One run of Karger's contraction algorithm on the cycle Cₙ always returns a minimum cut.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
True. Contracting an edge of a cycle gives a shorter cycle, so at 2 vertices there are exactly 2 parallel edges; every cut of Cₙ has ≥ 2 edges, so the output is a min cut (300 random runs on C₆ checked in calc_ec.py).
Where partial credit is lost
  • Reflexively answering “probability 2/(n(n − 1))”: that is a lower bound, not the exact value.
✍ EC.39Strongest bounds, LP + approximation New drillshort answer
Source: New drill written for these notes
A 2-approximation for an integer-valued minimization problem returns 30, and the LP relaxation's optimum is 18.5. Strongest bounds on OPT?
Show solution
19 ≤ OPT ≤ 30. Feasible solution ⇒ OPT ≤ 30. Guarantee ⇒ OPT ≥ 15. Relaxation ⇒ OPT ≥ 18.5, so ≥ 19 by integrality; 19 beats 15.
Where partial credit is lost
  • Giving [15, 30]: the extra fact (LP) is stronger here; always compare.
✍ EC.402-SAT New drillshort answer
Source: New drill written for these notes
2-SAT is NP-complete because it is a special case of SAT.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
False. A special case of a hard problem can be easy: 2-SAT is solvable in linear time via the implication graph and SCCs (unsatisfiable ⇔ some x and ¬x share an SCC).
Where partial credit is lost
  • Hardness flows to generalizations, not to special cases.
✍ EC.41Raising every capacity New drillshort answer
Source: New drill written for these notes
Adding 1 to every edge capacity can change which s–t cut is minimum.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
True. s→a (4), a→xᵢ (1) for i = 1, 2, 3, xᵢ→t (10): min cut {s, a} of capacity 3. After +1: cut {s} has 5 < 6, so the min cut moves; max flow goes 3 → 5 (Edmonds–Karp in calc_ec.py). Cuts with more edges grow faster.
Where partial credit is lost
  • Analogy trap: adding a constant also changes shortest paths, but never the MST.
✍ EC.42Max-SAT in NP? New drillshort answer
Source: New drill written for these notes
The optimization problem Max-SAT (output an assignment maximizing satisfied clauses) is known to be in NP.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
False. It is NP-hard (SAT reduces to it: φ satisfiable ⇔ the optimum is m), but a candidate cannot be checked for optimality in polynomial time, so it is not known to be in NP. Say “not known”, never “provably not”.
Where partial credit is lost
  • NP-hard does not require membership in NP.
✍ EC.43Threshold 1/3 for VC rounding New drillshort answer
Source: New drill written for these notes
Rounding the vertex-cover LP solution at threshold 1/3 (take v iff x*_v ≥ 1/3) gives a feasible cover of cost ≤ 3·OPT.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
True. Each edge has x*_u + x*_v ≥ 1, so some endpoint is ≥ ½ ≥ ⅓ (feasible); the taken set costs ≤ 3·Σx* = 3·LP ≤ 3·OPT. Valid, just weaker than threshold ½.
Where partial credit is lost
  • Thresholds above ½ can be infeasible (single edge with x = (½, ½)); below ½ stay feasible but cost more.
✍ EC.44Conditional expectations New drillshort answer
Source: New drill written for these notes
In derandomization by conditional expectations with fair coins, at every step at least one value of the next variable keeps the conditional expectation ≥ its current value.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
True. E[Y | past] = ½E_T + ½E_F (law of total expectation, the next coin is fair and independent), and an average is ≤ the larger term.
Where partial credit is lost
  • Exam 3 Q2c (−3): state why one of them is ≥ (the average identity), not just that one is.
✍ EC.45Maximal vs maximum New drillshort answer
Source: New drill written for these notes
A bipartite graph can have a maximal matching of size 2 and a maximum matching of size 5.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
False. Every edge of a maximum matching M* touches the maximal M (else add it), and each M-edge touches ≤ 2 M*-edges, so |M*| ≤ 2|M| = 4 < 5.
Where partial credit is lost
  • Knowing maximal ≠ maximum but not the factor-2 relation between them.
✍ EC.46Descent with the safe step New drillshort answer
Source: New drill written for these notes
For convex β-smooth f, GD with η = 1/β satisfies f(x_{t+1}) ≤ f(x_t) at every step.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
True. Descent lemma with η = 1/β: f(x_{t+1}) ≤ f(x_t) − ‖∇f(x_t)‖²/(2β) ≤ f(x_t). (It does not even need convexity.)
Where partial credit is lost
  • Saying “only for small enough η” without the threshold: decrease holds for every η < 2/β.
✍ EC.47Value-indexed knapsack New drillshort answer
Source: New drill written for these notes
If every item value is in {1, …, 10}, 0/1 knapsack is solvable in polynomial time.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
True. The value-indexed DP runs in O(n·Σv) ≤ O(n·10n) = O(n²). (This does not contradict NP-hardness: hard instances need large values.)
Where partial credit is lost
  • Answering “NP-hard ⇒ no” without looking at which parameter is small.
✍ EC.48Expectation of a product New drillshort answer
Source: New drill written for these notes
For any random variables X, Y with finite means, E[XY] = E[X]·E[Y].

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
False. X = Y = one fair bit: E[XY] = E[X²] = 1/2 but E[X]E[Y] = 1/4. Needs independence (linearity is only for sums).
Where partial credit is lost
  • Extending linearity of expectation to products or maxima.
✍ EC.49Optimal action vs horizon New drillshort answer
Source: New drill written for these notes
In a finite-horizon MDP, the optimal action at a state can depend on the number of steps remaining.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
True. At s, a pays 1 and stays; b pays 0 and moves to g where every step pays 3. With 1 step left choose a (1 vs 0); with 2 steps left choose b (0 + 3 = 3 vs 1 + 1 = 2).
Where partial credit is lost
  • Treating the policy as stationary; the Bellman table is indexed by (state, steps remaining).
✍ EC.50Reduction direction New drillshort answer
Source: New drill written for these notes
To prove a new problem X is NP-hard, it suffices to give a polynomial-time reduction X ≤p 3-SAT.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
False. That shows X is no harder than 3-SAT (true of every NP problem, even shortest path). Reduce FROM the known hard problem TO X: 3-SAT ≤p X.
Where partial credit is lost
  • Exam 3 Q3c rubric: “Did the reverse” cost 3.5 of 7.
✍ EC.51Farkas certificate New drillshort answer
Source: New drill written for these notes
Show that Ax = b, x ≥ 0 has no solution for A = [[1, 2], [2, 1]], b = (1, −1), by exhibiting y with Aᵀy ≥ 0 and bᵀy < 0.
Show solution
y = (1, 2). Aᵀy = (5, 4) ≥ 0 and bᵀy = 1 − 2 = -1 < 0. If x ≥ 0 solved Ax = b, then 0 ≤ (Aᵀy)ᵀx = yᵀAx = yᵀb < 0, a contradiction.
Where partial credit is lost
  • Giving y without verifying both inequalities numerically.
✍ EC.52Self-reduction count New drillshort answer
Source: New drill written for these notes
Given a black box that answers IS-search (given G, k: return an independent set of size ≥ k or No), a maximum independent set can be found with at most n + 1 calls.

True or False? Justify in 1–2 lines (a counterexample suffices for False).

Show solution
True. Query k = n, n − 1, …, 0; the first k that returns a set equals α(G), and that set is maximum (Lec 20 §1). Binary search uses O(log n) calls.
Where partial credit is lost
  • Forgetting that the search box returns the set itself (no extra reconstruction needed).

12 · What the professor flagged verbatim quotes from lectures, boards and announcements, each linked to where the notes cover it

▸ Collapsed: click to expand▾ Click to collapse
The idea in one sentenceThings the professor said were important, tricky or "on the exam" carry more weight than anything a textbook says; each quote below is checked against its source and points to the part of the notes it changed.

Kinds: emphasis, trap, convention, exam hint. "Transcribed from handwritten board" means the quote was read off a board image, not a text layer.

Unit 1b · Max flow and min cut

B01direct exam signal
“another thing to be careful about because it's a directed graph I'm talking about when I say cut value I'm saying the sum of the edge capacities along the cut going from inside to outside so I'm only summing up edges going from inside to outside I'm not summing up the edges going from outside to inside”
algo-part1-notes/Lec 8 Sec A.srt · Lec 8, 01:00:16
What it changes: The capacity of a directed s–t cut adds only the edges leaving X. Edges coming back into X add nothing to the capacity (their flow is subtracted when you compute the net flow across the cut). → covered in the notes
B02direct exam signal
“if the capacities were higher or something I kind of have to do every edge I have to do both the moves”
algo-part1-notes/Lec 8 Sec A.srt · Lec 8, 00:39:44
What it changes: Every original edge with 0 < fe < ce gives two residual edges: forward ce − fe and backward fe. In the unit-capacity example one of the two was always 0, which hides this. Exam 1A Q1h tested exactly this. → covered in the notes
B03direct exam signal
“the definition and so on is very important of the residual graph”
algo-part1-notes/Lec 8 Sec A.srt · Lec 8, 00:54:57
What it changes: Be able to draw Gf for any given flow, with both edge types and their capacities (the Unit 1 practice exam gave 6 points for this drawing). → covered in the notes
B04direct exam signal
“this part is in syllabus that like this is a pseudo polynomial time algorithm this you should understand it's a pseudo polynomial time algorithm because the running time depends on the maximum flow value”
algo-part1-notes/Lec 8 Sec A.srt · Lec 8, 00:49:38
What it changes: Ford–Fulkerson runs in O((m + n)(1 + |f*|)): polynomial in the value |f*|, which can be exponential in the number of input bits. Say “pseudo-polynomial”, the same word as for the O(nB) knapsack DP. → covered in the notes
B05conflict between sources
“one can show that that algorithm works even polynomial time but the analysis is more involved like we'll take a lecture so we are not doing it”
algo-part1-notes/Lec 8 Sec A.srt · Lec 8, 00:50:25
What it changes: The Edmonds–Karp running-time proof was not done in lecture. You still need the statement (shortest augmenting path by BFS ⇒ O(nm²), independent of capacities). → covered in the notes
⚠ Practice problems 1, Q4.3 asks you to derive the O(|V||E|²) bound from a given lemma (each residual edge is saturated at most |V|/2 times). That derivation is a three-line counting argument; drill it (U1B.43).
B06direct exam signal
“And now in the middle one, I have basically sending 59 on 100.”
algo-part1-notes/Lec 8 Sec A.srt · Lec 8, 00:44:50
What it changes: An augmentation raises |f| but can lower the flow on individual edges: wherever the augmenting path uses a backward residual edge, that original edge loses Δ units (60 → 59 in the lecture example). → covered in the notes
B07direct exam signal
“you can do the bottleneck capacity or even like or just one”
algo-part1-notes/Lec 8 Sec A.srt · Lec 8, 00:46:49
What it changes: Augmenting by 1 or by the full bottleneck are both valid Ford–Fulkerson steps; the bottleneck version can be faster but has the same worst-case bound. → covered in the notes
B08direct exam signal
“you can just work with integral flows and you don't lose anything because my capacities are integral”
algo-part1-notes/Lec 8 Sec A.srt · Lec 8, 00:26:10
What it changes: Integrality theorem: integer capacities ⇒ some maximum flow is integral, and Ford–Fulkerson finds one. Every flow-modeling proof (matching, assignment) needs this step for the “flow ⇒ solution” direction. → covered in the notes
B09direct exam signal
“especially if it's an integral max flow, you can immediately interpret it as, like, a matched edge.”
algo-part1-notes/Lec 8 Sec A.srt · Lec 8, 00:20:11
What it changes: Bipartite matching via flow: the flow-1 middle edges of an integral flow form a matching. A fractional flow (½ on several edges) does not. → covered in the notes
B15direct exam signal transcribed from handwritten board
“Claim: |f| = Cut value (a) f_e = c_e (b) f_e = 0 ⇒ Total flow = Total cut”
algo-part1-notes/Lec_8_SecA.pdf · Lec 8 board, p5 (handwritten next to the max-flow min-cut proof)
What it changes: The whole MFMC proof in one line: for X = vertices reachable in Gf, (a) every edge leaving X is saturated and (b) every edge entering X carries 0, so |f| equals the capacity of (X, V∖X). → covered in the notes
B17direct exam signal
“There is no mention of student or project here?”
my-exams/submission_429412841.pdf · Exam 1A graded, Q4(b) grader comment
What it changes: A flow-modeling answer must name the vertices in the problem's own words (one vertex per student, one per project), every edge with its capacity, s, t, and how to read the answer off an integral max flow. → covered in the notes
B18direct exam signal
“Only one direction is correct of (i) and (ii),”
my-exams/submission_429412841.pdf · Exam 1A rubric, Q4(c)
What it changes: Correctness of a flow reduction is two directions: (i) solution ⇒ flow of the same value, and (ii) integral flow ⇒ solution of the same value. One direction alone loses 3 of 8 points. → covered in the notes

Unit 1b · Shortest paths and MST

B10direct exam signal transcribed from handwritten board
“if there are ties”
algo-part1-notes/Lec_7_SecA.pdf · Lec 7 board, p1 (arrow under the word “some” in the cut property)
What it changes: The cut property gives “some MST” because of ties; only a unique light edge is in every MST. A T/F that swaps “some” and “every” is the classic trap. → covered in the notes
B13direct exam signal transcribed from handwritten board
“O(n+m+Σ_e(w_e−1)) Claim: Suffices to find shortest path in this expanded graph”
algo-part1-notes/Lec_6_SecA(1).pdf · Lec 6 board, p3 (next to the unit-edge reduction)
What it changes: Replacing an edge of weight w by w unit edges and running BFS is correct but pseudo-polynomial: the graph size depends on the weights' values. This is the motivation for Dijkstra. → covered in the notes
B14direct exam signal transcribed from handwritten board
“Optional”
algo-part1-notes/Lec_6_SecA(1).pdf · Lec 6 board, p4 (written beside §4.3 “Remarks: beyond the binary-heap bound”)
What it changes: Fibonacci heaps and the recent research bounds were marked optional. Quote Dijkstra as O((n + m) log n) with a binary heap. → covered in the notes
B16direct exam signal
“False. Use directed edges s → u and u → t, each of weight 1, and s → t of weight 3.”
exams/Exam1_SecA_Soln.pdf · Exam 1A solutions, Q1(f)
What it changes: Adding a constant to every edge penalizes paths with more edges, so shortest paths can change. The answer needs the counterexample with numbers (5 points; the student scored 0). → covered in the notes
B19direct exam signal
“True, by applying the cut property on the cut ({u},V \ {u})”
algo-part1-notes/Practice_Exam_Unit_1_Solutions.pdf · Practice Exam Unit 1, Q1.5
What it changes: The expected 1–2 line justification on MST T/F: name the cut property and the specific cut. → covered in the notes

Unit 1b · Matchings

B11direct exam signal transcribed from handwritten board
“Maximum vs Maximal Global opt Local opt”
algo-part1-notes/Lec_7_SecA.pdf · Lec 7 board, p3 (next to the definitions)
What it changes: Maximal = no edge can be added (a local dead end); maximum = largest possible. The board example: M = {(3,5)} is maximal but a matching of size 3 exists. → covered in the notes
B12direct exam signal transcribed from handwritten board
“If |M| < |M| then ∃ aug path”
algo-part1-notes/Lec_7_SecA.pdf · Lec 7 board, p4 (boxed, next to Berge's theorem)
What it changes: This is the hard direction of Berge (not maximum ⇒ augmenting path exists), proved with M △ M*. Write both directions on the exam. → covered in the notes

15 · Your error patterns: one rule each weak spots · 105.5 raw points lost across Exams 1–3 · from your graded submissions in my-exams/

▸ Collapsed: click to expand (3 subsections)▾ Click to collapse
The idea in one sentenceYour lost points cluster into eleven repeatable patterns; each has a one-line check, and the check is cheap enough to run on every answer during the final.

Points are raw losses before curves (Exam 1: 49.5, Exam 2: 39.5, Exam 3: 16.5). Every part is listed with a link to its redo in §17.

TagPatternPtsThe checkDrills
DPDP write-up incomplete15All six lines of the frame (§6), tickedWS.1–WS.4, U1A.31
IFFOnly one direction (or none)14Write (⇒) and (⇐) headers first; each preserves valueWS.5–WS.7
CEXCounterexample / tight instance not produced12Smallest instance; both values with numbers; families in n / k / Δ§11 False items, U1B.8
CHAINHint / earlier part not used12List the given facts that must appear; count termsWS.15–WS.17
FLOW / FORMModel with missing components12Every input parameter appears somewhere (bj as a capacity, k′, U)WS.12–WS.14
PROBExpectation not computed / "how" not stated11.5Σ prob × value written; geometric 1/p; per-clause ruleEC.6, EC.7, EC.11
BOUNDSOne side of "bounds on OPT" missing9.5Feasibility gives one side, the guarantee the otherEC.12, EC.39, U1A.40
LPComplementary slackness / Farkas select-all9Slack ⇒ partner 0; tight ⇏ positive; one line per optionEC.20, EC.51
EXISTExistence proof6Extremal choice + boundary casesWS.8–WS.11
OFF1Off-by-one constant / index2.5Re-read the target constant before finishingU1A.17
CALCCalculation stopped one step early2Does the last number answer the question (projected, feasible)?EC.2

15.1 BOUNDS: both sides, every time

Exam 1 Q1c (−5) and Exam 2 Q1f (−4). The rule: feasibility of the returned solution gives one side for free (min: OPT ≤ ALG; max: OPT ≥ ALG). The guarantee gives the other (min with factor c: OPT ≥ ALG/c; max with factor ρ < 1: OPT ≤ ALG/ρ). Extra facts (a matching, an LP value) can only tighten the guarantee's side; keep whichever is stronger.

Minimization (E2 Q1f): 2-approx returned ALG = 208 (matching)10 = ALG/220 = ALG0OPT ∈ [10, 20]Maximization (E1 Q1c): (1−1/5)-approx returned ALG = 8080 = ALG100 = ALG/(4/5)64 (my lower)120 (my upper)OPT ∈ [80, 100]
Feasibility gives one side (ALG itself), the guarantee gives the other. My answers 64 and 120 sit outside the true interval.
How to read this figure Top: Exam 2 Q1f (minimization). The matching gives OPT ≥ 8, the guarantee gives OPT ≥ 10 (stronger), and ALG = 20 is the upper end. Bottom: Exam 1 Q1c (maximization). ALG = 80 is the lower end and 80/(4/5) = 100 the upper. The red marks are what you wrote (64 and 120): one side wasn't derived from feasibility and the other was an arithmetic slip.
Three quick variants
  • Max, ¾-approximation returns 60: 60 ≤ OPT ≤ 80.
  • Min vertex cover, 2-approximation returns 30, the graph has a matching of size 18: lower bounds 15 (guarantee) and 18 (each matching edge needs its own cover vertex), so 18 ≤ OPT ≤ 30.
  • Min set cover by 1/f rounding with f = 3 returns 27, LP value 23/2: lower bounds 9 and ⌈11.5⌉ = 12, so 12 ≤ OPT ≤ 27.

15.2 PROB: a policy chooses per state, and expectations are numbers

Exam 1 Q1d (−3.5): you computed "a then c gives 5", a fixed sequence of actions. A policy chooses the second action after seeing the state: at u pick c (8), at v pick d (4), so Q(s, a) = ½·8 + ½·4 = 6 > Q(s, b) = 1 + 4 = 5. The rubric gave points separately for the policy and for each first action's expectation.

saction ab: +2wuv1/32/3c: +9 ✓d: +1c: +0d: +6 ✓e: +3Q(s,a) = ⅓·9 + ⅔·6 = 7Q(s,b) = 2 + 3 = 5
Choose the second action separately in u and in v (✓), then average. A fixed sequence ‘a then c’ or ‘a then d’ is not a policy.
How to read this figure A new instance with the same shape as Exam 1 Q1d. From s, action a branches to u (prob 1/3) and v (prob 2/3); action b goes to a state whose only action pays 3. Ticks mark the best second action in each state, chosen separately. Q(s, a) = 7 beats Q(s, b) = 5, but any fixed sequence starting with a is worse than b (a then c: 3; a then d: 13/3).
Geometric, counting the success Exam 3 Q1f (−5): 25 PhD among 200 names, sample with replacement until a PhD: p = 25/200 = 1/8, so E = 8 draws. Variants: a die until a 5 or 6: E = 3; a deck until an ace: E = 13, and Pr[more than 3 draws] = (12/13)³ = 1728/2197.

Conditional expectations (Exam 3 Q2c, −3): say how E_T and E_F are computed: for each clause, probability 1 if a fixed literal is already true, 0 if all its literals are fixed false, otherwise 1 − 2−f (f = free literals); sum over clauses by linearity. Then E[Y | past] = ½E_T + ½E_F ⇒ max(E_T, E_F) ≥ E[Y | past].

15.3 FORM and IFF: every input appears, and both directions

Exam 3 Q3 (−8): your universe was the vertices with Sv = {v} ∪ N(v). That instance encodes Dominating Set, not Vertex Cover; the hint said "a universe of edges". Test a reduction on a triangle before proving it.

Correct: U = edges, S_v = edges at vabce₁e₃e₂S_a={e₁,e₃} S_b={e₁,e₂} S_c={e₂,e₃}min SC = 2 = min VC ✓My exam: U = vertices, S_v = {v} ∪ N(v)abcS_a = {a,b,c} covers U alone:SC size 1, but min VC = 2 ✗
Test any reduction on a triangle before proving it. The closed-neighbourhood sets build Dominating Set, not Vertex Cover.
How to read this figure Top: the correct construction on a triangle: U = its three edges, Sv = edges at v. Any two sets cover U and no single set does, so min SC = 2 = min VC. Bottom: your construction. Sa = {a, b, c} covers U by itself, giving a set cover of size 1 while the minimum vertex cover is 2, so the (⇐) direction fails.
Summary card
  • Every given parameter (bj, k, the slot σ) must appear in the construction.
  • Headers (⇒) and (⇐) before anything else; each maps solutions with the same value.
  • Test the construction on the smallest interesting instance (triangle, 2 students).
Recall check
Max problem, (1 − ε)-approximation with ε = 1/4 returns 90. Strongest bounds?
90 ≤ OPT ≤ 90/(3/4) = 120.
Why is "a then c" not a policy in a two-step MDP?
A policy may choose the second action depending on the state reached; a fixed sequence ignores that, so it can be worse than the optimum.
VC ≤ SC: what is the universe, and what is Sv?
U = E; Sv = edges incident to v; k′ = k.

16 · Weak-spot drills: your five biggest losses weak spots · E1 Q3b (10) · E1 Q4c (8) · E1 Q2a (6) · E1 Q4b (6) · E2 Q3b (6)

▸ Collapsed: click to expand (5 subsections)▾ Click to collapse
The idea in one sentenceFor each of your five largest single losses: the redo with the real rubric line, what you wrote and why it lost the points, then new instances of the same skill until the frame is automatic.

The redo cards repeat questions also redone in the Unit 1 sections (U1A.31, U1B.32, U1A.16); these versions add your answer and its root cause. Rate them separately.

16.1 DP recurrences (E1 Q3b, −10)

Rule Case on the last decision. If taking item i forbids its neighbours, the take-case jumps past them (i−2 for "no two adjacent", i−3 for "gap ≥ 3"); a count limit drops one column.
✍ WS.4Fill the non-adjacent DP table on a new instance New drillcalculation
Source: New drill for these notes (weak spots)
Same problem as E1 Q3 (no two consecutive, at most k chosen). Values v = (4, 1, 3, 6, 2), k = 2. Fill D(i, j) for 0 ≤ i ≤ 5, 0 ≤ j ≤ 2 using D(i, j) = max{D(i−1, j), vi + D(i−2, j−1)}, report the answer cell and an optimal set.
Show solution

Rows i = 0..5, columns j = 0, 1, 2:

iD(i,0) · D(i,1) · D(i,2)
00 · 0 · 0
10 · 4 · 4
20 · 4 · 4
30 · 4 · 7
40 · 6 · 10
50 · 6 · 10

Sample cells: D(3,2) = max{D(2,2) = 4, 3 + D(1,1) = 7} = 7; D(4,2) = max{7, 6 + D(2,1) = 10} = 10; D(5,2) = max{10, 2 + D(3,1) = 6} = 10.

Answer D(5, 2) = 10, from I = {1, 4} (4 + 6). Checked by brute force over all subsets in calc_ws.py.

Rubric: what earns the points
  • base row and column filled with 0
  • each cell from the two cases
  • answer cell D(n,k)
  • optimal set traced back
Where partial credit is lost

Reading the answer from D(n, n) or max over the last row instead of D(n, k); forgetting that row 1 is v1 for j ≥ 1.

✍ WS.1Redo E1 Q3b: recurrence for non-adjacent projects with at most k chosen Past examdesign + prove
Source: Exam 1 Sec A (Sep 22, 2026), exams/Exam1_SecA_Soln.pdf p4
There are n ≥ 1 projects in a fixed order; project i has a nonnegative integer value vi. Choose I ⊆ {1,…,n} with at most k chosen projects and no two consecutive indices, maximizing Σi∈I vi. Let D(i, j) = the maximum total value using only projects 1..i, choosing at most j of them, no two consecutive. Give the recurrence for D(i, j) and justify it by considering whether project i is chosen. Explain how it enforces both constraints. (10 pts)
Show solution

Recurrence. For i ≥ 2 and j ≥ 1:

D(i, j) = max{ D(i−1, j), vi + D(i−2, j−1) }

with base cases D(0, j) = 0, D(i, 0) = 0, and D(1, j) = v1 for j ≥ 1 (so no negative row is referenced).

Justification (case on project i).

  1. i not chosen. The rest is any feasible choice from 1..i−1 with at most j projects: best value D(i−1, j).
  2. i chosen. Then i−1 cannot be chosen (adjacency), and only j−1 slots remain for projects 1..i−2: best value vi + D(i−2, j−1).

Both constraints: jumping to row i−2 enforces “no two consecutive”; dropping to column j−1 enforces “at most k” (the count only goes down when a project is taken, and column 0 has value 0).

Exactness (converse). Each candidate is attained by a feasible set: skipping i keeps feasibility; appending i to a feasible set from 1..i−2 creates no adjacency and uses at most j projects. Induction on i proves every entry correct.

Rubric: what earns the points
  • recurrence stated for i ≥ 2, j ≥ 1
  • case i not chosen → D(i−1, j)
  • case i chosen → v_i + D(i−2, j−1)
  • explains adjacency (row i−2) and count (column j−1)
  • converse: each candidate achievable
  • i = 1 handled without a negative row
Where partial credit is lost

Real rubric line: −10 pts “Empty”.

What I wrote: Only the start of a line: “D[i,j] = max(vi + D[i−1, j−”, unfinished. Row i−1 after taking i would also have allowed i−1, breaking adjacency.

Root cause: Time (Q3b and Q4c were the last things I reached) plus the include-case index: taking i forbids i−1, so jump to i−2.

✍ WS.2DP write-up: no three consecutive chosen New drilldesign + prove
Source: New drill for these notes (weak spots)
Projects 1..n in order with values vi ≥ 0. Choose any number of projects, but never three consecutive indices. Maximize the total value. Write the full DP in the 6-line frame, then run it on v = (3, 5, 4, 6, 2, 7).
Show solution
  1. State. D(i) = max total value using only projects 1..i with no three consecutive chosen.
  2. Range. 0 ≤ i ≤ n.
  3. Base cases. D(0) = 0, D(1) = v1, D(2) = v1 + v2 (values are nonnegative and two in a row is allowed).
  4. Recurrence (case on how the solution ends), i ≥ 3: D(i) = max{ D(i−1), vi + D(i−2), vi + vi−1 + D(i−3) }. Either i is skipped; or i is taken and i−1 skipped; or i and i−1 are taken, which forces i−2 skipped. These are all the ways a valid set can end, and each candidate is achievable.
  5. Order. Increasing i.
  6. Answer and runtime. D(n); O(n) time, O(n) space (O(1) with three rolling values).

Run: D(0..6) = 0, 3, 8, 9, 14, 16, 21. E.g. D(5) = max{14, 2 + D(3) = 11, 2 + 6 + D(2) = 16} = 16. Answer 21 (projects 1, 2, 4, 6).

Rubric: what earns the points
  • state in words (what D means, which prefix, which limit)
  • index ranges
  • every base case
  • recurrence by cases on the last decision, with justification
  • evaluation order
  • answer cell
  • runtime (and space)
Where partial credit is lost

Only two cases (skip / take) cannot see the length of the run at the end; the case split must be on the last block. Missing D(2) as a base case makes the third case reference D(−1).

✍ WS.3DP write-up: chosen indices at least 3 apart, at most k chosen New drilldesign + prove
Source: New drill for these notes (weak spots)
Values vi ≥ 0 for i = 1..n. Choose at most k indices such that any two chosen indices differ by at least 3. Give the DP (state, ranges, base cases, recurrence with justification, order, answer, runtime) and evaluate it for v = (5, 1, 4, 6, 3, 2, 8), k = 2.
Show solution
  1. State. D(i, j) = max value from projects 1..i choosing at most j, pairwise gaps ≥ 3.
  2. Ranges. 0 ≤ i ≤ n, 0 ≤ j ≤ k.
  3. Base cases. D(0, j) = 0; D(i, 0) = 0; for i ∈ {1, 2} and j ≥ 1, D(i, j) = max{v1, …, vi} (only one index fits).
  4. Recurrence, i ≥ 3, j ≥ 1: D(i, j) = max{ D(i−1, j), vi + D(i−3, j−1) }. If i is taken, i−1 and i−2 are forbidden and one slot is used.
  5. Order. Increasing i; any order of j inside a row.
  6. Answer. D(n, k); time and space O(nk).

Run: D(7, 2) = 14 (indices 4 and 7: 6 + 8). Verified by brute force.

Rubric: what earns the points
  • state in words (what D means, which prefix, which limit)
  • index ranges
  • every base case
  • recurrence by cases on the last decision, with justification
  • evaluation order
  • answer cell
  • runtime (and space)
Where partial credit is lost

Writing D(i−2, ·) out of habit from the non-adjacent version; the jump must match the gap (i−3 for gap ≥ 3).

16.2 Correctness in both directions (E1 Q4c, −8)

Rule (i) solution → flow: one unit per chosen pair, check each capacity type and conservation, same value. (ii) integral flow → solution: integrality ⇒ 0/1 on unit edges, conservation ⇒ one choice each, capacities ⇒ limits, same value.
✍ WS.5Redo E1 Q4c: prove the student–project flow reduction (both directions) Past examguided proof
Source: Exam 1 Sec A (Sep 22, 2026), exams/Exam1_SecA_Soln.pdf p5
Network: source s, a vertex ai per student, pj per project, sink t; edges s→ai (cap 1), ai→pj (cap 1) for each compatible pair, pj→t (cap bj). Prove: (i) a valid assignment of q students gives a feasible flow of value q; (ii) an integral flow of value q gives a valid assignment of q students. You may use the integrality theorem. (8 pts)
Show solution

(i) Assignment ⇒ flow. For each assigned pair (i, j) send one unit along s → ai → pj → t.

  • s→ai: each student is assigned at most once, so flow ≤ 1.
  • ai→pj: used only for compatible pairs, at most once.
  • pj→t: at most bj students use project j, so flow ≤ bj.
  • Conservation holds at every ai and pj (each unit enters and leaves). Value = q.

(ii) Integral flow ⇒ assignment. Let f be integral with value q.

  • Each ai receives 0 or 1 unit (capacity 1, integral). By conservation a student receiving 1 sends it on exactly one edge ai→pj, which exists only for compatible pairs.
  • Project j receives at most bj units, since its only outgoing edge has capacity bj.
  • Assign i to j iff f(ai, pj) = 1: each student at most once, each project at most bj, and the number of assigned students = flow out of s = q.

Conclusion. Both maps preserve value, and an integral max flow exists (integer capacities), so max flow = max number of assigned students.

Rubric: what earns the points
  • (i) one unit per assigned pair along s→a_i→p_j→t
  • (i) capacities checked on all three edge types + conservation, value q
  • (ii) integrality ⇒ each student 0/1 unit, goes to exactly one compatible project
  • (ii) project load ≤ b_j, value q
  • conclude equality of optima via integrality
Where partial credit is lost

Real rubric line: −8 pts “Not Done”.

What I wrote: Nothing: the page is blank.

Root cause: Time. Also part (b) had no correct network, so (c) had nothing to stand on. Fix: write the (i)/(ii) headers first; each is a 3-bullet capacity check.

✍ WS.6Flow correctness: each student may join up to two projects New drillguided proof
Source: New drill for these notes (weak spots)
Same setting as E1 Q4, except each student may join up to two different compatible projects (never the same one twice); project j still takes at most bj students. Maximize the number of (student, project) memberships.
  1. Give the network (vertices, edges, capacities, s, t) and how to read the answer.
  2. Prove both directions: memberships ↔ integral flow of the same value.
  3. Instance: a1 compatible with p1, p2; a2 with p1; a3 with p1, p3; b = (2, 1, 1). Find the maximum.
Show solution

(a) Vertices s, t, ai, pj. Edges s→ai cap 2; ai→pj cap 1 for compatible pairs (cap 1 is what forbids joining the same project twice); pj→t cap bj. Compute an integral max flow; memberships = pairs with f(ai, pj) = 1.

(b) (⇒) Given a valid set of q memberships, push one unit along s→ai→pj→t for each. Student i carries ≤ 2 units (≤ 2 memberships), each middle edge ≤ 1 (distinct projects), project j ≤ bj. Conservation holds; value q.

(⇐) Given an integral flow of value q: each middle edge carries 0 or 1. Student i has inflow ≤ 2, so by conservation at most 2 of its middle edges carry 1, to distinct compatible projects. Project j's outflow ≤ bj, so its inflow ≤ bj. The flow-1 middle edges form q valid memberships (q = total flow across the middle layer).

(c) Max flow = 4: a1→p2, a3→p3, and p1 takes two of {a1, a2, a3} (e.g. a2, a3). It cannot exceed Σbj = 4. Verified by max-flow and brute force.

Rubric: what earns the points
  • vertices + s,t
  • capacities 2 / 1 / b_j with reasons
  • (⇒) memberships → flow, capacity checks
  • (⇐) integral flow → memberships
  • numeric answer with upper-bound check
Where partial credit is lost

Putting capacity 2 on the middle edges (allows the same project twice). Writing only (⇒).

✍ WS.7Edge-disjoint paths = max flow (both directions) New drillguided proof
Source: New drill for these notes (weak spots) (KT §7.6 Menger)
Directed graph G, vertices s ≠ t. Give every edge capacity 1. Prove: G has k edge-disjoint s→t paths ⇔ the network has an integral flow of value k.
Show solution

(⇒) Given k edge-disjoint paths, put flow 1 on every edge of every path. An edge lies on at most one path, so flow ≤ 1 = capacity. At an internal vertex each path that enters also leaves, so conservation holds. Value = number of paths leaving s = k.

(⇐) Induction on k. Let f be integral of value k ≥ 1, so every edge has f ∈ {0, 1}.

  1. Start at s and repeatedly follow an unused edge carrying flow 1. When we enter a vertex v ≠ t, conservation guarantees an outgoing flow-1 edge, so the walk can continue until t is reached.
  2. If the walk revisits a vertex, the closed part is a cycle: set its flow to 0 (value unchanged, still feasible) and continue. So we get a simple s→t path P of flow-1 edges.
  3. Set the flow on P to 0: still feasible, integral, value k − 1. By induction it gives k − 1 edge-disjoint paths, none using an edge of P (those now carry 0).

So max number of edge-disjoint paths = max flow value.

Rubric: what earns the points
  • (⇒) flow 1 on path edges, capacity + conservation
  • (⇐) find one path using conservation
  • cycle removal
  • remove path, induct
  • paths are edge-disjoint
Where partial credit is lost

Claiming “decompose the flow into paths” with no argument; forgetting cycles; only proving one direction.

16.3 Existence by an extremal choice (E1 Q2a, −6)

Rule Pick the maximum (or minimum, longest, last) object and check each neighbour, treating the boundary cases separately.
✍ WS.8Redo E1 Q2a: an interval with rising boundaries contains a peak Past examguided proof
Source: Exam 1 Sec A (Sep 22, 2026), exams/Exam1_SecA_Soln.pdf p3
A[1..n] distinct, A[0] = A[n+1] = −∞; i is a peak if A[i] > A[i−1] and A[i] > A[i+1]. Let [l, r] satisfy A[l] > A[l−1] and A[r] > A[r+1]. Prove [l, r] contains a peak of the original array (short existence proof, not an algorithm). (6 pts)
Show solution

Extremal choice. Let i ∈ [l, r] maximize A over the interval.

  1. Neighbours inside [l, r] are smaller: i is the maximum and entries are distinct.
  2. If i = l, the left neighbour l−1 is outside the interval, but A[l] > A[l−1] by hypothesis.
  3. If i = r, the right neighbour is smaller by A[r] > A[r+1].
  4. If l = r, both boundary conditions apply to the single index.

So both neighbours of i are smaller: i is a peak. ∎

Rubric: what earns the points
  • take the max over [l, r]
  • inside neighbours smaller (max + distinct)
  • boundary i = l via A[l] > A[l−1]
  • boundary i = r via A[r] > A[r+1]
  • l = r case
Where partial credit is lost

Real rubric line: −6 pts “Wrong answer”.

What I wrote: A hill-climbing story: “the intervals are monotonic… keep following the upward direction until L = R”, no definite element chosen, no boundary check.

Root cause: Missing the extremal-argument template: for existence, pick the max (or min, or the longest) and check its neighbours.

✍ WS.11Existence: discrete intermediate value New drillguided proof
Source: New drill for these notes (weak spots)
Integers f(1), …, f(n) with f(1) < 0 < f(n). Prove there is an index i with f(i) < 0 ≤ f(i+1). (This is the invariant behind binary search for a sign change.)
Show solution

Let i be the largest index with f(i) < 0. It exists because f(1) < 0, and i ≤ n − 1 because f(n) > 0. By maximality, f(i+1) is not negative, so f(i+1) ≥ 0. ∎

Rubric: what earns the points
  • extremal choice (largest index with f < 0)
  • existence and i ≤ n−1
  • maximality gives f(i+1) ≥ 0
Where partial credit is lost

Not checking that i + 1 ≤ n.

✍ WS.9Existence: local maximum in a block of grid columns New drillguided proof
Source: New drill for these notes (weak spots)
M is an n×n grid of distinct numbers; a cell is a local maximum if it is larger than each of its (up to 4) horizontal/vertical neighbours. Fix a column c < n, let r be the row of the largest entry of column c, and suppose M[r][c+1] > M[r][c]. Prove that columns c+1..n contain a local maximum of the whole grid.
Show solution

Let (r*, c*) be the position of the maximum of M over the block of columns c+1..n.

  1. Neighbours inside the block are smaller (maximum, distinct entries).
  2. The only neighbour that can lie outside the block is the left neighbour (r*, c), when c* = c+1. Then M[r*][c] ≤ M[r][c] (r is the row of column c's maximum) < M[r][c+1] (hypothesis) ≤ M[r*][c*] (maximum of the block).
  3. Neighbours above, below or to the right outside the grid do not exist.

So (r*, c*) is a local maximum of the whole grid. ∎ (This is the step behind the O(n log n) 2D peak finder.)

Rubric: what earns the points
  • max over the block
  • inside neighbours
  • the one outside neighbour via the chain of three inequalities
  • edges of grid
Where partial credit is lost

Forgetting the boundary neighbour, or comparing with M[r][c] for the wrong row: the chain needs “column maximum”.

✍ WS.10Existence: every finite DAG has a source New drillguided proof
Source: New drill for these notes (weak spots)
Prove that every directed acyclic graph with at least one vertex has a vertex of in-degree 0.
Show solution

Extremal choice. Paths in a DAG repeat no vertex (a repeat would be a cycle), so they have at most n vertices and a longest path P = v1→…→vℓ exists (ℓ ≥ 1; a single vertex is a path).

Suppose v1 had an in-edge (u, v1).

  • If u is on P, say u = vt, then v1→…→vt→v1 is a cycle: contradiction.
  • If u is not on P, then u→v1→…→vℓ is longer than P: contradiction.

So v1 has in-degree 0. ∎

Rubric: what earns the points
  • choose a longest path (and say why it exists)
  • case u on path → cycle
  • case u off path → longer path
Where partial credit is lost

“Keep walking backwards until you stop” without saying why the walk stops (finiteness + no repeats).

16.4 Flow networks with every parameter (E1 Q4b, −6)

sta1a2a3111p1p2b₁b₂1111studentsprojects
s → student (cap 1), student → compatible project (cap 1), project j → t (cap b_j). Assign a_i to p_j iff f(a_i, p_j) = 1.
How to read this figure The Exam 1 Q4b network on a small instance: s on the left, one vertex per student, one per project, t on the right. Every edge from s has capacity 1, every compatible pair capacity 1, and project j's edge into t carries the label bj: that label is the component your answer was missing.
✍ WS.12Redo E1 Q4b: build the student–project flow network Past examdesign + prove
Source: Exam 1 Sec A (Sep 22, 2026), exams/Exam1_SecA_Soln.pdf p5
n students, k projects; project j accepts at most bj students (bj ≥ 0 integer); m compatible student–project pairs; each student gets at most one compatible project. Construct a directed flow network whose max-flow value equals the maximum number of assigned students. Specify vertices, edges, capacities, source and sink; say how to recover an assignment from an integral max flow. (6 pts)
Show solution
  • Vertices: source s, sink t, one vertex ai per student, one vertex pj per project (n + k + 2 vertices).
  • Edges and capacities: s → ai with capacity 1 (each student at most once); ai → pj with capacity 1 for each compatible pair; pj → t with capacity bj.
  • Algorithm: integral max flow (e.g. Ford–Fulkerson, O(m′·|f|) with |f| ≤ n; integer capacities give an integral optimum).
  • Read-off: assign student i to project j exactly when f(ai, pj) = 1.
Rubric: what earns the points
  • vertices named (s, t, students, projects)
  • s→a_i cap 1
  • a_i→p_j cap 1 for compatible pairs
  • p_j→t cap b_j
  • integral max flow + read-off rule
Where partial credit is lost

Real rubric line: −6 pts “Incorrect or not readable”. Grader: “There is no mention of student or project here?”

What I wrote: An augmenting-path matching algorithm (unmatched edges A→B, matched B→A, BFS/DFS from a super source, O(n(n+m))) with “capacities will be 1”: the bj never appear.

Root cause: Answered part (a)'s problem (bj = 1 matching) instead of modelling the general one. Fix: the FLOW checklist, vertices / edges / capacities / s, t / read-off, with every input parameter (here bj) appearing as a capacity.

✍ WS.13Flow model: doctors and days New drilldesign + prove
Source: New drill for these notes (weak spots)
Doctors d1, d2, d3 and days 1..5. Doctor d1 is available on days {1, 2, 3} and works at most 2 days; d2: days {1, 2}, at most 1 day; d3: days {3, 4}, at most 1 day. Each day needs at most one doctor. Maximize the number of covered days.
  1. Give the network in the FLOW checklist format (vertices, edges, capacities, s, t, read-off) for general input.
  2. Find the maximum on this instance and a min cut that certifies it.
Show solution

(a) Vertices s, t, one per doctor, one per day. s → doctor i with capacity ci (max days); doctor i → day d with capacity 1 if available; day d → t with capacity 1. Integral max flow; doctor i covers day d iff f(i, d) = 1.

(b) Max flow = 4: d1 → days 1 and 3, d2 → day 2, d3 → day 4. Day 5 has no available doctor, so the 5 day→t edges can carry at most 4 (cut: S = {s, all doctors, days 1–4}, crossing edges = day 1–4 → t, capacity 4). Verified by max-flow and brute force.

Rubric: what earns the points
  • vertices
  • three capacity types
  • s and t
  • read-off rule
  • value + certificate
Where partial credit is lost

Capacities missing on s→doctor edges (that is where “at most ci days” lives).

✍ WS.14Flow model with a gadget layer: TAs, sections and time slots New drilldesign + prove
Source: New drill for these notes (weak spots)
TAs 1..p and recitation sections 1..r; section q meets in time slot σ(q). TA i lists the sections they are qualified for, may lead at most 2 sections, and cannot lead two sections in the same slot. Each section needs exactly one TA. Design a flow network that decides whether all sections can be staffed, and prove the slot constraint is enforced.
Show solution
  • Vertices: s, t; a vertex Ti per TA; a vertex (i, σ) per TA i and slot σ in which i is qualified for some section; a vertex Qq per section.
  • Edges: s → Ti cap 2; Ti → (i, σ) cap 1; (i, σ) → Qq cap 1 if i is qualified for q and σ(q) = σ; Qq → t cap 1.
  • Decision: all sections staffed ⇔ max flow = r. Read-off: TA i leads q iff f((i, σ(q)), Qq) = 1.

Why slots are enforced: every unit from Ti to sections in slot σ passes through (i, σ), whose only incoming edge has capacity 1, so at most one section per slot per TA. Conversely a valid staffing routes each (TA, section) pair through its own (i, σ(q)) vertex, using it at most once. Size: O(p·#slots + r) vertices, so polynomial.

Rubric: what earns the points
  • vertices incl. gadget layer
  • capacities 2 / 1 / 1 / 1
  • decision rule (= r)
  • why the gadget enforces one-per-slot
  • both directions sketched
  • size polynomial
Where partial credit is lost

Putting the slot limit on the TA vertex (cannot distinguish slots), or forgetting the read-off rule.

16.5 Proof chains that use the earlier part (E2 Q3b, −6)

Rule Before writing, list the facts the chain must use (hint, part (a), definitions). Here: the sum has k + 1 terms; part (a) says the last one is the smallest.
✍ WS.16Check the gradient-norm chain on a concrete function New drillcalculation
Source: New drill for these notes (weak spots)
f(x, y) = ½(x² + 4y²) is convex and β-smooth with β = 4, minimum f* = 0 at the origin. Run xk+1 = xk − ¼∇f(xk) from x0 = (2, 1).
  1. Compute ‖∇f(xk)‖² for k = 0, 1, 2, 3 and check they are non-increasing (part (a)).
  2. Check the hint Σi=03‖∇f(xi)‖² ≤ 2β(f(x0) − f*), and the bound of part (b) at k = 3.
  3. What goes wrong at k = 0 if you divide by k instead of k + 1?
Show solution

∇f(x, y) = (x, 4y), so xk+1 = (¾xk, yk − yk) = (¾xk, 0). Iterates: (2,1), (3/2, 0), (9/8, 0), (27/32, 0).

(a) ‖∇f(xk)‖² = 20, 9/4, 81/64, 729/1024: non-increasing ✓.

(b) f(x0) = ½(4 + 4) = 4, so 2β(f(x0) − f*) = 32. Sum = 24809/1024 ≈ 24.2 ≤ 32 ✓. Part (b) at k = 3: ‖∇f(x3)‖² ≤ 32/4 = 8; actual 729/1024 ✓.

(c) At k = 0 the sum has one term; dividing by k = 0 makes no sense (division by zero). The k + 1 counts the terms i = 0..k.

Rubric: what earns the points
  • gradient formula
  • iterates
  • four squared norms
  • hint check
  • part (b) check at k=3
  • k vs k+1 explained
Where partial credit is lost

Using η = 1/β with the wrong β (here β = 4 is the largest curvature, from the 4y² term ×½×2).

✍ WS.15Redo E2 Q3b: gradient norm after k steps Past examguided proof
Source: Exam 2 (Oct 27, 2026), exams/Exam2_Soln.pdf p9
f convex and β-smooth on ℝn, xk+1 = xk − (1/β)∇f(xk). Part (a) proved ‖∇f(xk+1)‖ ≤ ‖∇f(xk)‖. Prove ‖∇f(xk)‖ ≤ √(2β(f(x0) − f(x*))/(k+1)). Hint: you may use Σi=0k ‖∇f(xi)‖² ≤ 2β(f(x0) − f(x*)). (6 pts)
Show solution
  1. Count terms. The sum Σi=0k has k + 1 terms, each ≥ the smallest: Σ ≥ (k+1)·min0≤i≤k ‖∇f(xi)‖².
  2. Use part (a). The norms are non-increasing, so the minimum is the last one: min = ‖∇f(xk)‖².
  3. Use the hint. (k+1)‖∇f(xk)‖² ≤ Σ ≤ 2β(f(x0) − f(x*)).
  4. Finish. Divide by k + 1 and take square roots: ‖∇f(xk)‖ ≤ √(2β(f(x0) − f(x*))/(k+1)). ∎
Rubric: what earns the points
  • sum ≥ (k+1)·min
  • min is the last term by part (a)
  • chain with the hint
  • divide by k+1, square root
Where partial credit is lost

Real rubric line: −6 pts “Not Done / Incorrect” (regrade denied: “a good first step, but more work was needed”).

What I wrote: (1/k)Σ‖∇f(xi)‖² ≤ 2β(f(x0) − f*)/k “by Jensen”: an average, never linked to the last iterate; divided by k, not k + 1.

Root cause: Did not use part (a). Rule: a stated earlier part is there to be used; list which given facts must appear before writing.

✍ WS.17Chain lemmas: count the terms, use the earlier part New drillguided proof
Source: New drill for these notes (weak spots)
  1. Let a0 ≥ a1 ≥ … ≥ 0 with Σi=0k ai ≤ C. Prove ak ≤ C/(k+1). What do you get if instead the given fact is Σi=1k ai ≤ C?
  2. (Strongly convex GD.) Suppose part (a) of some exam question proved gk+1 ≤ (1 − α/β) gk, where gk = f(xk) − f* ≥ 0 and 0 < α ≤ β. Prove gk ≤ (1 − α/β)k g0 ≤ e−kα/β g0. Check the first inequality numerically for f = ½(x² + 4y²) (α = 1, β = 4) from (2, 1).
Show solution

(a) The k + 1 terms are each ≥ ak (monotone), so (k+1)ak ≤ Σ ≤ C, i.e. ak ≤ C/(k+1). With Σi=1k (k terms) the same argument gives ak ≤ C/k. The denominator is the number of terms.

(b) Induction on k. Base k = 0: g0 ≤ g0. Step: gk+1 ≤ (1 − α/β)gk ≤ (1 − α/β)(1 − α/β)kg0, using the given part and then the hypothesis (1 − α/β ≥ 0 keeps the direction). Then 1 − u ≤ e−u for all u gives (1 − α/β)k ≤ e−kα/β.

Numeric check: g0..3 = 4, 9/8, 81/128, 729/2048; ratios g1/g0 = 9/32 and g2/g1 = 9/16, both ≤ 3/4 ✓.

Rubric: what earns the points
  • (a) each term ≥ last term
  • (a) correct count k+1 vs k
  • (b) induction base + step using the given part
  • (b) 1−u ≤ e^{−u}
  • numeric check
Where partial credit is lost

Dividing by the wrong count; in (b), proving the contraction again instead of citing the given part.

17 · Ledger: every point you lost, and where to redo it weak spots · 26 parts · 105.5 raw points

▸ Collapsed: click to expand▾ Click to collapse
The idea in one sentenceEach lost part, largest first, with the rubric line, its pattern (§15) and the card in these notes where you redo it; a row is done when its redo card is rated Got it (cold, on time, every rubric item).
#PartPtsRubric linePatternRedo here
1E1 Q3b DP recurrence + justification10EmptyDPWS.1 U1A.31
2E1 Q4c Flow correctness (i) and (ii)8Not doneIFFWS.5 U1B.32
3E1 Q2a Peak exists in [l, r]6Wrong answerEXISTWS.8 U1A.16
4E1 Q4b Students → projects network with bj6Incorrect or not readable; “no mention of student or project here?”FLOWWS.12 U1B.32
5E2 Q3b ‖∇f(xk)‖ bound from the hint6Not done / incorrectCHAINWS.15 WS.16
6E3 Q3b VC ≤ SC, both directions6AttemptIFF§15.3; full redo in Unit 3
7E1 Q1c Bounds on OPT from (1 − ε)5Lower and upper bound missing/incorrectBOUNDSU1A.40 EC.12
8E1 Q1f Add 7 to every edge: shortest paths?5Wrong answerCEXU1B.8
9E2 Q1b Strict primal constraint ⇒ dual variable?5Chose “strictly positive”LPEC.20; Unit 2
10E2 Q4.4 Tight instance for 1/k rounding5BlankCEXUnit 2 (§35–39)
11E3 Q1f Expected samples until a PhD5IncorrectPROBEC.7 EC.18 §15.2
12E2 Q1c Farkas select-all4Selected one of three true optionsLPEC.51; Unit 2
13E2 Q1f Bounds from a 2-approx VC + matching4IncorrectBOUNDSEC.39 §15.1
14E2 Q4.1 ILP for set cover4Only the objectiveFORMUnit 2 (§35–39)
15E1 Q1d Two-step MDP policy + expectations3.5Expectations missing/wrongPROBU1A.45 EC.6 §15.2
16E1 Q3a DP state, ranges, base cases, answer3Base cases −1, final answer −2DPU1A.31 WS.2
17E2 Q3c ‖∇f(xk)‖ ≤ βD/√(k+1)3Used f(x₀) − f* ≤ DCHAINUnit 2 (§35–39)
18E2 Q4.3 1/k-threshold rounding is a k-approx3Major errorCHAINUnit 2 (§35–39)
19E3 Q2c max{E_T, E_F} ≥ E[Y | …], how to compute3Missing details on how to computePROBEC.11 EC.44
20E1 Q3c Fill order, time, space2Incorrect orderDPU1A.31
21E2 Q1d One projected GD step2Failing to projectCALCEC.2
22E2 Q2c Family where greedy IS is exactly OPT/Δ2Incorrect (ratio 1; only Δ = 2)CEXUnit 2 (§35–39)
23E3 Q3a Construct the SC instance2Incorrect/missing U (should be the set of edges)FORM§15.3; Unit 3
24E2 Q2b Greedy IS is a Δ-approx1.5Proved Δ + 1, not ΔOFF1Unit 2 (§35–39)
25E1 Q2b Peak recursion: m vs m + 11“needs to be m+1, otherwise infinite recursion on 2 elements”OFF1U1A.17
26E3 Q2b Random assignment 7/8 even if unsatisfiable0.5Didn't say what happens when OPT < mBOUNDSUnit 3 (§40–49)

Rows marked "Unit 2" or "Unit 3" get their redo card when those sections are built (Sun–Mon); until then use the clean paper and solution page listed in START_HERE §1.

Summary card
  • Rows 1–6 (42 pts) are all frames left empty or incomplete: DP, both directions, extremal, flow components, chain.
  • Rows 7–15 (40.5 pts) are short answers or short parts: both bounds, counterexamples, slackness direction, Σ prob × value.

20 · Proof techniques Lec 1–2 · HW1 · used in every unit

▸ Collapsed: click to expand (3 subsections)▾ Click to collapse

Unit 1 starts here. Every long answer on the final is a proof of some kind: correctness of a D&C/DP algorithm, an exchange argument, both directions of a reduction. This section is the toolbox; each later section applies it.

20.1 Induction and strong induction

Warm-up: try from memory first (fine to miss)
What exactly must the induction step prove?
For every k ≥ base: if P(k) holds (the hypothesis) then P(k+1) holds. For strong induction: if P(m) holds for all base ≤ m ≤ k, then P(k+1).
When do you need strong induction instead of ordinary induction?
When the step uses a case that is not exactly k, e.g. T(⌊n/2⌋) and T(⌈n/2⌉) in a recurrence, or any split n = a + b.
Why can't you induct on the statement “T(n) = O(n)”?
O(·) hides a constant; the step can silently make the constant grow with n. You must induct on an explicit inequality T(m) ≤ K·g(m) with K fixed in advance.
The idea in one sentenceProve the smallest case directly, then prove that every case follows from the smaller ones; together they cover every case, like dominoes.

Template that earns full credit.

  1. Statement P(n), written as an explicit (in)equality with all constants fixed (e.g. “T(m) ≤ K·m log₂ m for every integer m ≥ 2”, with K chosen below).
  2. Base case(s): verify P at the smallest value(s), numerically.
  3. Induction hypothesis: “assume P(m) for all m with base ≤ m < n” (strong) or “assume P(k)” (ordinary).
  4. Step: derive P(n), and point to the exact place where the hypothesis is used and on which smaller value(s).
  5. Conclusion: “by induction, P(n) holds for all n ≥ base.”

Strong induction is the same with a bigger hypothesis. It is what recurrences with ⌊n/2⌋, ⌈n/2⌉ or uneven splits need, and it removes any “n is a power of 2” assumption.

Worked example (Exam 1A Q1a) Claim Σi=0n 2i = 2n+1 − 1. Hypothesis: true for k. Step: Σi=0k+1 2i = (2k+1 − 1) + 2k+1 = 2k+2 − 1, which is the claim at k + 1. Check at k = 3: 1+2+4+8+16 = 31 = 25 − 1.

Takeaway: split off the last term, use the hypothesis on the rest, simplify to the claim for k + 1. The rubric took a point for “did GP instead” (re-deriving the formula instead of using the hypothesis).

20.2 Broken-proof patterns (spot the error)

The idea in one sentenceA wrong induction proof always has one false sentence; find the smallest case where the step's assumptions fail, or the place where a hidden quantity changes.
PatternWhat goes wrongHow to spot it
Missing/false base caseA correct step from a false start proves nothing (U1A.3).Plug in the base value.
Step fails at the smallest nThe step relies on an assumption (e.g. a, b < n) that is false at the first step after the base (U1A.4).Run the step by hand at the base + 1.
Growing constant“O(n−1) + n = O(n)”: the hidden constant increases each step (U1A.2).Rewrite O(·) with an explicit fixed constant.
Hypothesis applied to the wrong sizeThe step uses P(n) or P(n+1) while proving P(n).Check every use is on a strictly smaller value.
Circular / proving the converseAssumes the conclusion, or proves Q ⇒ P instead of P ⇒ Q.Write “want: …” and “given: …” separately.
Only one direction of an iffProves P ⇒ Q twice (directly and by contrapositive, U1A.5 option B).Write headers (⇒) and (⇐) first.
Traps
  • A verdict (“the proof is wrong”) earns nothing without naming the exact faulty sentence and why it fails.
  • Don't “fix” the claim when asked where the mistake is; locate the mistake first.

20.3 The other tools: invariants, contradiction, exchange, extremal, both directions

The idea in one sentenceEach technique matches a question shape: “the loop is correct” → invariant; “an optimal solution has property X” → exchange; “something exists” → extremal choice; “A iff B” → two separate directions.
  • Loop invariant (initialization, maintenance, termination): a statement true before every iteration; at exit it gives correctness (U1A.7).
  • Contradiction / minimal counterexample: assume the claim fails, take the smallest failure, derive a smaller one or an impossibility (used for Dijkstra in §26 and Berge in §28).
  • Exchange argument (greedy correctness): take any optimal solution that differs from the greedy one, swap one piece toward greedy without making it worse, repeat (U1A.6; MST cut property in §27).
  • Extremal choice (existence): pick the maximum/minimum object and check it has the property (Exam 1A Q2a: the maximum entry of an interval is a peak; you lost 6 points there, see §22).
  • Both directions for iff / reductions / flow models: (⇒) build a solution of the second problem from one of the first with the same value; (⇐) the reverse. Each direction is separate work (Exam 1A Q4c and Exam 3 Q3b cost you 14 points).
Why is it done this way?
Why does an exchange argument compare costs before and after the swap?Because the whole proof rests on “the swap never increases cost”. If you only describe the swap, the grader can't see that optimality is preserved.
Why is “take the maximum” a good existence strategy?A maximum automatically beats everything near it, which is what local properties (peak, light edge, …) ask for. You only need to check the boundary cases.
Why can't the contrapositive of P ⇒ Q serve as the second direction?It is logically the same statement as P ⇒ Q. The converse Q ⇒ P (or its contrapositive not P ⇒ not Q) is the other direction.
Summary card
  • Induction: explicit P(n) with fixed constants · base checked numerically · IH quantified · step uses IH on smaller values · conclusion.
  • Spot-the-error: test base; run the step at base + 1; look for growing hidden constants; check IH is applied to smaller sizes.
  • Invariant: init · maintenance · termination. Exchange: inverted pair → swap → cost doesn't increase → optimal can be made greedy. Iff: (⇒) and (⇐), each value-preserving.
Recall check
List the five parts of a full-credit induction proof.
Explicit statement P(n) (constants fixed) · base case · hypothesis (for all smaller m, if strong) · step that uses the hypothesis on smaller values · conclusion.
What is the first thing to test when asked “where is the mistake?” in an induction proof?
The base case, then the step at the smallest n where it's applied (base + 1): does every assumption the step uses actually hold there?
What are the three parts of a loop-invariant proof?
Initialization (true before the first iteration), maintenance (preserved by each iteration), termination (at exit the invariant gives the result).
To prove P ⇔ Q, which pairs of implications suffice?
P ⇒ Q together with Q ⇒ P, or with its contrapositive (not P) ⇒ (not Q). P ⇒ Q with (not Q) ⇒ (not P) is one direction twice.
✍ U1A.1Induction step for a geometric sum (Exam 1A Q1a) Past examshort answer
Source: exams/Exam1_SecA_Soln.pdf p1 (paper p2)
The claim is Σi=0n 2i = 2n+1 − 1 for every integer n ≥ 0. The base case n = 0 has been checked. Induction hypothesis: for some integer k ≥ 0, Σi=0k 2i = 2k+1 − 1. Prove the claim for n = k + 1 (only the step).
Show solution

Separate the last term, then apply the hypothesis to the remaining sum:

Σi=0k+1 2i = (Σi=0k 2i) + 2k+1 = (2k+1 − 1) + 2k+1 = 2·2k+1 − 1 = 2k+2 − 1,

which is the claim for n = k + 1. Check at k = 3: 1 + 2 + 4 + 8 + 16 = 31 = 25 − 1 ✓.

Where partial credit is lost
  • Rubric (4 pts): “Did GP instead” cost 1 point. You must use the hypothesis, not re-derive the geometric-series formula.
  • Say explicitly which term you split off and where the IH is used.
✍ U1A.2Spot the error: “1 + 2 + ⋯ + n = O(n)” New drillshort answer
Source: New drill (classic broken-proof pattern; Lec 2 board warns that K must be fixed)

“Claim: S(n) = 1 + 2 + ⋯ + n = O(n). Proof by induction. Base: S(1) = 1 = O(1). Step: assume S(n−1) = O(n−1). Then S(n) = S(n−1) + n = O(n−1) + n = O(n). ∎”

The claim is false (S(n) = n(n+1)/2). Find the exact faulty step and explain it in 1–2 lines.

Show solution

The error: “O(·)” is not a statement you can induct on. The step silently lets the hidden constant grow. Written with constants, the hypothesis is S(n−1) ≤ c(n−1) for a fixed c. The step then needs S(n) ≤ c(n−1) + n ≤ cn, i.e. n ≤ c, which fails once n > c. Each step pays “one more n”, so after n steps the constant is about n: the bound is really n·n.

Fix: always induct on an explicit inequality with a constant fixed before the induction (e.g. “T(m) ≤ K·m log m for all m < n”).

Where partial credit is lost
  • Saying “the claim is false” without naming the step earns nothing: point to “O(n−1) + n = O(n)” and say the constant changes with n.
  • Don't blame the base case; it is fine.
✍ U1A.3Spot the error: a step without a base New drillshort answer
Source: New drill

“Claim: 2 + 4 + ⋯ + 2n = n² + n + 1 for all n ≥ 1. Step: if 2 + ⋯ + 2k = k² + k + 1, then 2 + ⋯ + 2(k+1) = k² + k + 1 + 2k + 2 = (k+1)² + (k+1) + 1. ∎”

Is the claim true? Is the step correct? What is wrong?

Show solution

The step's algebra is correct: k² + 3k + 3 = (k+1)² + (k+1) + 1. But the claim is false: at n = 1 the left side is 2 and the right side is 3. The proof never checked a base case, and a correct step from a false base proves nothing. (The true identity is 2 + ⋯ + 2n = n² + n.)

Where partial credit is lost
  • Always check the base case numerically, even when the step looks right.
✍ U1A.4Spot the error: strong induction with too-small n New drillshort answer
Source: New drill (classic)

“Claim: 5n = 0 for every integer n ≥ 0. Strong induction. Base: 5·0 = 0. Step: let n ≥ 1 and write n = a + b with 0 ≤ a, b < n. By the hypothesis 5a = 0 and 5b = 0, so 5n = 5a + 5b = 0. ∎”

Find the first n where the step breaks and say why.

Show solution

The step breaks at n = 1. It needs a, b < n with a + b = n. For n = 1 the only splits are 1 = 0 + 1 and 1 = 1 + 0, and both use b = 1 or a = 1, which is not smaller than n. So the hypothesis does not apply, and 5·1 = 0 is never justified. For n ≥ 2 the split works (e.g. a = 1, b = n − 1), but it builds on the false case n = 1.

General check: test the step at the smallest n where it is used (the jump from the base to the next value). That first step is where hidden assumptions most often fail.

Where partial credit is lost
  • Name the exact n where the step fails and the exact assumption that fails (“b < n” is false).
✍ U1A.5Logic of proofs (select all) New drillshort answer
Source: New drill
Select ALL statements that are valid proof strategies. Justify each in one line.
  1. To prove P ⇔ Q it suffices to prove P ⇒ Q and (not P) ⇒ (not Q).
  2. To prove P ⇔ Q it suffices to prove P ⇒ Q and (not Q) ⇒ (not P).
  3. One counterexample disproves “for all x, P(x)”.
  4. Checking P(x) for many examples proves “for all x, P(x)”.
Show solution
  • A valid. (not P) ⇒ (not Q) is the contrapositive of Q ⇒ P, so both directions are covered.
  • B invalid. (not Q) ⇒ (not P) is the contrapositive of P ⇒ Q: the same direction twice; Q ⇒ P is never shown.
  • C valid. A single x with P(x) false makes the universal statement false.
  • D invalid. Finitely many examples never prove a universal claim; the next x could be a counterexample.

Answer: A and C.

Where partial credit is lost
  • This is exactly the “both directions” trap that cost 14 points on your exams: B looks like two directions but is one.
✍ U1A.6Exchange argument: shortest job first New drillguided proof
Source: New drill (exchange-argument template used for MST in §27)

n jobs with lengths p1, …, pn run one after another on one machine. The completion time of a job is when it finishes. Minimize the sum of completion times.

  1. For lengths (3, 1, 2) in that order, compute the sum of completion times. Then compute it for the sorted order.
  2. Prove that sorting by length (shortest first) is optimal, using an exchange argument.
Show solution

(a) Order 3, 1, 2: completions 3, 4, 6, sum 13. Sorted 1, 2, 3: completions 1, 3, 6, sum 10.

(b) Exchange argument. Take any order that is not sorted. Then some adjacent pair has a longer job x immediately before a shorter job y (px > py). Swap them.

  1. Jobs before the pair and after the pair finish at exactly the same times (the pair occupies the same total time px + py).
  2. Before the swap the pair contributes (t + px) + (t + px + py); after, (t + py) + (t + py + px), where t is the start time of the pair.
  3. The change is py − px < 0, so the swap strictly lowers the sum.

So any unsorted order can be strictly improved and is not optimal. An optimal order exists (finitely many orders), so it must be sorted; all sorted orders (ties in any order) have the same sum. ∎

Rubric: what earns the points
  • (a) both sums computed
  • identify an adjacent inverted pair
  • show other jobs unchanged
  • compute the change p_y − p_x < 0
  • conclude optimal ⇒ sorted
Where partial credit is lost
  • The exchange must compare the cost before and after the swap explicitly and show it does not increase.
  • State why the other jobs are unaffected.
  • Finish the argument: “any non-sorted order can be improved ⇒ an optimal order is sorted”.
✍ U1A.7Loop invariant: binary search New drillguided proof
Source: New drill

Binary search for x in a sorted array A[1..n]: l ← 1, r ← n; while l ≤ r: m ← ⌊(l+r)/2⌋; if A[m] = x return m; if A[m] < x then l ← m+1 else r ← m−1. Return “not found”.

State a loop invariant and use it to prove that “not found” is correct. Then give the runtime.

Show solution

Invariant: if x occurs in A, then it occurs in A[l..r].

  1. Initialization: l = 1, r = n, so A[l..r] is the whole array.
  2. Maintenance: if A[m] < x, then every entry at index ≤ m is ≤ A[m] < x (sorted), so x is not in A[l..m]; setting l = m+1 keeps the invariant. The case A[m] > x is symmetric.
  3. Termination: the loop stops with l > r, i.e. A[l..r] is empty. By the invariant, x is not in A, so “not found” is correct.

Runtime: r − l + 1 at least halves each iteration, so there are at most ⌊log₂ n⌋ + 1 iterations: O(log n).

Rubric: what earns the points
  • invariant stated precisely
  • initialization
  • maintenance (both branches)
  • termination ⇒ correctness
  • runtime O(log n)
Where partial credit is lost
  • An invariant proof needs all three parts: initialization, maintenance, termination (what the invariant gives at exit).

21 · Asymptotics and recurrences Lec 1–2 · HW1 #1

▸ Collapsed: click to expand (2 subsections)▾ Click to collapse

21.1 O, Ω, Θ, o and input size

Warm-up: try from memory first
Define f = O(g) precisely.
There exist constants c > 0 and n₀ such that f(n) ≤ c·g(n) for all n ≥ n₀.
Order these: n log n, (log n)5, n0.1, 2n, n!, n².
(log n)5 ≺ n0.1 ≺ n log n ≺ n² ≺ 2n ≺ n!
What is the input size of a single integer N?
Θ(log N) bits. “Polynomial time” means polynomial in the number of bits.
The idea in one sentenceAsymptotic notation compares growth rates while ignoring constant factors and small inputs, and "polynomial" is always measured against the number of bits of the input.
SymbolMeaningLimit test (when lim f/g exists)
f = O(g)∃ c, n₀: f(n) ≤ c·g(n) for n ≥ n₀ (upper bound)lim f/g < ∞
f = Ω(g)g = O(f) (lower bound)lim f/g > 0
f = Θ(g)both O and Ω (tight)0 < lim f/g < ∞
f = o(g)for every c > 0, eventually f < c·glim f/g = 0
f = ω(g)g = o(f)lim f/g = ∞
  • Growth ladder: 1 ≺ log log n ≺ log n ≺ (log n)c ≺ nε ≺ n ≺ n log n ≺ nc ≺ 2n ≺ n! ≺ nn. Logs lose to every positive power; powers lose to every exponential dn with d > 1 (HW1 #1).
  • Rewrite with base 2 to compare: ab = 2b log a. Example: (log n)log n = nlog log n.
  • Input size: an integer N takes Θ(log N) bits, so an algorithm doing √N or N steps on input N is exponential in the input length (trial division, knapsack's O(nB): pseudo-polynomial).
Traps
  • O-bounds don't survive division: f′ = O(f), g′ = O(g) does not give f′/g′ = O(f/g) (take g′ = 1/n). Θ-bounds do.
  • “Sublinear in N” is not “polynomial”: measure against bits.
Recall check
For which d is n5 = O(dn)?
Exactly d > 1 (L'Hôpital 5 times gives 5!/((ln d)5 dn) → 0; for d ≤ 1 the right side stays ≤ 1).
Is (log n)100 = O(n0.01)?
Yes: logs lose to every positive power (HW1 #1 part 2).
✍ U1A.8Is trial division polynomial? (Practice Exam U1 Q1.2) Practice examshort answer
Source: practice-exams/Practice_Exam_Unit_1_Solutions.pdf Q1.2
Given n ≥ 4, we test primality by checking divisibility by all integers 2 ≤ i ≤ ⌊√n⌋. This takes O(√n) divisions. Is this a polynomial-time algorithm? Justify.
Show solution

No. The input is the number n, written in Θ(log n) bits. Let L = log₂ n be the input length. Then √n = 2L/2, which is exponential in L. Example: a 64-bit number needs up to 2^32 ≈ 4.3 billion divisions.

Where partial credit is lost
  • “O(√n) is sublinear, so it's polynomial” is the trap: polynomial means polynomial in the number of bits.
✍ U1A.9k = log n ⇒ kk = Θ(n)? (Practice Exam U1 Q1.3) Practice examshort answer
Source: practice-exams/Practice_Exam_Unit_1_Solutions.pdf Q1.3
Suppose k = log n. True or false: kk = Θ(n). Justify.
Show solution

False. kk = (log n)log n = 2(log n)(log log n) = nlog log n, which grows faster than any fixed power of n. So n = O(kk) but not the reverse. Check: n = 2^16 = 65,536 gives kk = 16^16 = 2^64, far larger than n.

Where partial credit is lost
  • Rewrite with a common base (ab = 2b log a) before comparing growth rates.
✍ U1A.15log(n!) = Θ(n log n) Lectureshort answer
Source: Lec 1 board p3 + algo-part1-notes/Grad Algorithms.pdf (your notes)
Prove log(n!) = Θ(n log n): give both the upper and the lower bound.
Show solution

Upper: n! = 1·2⋯n ≤ n·n⋯n = nn, so log n! ≤ n log n.

Lower: keep only the largest n/2 factors, each at least n/2: n! ≥ (n/2)n/2, so log n! ≥ (n/2) log(n/2) = Ω(n log n).

Check at n = 16: 24 ≤ log₂ 16! ≈ 44.3 ≤ 64.

Where partial credit is lost
  • Θ needs both directions; the lower bound is the one people skip.
✍ U1A.10For which c, d: nc = O(dn) and (log n)c = O(nd)? (HW1 #1) HWguided proof
Source: algo-part1-notes/HW1_Solutions.pdf §1.2
Find all constants c, d > 0 for which (1) nc = O(dn), (2) (log n)c = O(nd). Prove your answers. (c, d need not be integers.)
Show solution

(1) Exactly when d > 1 (any c > 0). Reduce to integer c: nc ≤ n⌈c⌉, so it suffices to handle ⌈c⌉. Apply L'Hôpital c times: lim nc/dn = lim c·nc−1/(ln d · dn) = ⋯ = lim c!/((ln d)c dn) = 0 < ∞, so nc = O(dn). For d ≤ 1, dn ≤ 1 while nc → ∞, so no constant works.

(2) For all c, d > 0. Again reduce to integer c. Each L'Hôpital step: d/dn (log n)c = c (log n)c−1/n (up to the constant 1/ln 2), and d/dn nd = d nd−1; the ratio becomes c (log n)c−1/(d nd). After c steps: c!/(dc nd) → 0. Logs lose to every positive power, however small d is.

Rubric: what earns the points
  • (1) answer d > 1, any c
  • (1) limit/L'Hôpital proof
  • (1) failure for d ≤ 1
  • (2) answer all c, d > 0
  • (2) proof
  • non-integer c handled
Where partial credit is lost
  • Give the full set of constants (“d > 1”, “all c, d”), and prove both that it works there and fails elsewhere (d ≤ 1).
  • Handle non-integer c (round up).

21.2 Solving recurrences: master theorem, recursion trees, induction

Warm-up: try from memory first
State the master theorem (course form).
T(n) = aT(n/b) + Θ(nd), a ≥ 1, b > 1, d ≥ 0. If d > logb a: Θ(nd). If d = logb a: Θ(nd log n). If d < logb a: Θ(nlogb a).
Solve T(n) = T(n/5) + T(7n/10) + Θ(n).
Θ(n): the fractions sum to 9/10 < 1, so level costs shrink geometrically.
Solve T(n) = T(n/3) + T(2n/3) + Θ(n).
Θ(n log n): the fractions sum to exactly 1, so each level costs ~n over Θ(log n) levels.
The idea in one sentenceA recurrence's cost is the sum over the levels of its recursion tree; compare how the per-level cost grows or shrinks, and the biggest part (root, all levels equally, or leaves) wins.

Master theorem (course form). For T(n) = a·T(n/b) + Θ(nd) with T(1) = Θ(1): level i has ai subproblems of size n/bi, so it costs ai(n/bi)d = nd(a/bd)i. The ratio a/bd decides:

Compare d with logb aPer-level costAnswerExample
d > logb ashrinks: root dominatesΘ(nd)T(n/2) + n = Θ(n)
d = logb aequal on all logb n levelsΘ(nd log n)2T(n/2) + n = Θ(n log n)
d < logb agrows: leaves dominateΘ(nlogb a)4T(n/2) + n = Θ(n²)
n1 × cn = cnn/2n/22 × c·n/2 = cnn/4n/4n/4n/44 × c·n/4 = cnn/8n/8n/8n/8n/8n/8n/8n/88 × c·n/8 = cn⋮ log₂ n levels, then n leaves of cost Θ(1) each: Θ(n)level total
Recursion tree for T(n) = 2T(n/2) + cn: every level costs cn, there are log₂ n levels, so T(n) = Θ(n log n).
How to read this figure Each row is one level of merge sort's recursion: the number of subproblems doubles while each halves, so every row costs cn. With log₂ n rows the total is cn log₂ n. When the rows' costs instead shrink (or grow) geometrically, the first (or last) row dominates.

Uneven splits (not covered by the master theorem): T(n) = T(αn) + T(βn) + Θ(n). The children's sizes add up to (α + β) times the parent's, so level d costs about n(α + β)d.

  • α + β < 1: geometric decrease, Θ(n) (median of medians: 1/5 + 7/10 = 9/10).
  • α + β = 1: Θ(n log n) (1/3 + 2/3).
  • α + β > 1: superlinear.
nn/4n/2n/16n/8n/8n/4nn/4 + n/2 = (3/4)n(3/4)²n = (9/16)nlevel total⋮ level d totals at most (3/4)^d · n ⇒ T(n) ≤ n·Σ(3/4)^d = 4n
Exam 1A Q1b: T(n) = T(⌊n/4⌋) + T(⌊n/2⌋) + n. The child sizes add to 3/4 of the parent, so level totals shrink geometrically and the root dominates: Θ(n).
How to read this figure Exam 1A Q1b: each node of size s has children of sizes s/4 and s/2, together (3/4)s. So the level totals are n, (3/4)n, (9/16)n, …, a geometric series summing to at most 4n.

Proving a bound by induction (when asked “do not use the master theorem”): guess the bound from the tree, then prove T(m) ≤ K·g(m) for all m < n by strong induction. The key move is always a negative term that absorbs the extra work:

  1. Want: T(n) ≤ Kn log₂ n for T(n) = T(⌊n/2⌋) + T(⌈n/2⌉) + cn.
  2. Trick: for n ≥ 4 both halves are ≤ 2n/3, so log₂(half) ≤ log₂ n − log₂(3/2).
  3. Steps: T(n) ≤ K(a log a + b log b) + cn ≤ K(a + b)(log₂ n − log₂(3/2)) + cn = Kn log₂ n − K·0.585·n + cn.
  4. Choose K with K·log₂(3/2) ≥ c (K = 2c works since 2·log₂(3/2) ≈ 1.17 ≥ 1), and large enough for the base cases m = 2, 3.
  5. In words: splitting into pieces at most 2n/3 saves a constant fraction of log n per element, and that saving pays for the cn combine cost.
Worked example Selection-type bound T(n) ≤ T(⌈n/5⌉) + T(⌈7n/10⌉) + cn. Hypothesis T(m) ≤ Am for all m < n. Then T(n) ≤ A(n/5 + 1) + A(7n/10 + 1) + cn = (9/10)An + 2A + cn. With A ≥ 20c, cn ≤ An/20, so T(n) ≤ (19/20)An + 2A ≤ An whenever n ≥ 40 (base cases cover n < 40 by enlarging A).

Takeaway: the 1/10 of slack (1 − 9/10) has to pay both for cn and for the +1's from ceilings; choose A after seeing what the step needs.

Why is it done this way?
Why is the master theorem's case decided by comparing d with logb a?Level i costs nd(a/bd)i. a/bd < 1 ⇔ d > logb a (decreasing series, root wins); = 1 ⇔ equality (log n equal levels); > 1 ⇔ leaves win, and there are alogb n = nlogb a leaves.
Why does the induction need the “2n/3” bound instead of n/2?⌈n/2⌉ can exceed n/2, so log₂⌈n/2⌉ is not exactly log₂ n − 1. A uniform bound ≤ 2n/3 (true for n ≥ 4) gives a clean saving of log₂(3/2) per element for every n.
Why is α + β = 1 still n log n even though the tree is lopsided?Every level that is complete costs exactly n, and the shallowest leaf is at depth log1/min(α,β) n = Θ(log n), so there are Θ(log n) full levels.
Traps
  • Leaves case: the answer is nlogb a, not nd. Strassen 7T(n/2) + n² is Θ(n2.807): not O(n2.5) (gap 0.307 in the exponent), but o(n³).
  • Uneven splits are not a master-theorem case; use the tree.
  • In induction, fix the constant before the step; never conclude “= O(n)” inside the step.
Summary card
  • aT(n/b) + nd: compare d vs logb a → root Θ(nd) / tie Θ(nd log n) / leaves Θ(nlogb a).
  • T(αn) + T(βn) + n: α+β < 1 → Θ(n); = 1 → Θ(n log n).
  • Induction: IH T(m) ≤ Kg(m) ∀m < n · step creates −(saving)·n · choose K ≥ (combine constant)/(saving) and big enough for bases.
Recall check
Solve 2T(n/2) + Θ(n²).
a = 2, b = 2, d = 2 > log₂2 = 1: root dominates, Θ(n²).
Solve 8T(n/2) + Θ(n²).
log₂8 = 3 > 2: leaves dominate, Θ(n³) (schoolbook matrix multiplication).
In the n log n induction proof, where does the saving come from and what does it pay for?
From each half having size ≤ 2n/3, so log(half) ≤ log n − log(3/2): it produces −K log(3/2)·n, which pays for the +cn combine cost.
✍ U1A.11Master theorem batch New drillcalculation
Source: New drill (Lec 2 master theorem)
Solve each with the master theorem (course form: T(n) = aT(n/b) + Θ(nd); compare d with logb a).
  1. 2T(n/2) + n
  2. 2T(n/2) + 1
  3. 4T(n/2) + n
  4. 4T(n/2) + n²
  5. 3T(n/2) + n
  6. T(n/2) + n
  7. 7T(n/2) + n²
  8. 8T(n/2) + n³
Show solution
a, b, dlogb a vs dAnswer
a2, 2, 11 = 1 (tie)Θ(n log n)
b2, 2, 01 > 0 (leaves)Θ(n)
c4, 2, 12 > 1 (leaves)Θ(n²)
d4, 2, 22 = 2 (tie)Θ(n² log n)
e3, 2, 11.585 > 1 (leaves)Θ(nlog₂3) ≈ Θ(n1.585)
f1, 2, 10 < 1 (root)Θ(n)
g7, 2, 22.807 > 2 (leaves)Θ(nlog₂7) ≈ Θ(n2.807) (Strassen)
h8, 2, 33 = 3 (tie)Θ(n³ log n)
Rubric: what earns the points
  • a, b, d identified
  • log_b a compared with d
  • correct case and answer for each
Where partial credit is lost
  • Write a, b, d and logb a for each before naming the case.
  • Tie case gets the extra log factor; leaves case answer is nlogb a, not nd.
✍ U1A.12Unequal subproblems (Exam 1A Q1b) Past examcalculation
Source: exams/Exam1_SecA_Soln.pdf p1 (paper p2)
Let T(1) = T(2) = T(3) = 1 and, for n ≥ 4, T(n) = T(⌊n/4⌋) + T(⌊n/2⌋) + n. Give a tight asymptotic bound and briefly justify it (no formal induction needed).
Show solution

T(n) = Θ(n).

  1. Upper bound (recursion tree). The two children of a node of size s have sizes at most s/4 + s/2 = (3/4)s. So the total size at depth d is at most n(3/4)d, and each node's own work is at most its size (base cases cost 1 ≤ size).
  2. Summing: T(n) ≤ n Σd≥0 (3/4)d = n · 1/(1 − 3/4) = 4n = O(n).
  3. Lower bound: the root alone costs n, so T(n) ≥ n = Ω(n).

Numeric check (code): T(106)/106 = 3.92, and the maximum of T(n)/n over n ≤ 106 is 3.93 < 4.

Rubric: what earns the points
  • answer Θ(n)
  • child sizes sum to (3/4) of parent
  • geometric sum ⇒ O(n)
  • lower bound from the root
Where partial credit is lost
  • Rubric: the 5 points were all for the upper bound with a justification. State the 3/4 shrink factor and the geometric sum.
  • Give the matching lower bound (root costs n) to justify “tight”.
✍ U1A.13Uneven splits: sum < 1 vs sum = 1 New drillcalculation
Source: New drill (Lec 2 selection-type recurrences)
Solve (a) T(n) = T(n/2) + T(n/3) + n and (b) T(n) = T(n/3) + T(2n/3) + n. Explain why they differ.
Show solution

(a) Θ(n). Level d has total size at most n(1/2 + 1/3)d = n(5/6)d; summing the geometric series gives at most n/(1 − 5/6) = 6n. The root gives Ω(n).

(b) Θ(n log n). The fractions sum to exactly 1, so every full level costs n. The shallowest leaf is at depth log3 n and the deepest at log3/2 n, both Θ(log n) levels, so the total is Θ(n log n).

Rule: T(αn) + T(βn) + Θ(n) is Θ(n) if α + β < 1, Θ(n log n) if α + β = 1, and superlinear if α + β > 1.

Rubric: what earns the points
  • (a) Θ(n) with geometric sum
  • (b) Θ(n log n)
  • explanation: sum of fractions < 1 vs = 1
Where partial credit is lost
  • For (b), argue both bounds: every level up to the shallowest leaf is full (gives Ω), and there are O(log n) levels each costing ≤ n (gives O).
✍ U1A.14Prove merge sort's bound by induction (Practice Exam U1 Q3.3) Practice examguided proof
Source: practice-exams/Practice_Exam_Unit_1_Solutions.pdf Q3.3 (“see handwritten notes from Lec 2”)
Assume n = 2k and T(1) = Θ(1), T(n) = 2T(n/2) + n for n ≥ 2. Prove by induction (no master theorem) that T(n) = O(n log n).
Show solution

We prove the explicit statement T(n) ≤ K·n log₂ n for every power of two n ≥ 2, with the fixed constant K = T(1) + 1.

  1. Base (n = 2): T(2) = 2T(1) + 2 = 2(T(1) + 1) = K·2·log₂ 2 ✓.
  2. Hypothesis: T(n/2) ≤ K·(n/2) log₂(n/2) for some power of two n ≥ 4.
  3. Step: T(n) = 2T(n/2) + n ≤ 2K(n/2)(log₂ n − 1) + n = Kn log₂ n − Kn + n ≤ Kn log₂ n, because K ≥ 1.

Hence T(n) = O(n log n). The key move: log₂(n/2) = log₂ n − 1 produces the negative term −Kn that absorbs the +n. Numeric check: with T(1) = 1, T(1024) = 11264 = 1024·10 + 1024 ≤ 2·1024·10 ✓.

Rubric: what earns the points
  • explicit hypothesis with fixed K
  • base case verified
  • step algebra with log(n/2) = log n − 1
  • constant absorbs +n
  • conclusion
Where partial credit is lost
  • State the hypothesis as an explicit inequality with a fixed constant (not “T = O(n log n)”: see U1A.2).
  • Choose K so that both the base case and the step's “−Kn + n ≤ 0” work.
  • Show the log₂(n/2) = log₂ n − 1 step.

22 · Divide & conquer and selection Lec 1–3 · HW1 #2–3 · Exam 1A Q2, Q1g · Practice Exam U1 Q3

▸ Collapsed: click to expand (3 subsections)▾ Click to collapse

22.1 The D&C frame: split, recurse, combine

Warm-up: try from memory first
What are the three parts of every D&C answer on the exam?
Algorithm (base case, split, recursive calls, combine), correctness (induction: base + combine is right if the recursive answers are right), runtime (recurrence + solve).
Merge sort's recurrence and solution?
T(n) = 2T(n/2) + Θ(n) = Θ(n log n).
How do you make a combine step O(1) instead of O(n)?
Have each recursive call return a richer summary (e.g. max, min, best prefix/suffix, total), so the parent never scans the array.
The idea in one sentenceSolve each half recursively, then build the whole answer from the two half-answers. The only new work is the part that crosses the middle.

Answer frame (what the rubric checks):

  1. Algorithm: base case (size 1 or 2), how you split, the recursive calls, and the combine step. Pseudocode or numbered steps.
  2. Correctness: strong induction on n. Base case is right; if both recursive results are right, every candidate answer is either entirely in the left, entirely in the right, or crosses the middle, and the combine handles the crossing case.
  3. Runtime: recurrence → master theorem or tree (§21).
ProblemEach call returnsCombineRecurrence
Merge sortsorted arraymerge, O(n)2T(n/2) + n = Θ(n log n)
Counting inversions(sorted array, count)merge and add |X| − i per Y outputΘ(n log n)
Max difference v2(D, M, m)D = max(DL, DR, ML − mR)2T(n/2) + 1 = Θ(n)
Max contiguous product (HW1)(best, prefix, suffix, total)best = max(BL, BR, SL·PR)Θ(n)
Peak finding / binary searchan indexnone: discard one halfT(n/2) + 1 = Θ(log n)
2 5 1 7 3 2 4 6(5, 7, 1)2 5 1 7(4, 7, 1)3 2 4 6(1, 6, 2)2 5(0, 5, 2)1 7(0, 7, 1)3 2(1, 3, 2)4 6(0, 6, 4)2(0, 2, 2)5(0, 5, 5)1(0, 1, 1)7(0, 7, 7)3(0, 3, 3)2(0, 2, 2)4(0, 4, 4)6(0, 6, 6)
Max difference on A = [2, 5, 1, 7, 3, 2, 4, 6]. Each box shows its subarray (grey) and the summary (D, M, m) = (best difference, max, min). Root: D = max{4, 1, M_L − m_R = 7 − 2} = 5.
How to read this figure Each box is a subarray with its summary (D, M, m) = (best difference, max, min). Leaves are single entries (0, x, x). A parent's D is the best of its children's D's and the crossing value Mleft − mright; nothing is rescanned.
Worked example: counting inversions (merge step) Merging X = [1, 3, 6, 8] with Y = [2, 4, 5, 7]: when 2 is output, 3, 6, 8 are still waiting in X and all of them are bigger than 2 (+3). Then 4 (+2: 6, 8), 5 (+2), 7 (+1: 8). Cross inversions = 8. With the halves' own counts 4 and 3 the total for [3, 8, 6, 1, 5, 2, 7, 4] is 15.

Takeaway: sortedness of X is what lets one comparison count |X| − i pairs at once.

Why is it done this way?
Why return a summary instead of just the answer?The crossing case needs information about the halves (e.g. the max of the left, the min of the right). If the recursive call doesn't return it, the combine has to rescan Θ(n) elements and you get n log n instead of n.
Why does sorting the halves not break the inversion count?A cross pair is "some x in the left half, some y in the right half, x > y". Reordering inside each half does not change which values are in which half, so the set of cross pairs is the same.
Summary card
  • Frame: base · split · recurse · combine (crossing case) · induction · recurrence.
  • Θ(n) D&C ⇔ O(1) combine ⇔ return a summary (max, min, prefix, suffix, total).
  • Inversions: count = left + right + (|X| − i per Y element output during the merge).
Recall check
In counting inversions, what do you add when an element of Y is output during the merge, and why?
|X| − i, the number of X elements not yet output: X is sorted, so all of them are larger than this Y element.
Max difference maxi≤j A[i] − A[j]: what summary makes it Θ(n), and what is the crossing term?
(D, M, m) = (best, max, min); crossing term ML − mR.
HW1 max contiguous product: the 4 returned values and the base case for an entry x < 1?
(best, best prefix, best suffix, total); for x < 1: (1, 1, 1, x), using the empty product 1.
✍ U1A.18Count inversions by hand (merge-and-count trace) Practice examcalculation
Source: Practice Exam U1 Q3 (algorithm); instance new
Count the inversions of A = [3, 8, 6, 1, 5, 2, 7, 4] using the divide-and-conquer algorithm: report the inversions inside the left half, inside the right half, and the cross inversions found by the top-level merge.
Show solution
  1. Left half [3, 8, 6, 1]: inversions (3,1), (8,6), (8,1), (6,1) = 4. Sorted: [1, 3, 6, 8].
  2. Right half [5, 2, 7, 4]: (5,2), (5,4), (7,4) = 3. Sorted: [2, 4, 5, 7].
  3. Merge X = [1,3,6,8] with Y = [2,4,5,7]. Each time a Y element is output, add the number of X elements still waiting (all of them are larger): 2 is output with 3, 6, 8 waiting (+3); 4 with 6, 8 waiting (+2); 5 with 6, 8 (+2); 7 with 8 (+1). Cross = 8.
  4. Total = 4 + 3 + 8 = 15 (out of at most C(8,2) = 28).
Where partial credit is lost
  • Add |X| − i (the number of X elements remaining), not 1, when a Y element is output.
  • Recursive counts are on the halves' original order; the merge works on the sorted halves.
✍ U1A.19Counting inversions in O(n log n) (Practice Exam U1 Q3.1–3.2) Practice examdesign + prove
Source: practice-exams/Practice_Exam_Unit_1_Solutions.pdf Q3
(1) Design MergeAndCount(X, Y): given two sorted arrays, return the merged sorted array and the number of pairs with X[i] > Y[j]. Example: MergeAndCount([1,5],[2,3]) → [1,2,3,5] and 2. (2) Using it, design a divide-and-conquer algorithm that counts all inversions (i < j, A[i] > A[j]) in O(n log n), with a correctness argument and the runtime.
Show solution

(1) MergeAndCount. Pointers i = j = 0, count c = 0. While both arrays have elements: if X[i] ≤ Y[j], append X[i], i++; else append Y[j], j++, and c += |X| − i (all of X[i..] are > Y[j] since X is sorted). Append the leftovers. Return (Z, c). Time O(|X| + |Y|).

(2) SortCount(A): if |A| ≤ 1 return (A, 0). Split into L = A[0..⌊n/2⌋−1], R = the rest. (L', a) = SortCount(L); (R', b) = SortCount(R); (Z, c) = MergeAndCount(L', R'). Return (Z, a + b + c).

Correctness (strong induction on n). Base n ≤ 1: no pairs, 0 inversions. Step: every inversion (i, j) has both indices in L (counted in a by the IH), both in R (in b), or i in L and j in R. The last kind is exactly a pair x ∈ L, y ∈ R with x > y; sorting each half does not change which such pairs exist, so MergeAndCount counts them exactly (c). The three kinds are disjoint, so the total is a + b + c; the returned array is sorted by the merge.

Runtime: T(n) = 2T(n/2) + O(n) = O(n log n) (master theorem, tie case).

Rubric: what earns the points
  • merge with |X| − i counting
  • recursive structure returns (sorted, count)
  • base case
  • split inversions into left / right / cross
  • cross pairs unchanged by sorting halves
  • recurrence and O(n log n)
Where partial credit is lost
  • Return the sorted array too: the merge step needs sorted halves.
  • Argue the three kinds of inversions are disjoint and exhaustive.
  • Explain why sorting the halves doesn't change the set of cross pairs.
✍ U1A.22Maximum difference with summaries (Lec 2): fill the tree Lecturecalculation
Source: Lec 2 board (max difference v1/v2); instance new
Maximum difference: max over i ≤ j of A[i] − A[j]. The Θ(n) D&C returns for each subarray the summary (D, M, m) = (best difference, maximum, minimum). (a) Give the combine rule. (b) Compute the root summary for A = [2, 5, 1, 7, 3, 2, 4, 6], listing the summaries of the two halves.
Show solution

(a) For left (DL, ML, mL) and right (DR, MR, mR): D = max(DL, DR, ML − mR), M = max(ML, MR), m = min(mL, mR). The crossing pair takes i in the left (largest A[i]) and j in the right (smallest A[j]). Base (one entry x): (0, x, x).

(b) Left half [2,5,1,7] → (4, 7, 1); right half [3,2,4,6] → (1, 6, 2). Root: D = max(4, 1, 7 − 2) = 5: (5, 7, 1). Best pair: A[i] = 7, A[j] = 2.

T(n) = 2T(n/2) + O(1) = Θ(n); the first version that scanned for ML, mR each time is 2T(n/2) + Θ(n) = Θ(n log n).

Where partial credit is lost
  • The crossing term is ML − mR (order matters: i ≤ j).
✍ U1A.21Maximum contiguous product in O(n) (HW1 #2) HWdesign + prove
Source: algo-part1-notes/HW1_Solutions.pdf §2 (Algorithm 2)
Given A[1..n] with non-negative entries, return the maximum product of a contiguous subarray (the empty product 1 is allowed). Example: A = [0.5, 2, 0.25, 2, 0.75, 2, 0.5] → 3 from [2, 0.75, 2]. Design a divide-and-conquer algorithm that splits A into halves; give pseudocode, a correctness argument (base case + combine) and the runtime. For full points it must be as fast as possible.
Show solution

Idea: return a 4-tuple summary so the combine is O(1): (best, best prefix, best suffix, total).

  1. Base (one entry x): if x ≥ 1 return (x, x, x, x), else (1, 1, 1, x) (empty product for best/prefix/suffix; total is x).
  2. Recurse on both halves: (BL, PL, SL, TL) and (BR, PR, SR, TR).
  3. Combine: total = TLTR; prefix = max(PL, TL·PR); suffix = max(SR, TR·SL); best = max(BL, BR, SL·PR).

Correctness (strong induction; IH: the four values are correct for both halves). A best subarray lies in the left half (BL), in the right half (BR), or crosses the middle; a crossing one is a suffix of the left times a prefix of the right, and both factors are maximized independently because entries are non-negative: SL·PR. A prefix of the whole array either ends in the left half (PL) or is the entire left half followed by a prefix of the right (TL·PR); suffixes are symmetric.

Runtime: T(n) = 2T(n/2) + O(1) = Θ(n) (master: log₂2 = 1 > 0, leaves case). Check on the example: left [0.5, 2, 0.25] → (2, 1, 1, 1/4), right [2, 0.75, 2, 0.5] → (3, 3, 3/2, 3/2); crossing 1·3 = 3; best = 3.

Rubric: what earns the points
  • 4-tuple summary defined
  • base case incl. empty product
  • combine formulas for all four values
  • crossing case = suffix × prefix
  • induction argument
  • T(n) = 2T(n/2) + O(1) = Θ(n)
Where partial credit is lost
  • The O(n log n) version (scan outward from the middle) is correct but loses the speed points: the official solution says it “wouldn't get full points”.
  • Non-negativity is what lets you maximize the two crossing factors separately; say so.
  • Prefix/suffix updates must use the total of the other half.
✍ U1A.20Variant: significant inversions (A[i] > 2A[j]) New drilldesign + prove
Source: New drill (classic variant)
Count pairs i < j with A[i] > 2·A[j] in O(n log n). Explain what changes relative to U1A.19. Check on A = [6, 1, 9, 2, 5, 3].
Show solution

Change: the cross count is no longer produced by the merge itself, because the merge order (x vs y) is not the order needed for x vs 2y. Do a separate linear pass before merging:

  1. With sorted halves L and R, pointer j = 0 into R. For each x in L in increasing order: advance j while j < |R| and x > 2R[j]; add j to the count.
  2. j never moves back, because a larger x satisfies x > 2R[j] for every R[j] the smaller x did. So the pass is O(n).
  3. Then merge normally (to keep the halves sorted for the parent).

T(n) = 2T(n/2) + O(n) = O(n log n). Check: L = [6,1,9] has 1 (6 > 2·1); R = [2,5,3] has 0. Sorted L = [1, 6, 9], R = [2, 3, 5]. x = 1: 1 > 2·2? no, +0. x = 6: 6 > 4 yes, 6 > 6 no, so j = 1, +1. x = 9: 9 > 4, 9 > 6, 9 > 10 no, so j = 2, +2. Cross = 3, total 4.

Rubric: what earns the points
  • separate counting pass
  • monotone pointer ⇒ O(n)
  • merge still needed
  • recurrence O(n log n)
Where partial credit is lost
  • Counting during the merge gives the wrong answer for this variant: separate the counting pass from the merging pass.
  • Justify that the pointer is monotone (that's what makes it linear).

22.2 Discard-half search: peak finding and binary search (Exam 1A Q2)

Warm-up: try from memory first
Why does every array (with A[0] = A[n+1] = −∞) have a peak?
The maximum entry is larger than both neighbours.
After comparing A[m] with A[m+1], which half must contain a peak?
The side of the larger one: if A[m] < A[m+1] keep [m+1, r]; otherwise keep [l, m].
The idea in one sentenceKeep an invariant that guarantees an answer lies in the current interval, and use one comparison to throw away a half that can't be needed.
  1. Invariant (Exam 1A Q2a): the interval [l, r] satisfies A[l] > A[l−1] and A[r] > A[r+1] ("both ends go uphill into the interval"). Then the interval contains a peak: its maximum is bigger than its neighbours inside the interval, and at the two ends the invariant handles the outside neighbour.
  2. Step (Q2b): m = ⌊(l+r)/2⌋. If A[m] < A[m+1], the interval [m+1, r] has an uphill left end, so keep it; else keep [l, m], whose right end is uphill (A[m] > A[m+1]).
  3. Runtime (Q2c): T(k) ≤ T(⌈k/2⌉) + c ⇒ O(log n).
2152934435866718index[1,8] m = 4[1,4] m = 2[3,4] m = 3[3,3] stop: peak 3
Peak finding on A = [2, 5, 9, 4, 3, 8, 6, 1] (A[0] = A[9] = −∞). Each blue bar is the interval kept after comparing A[m] with A[m+1]; it halves every step and ends at the peak A[3] = 9.
How to read this figure Bars are the array values. Each blue bar under the array is the interval kept after one comparison; it halves every step until a single index (the peak) remains.
Traps (both cost you points)
  • Existence proofs: "take the maximum" is the proof. Describing the algorithm instead earns nothing (Q2a, 0/6).
  • Off by one: keeping [m, r] when A[m] < A[m+1] loops forever on two elements (l = 1, r = 2 ⇒ m = 1 ⇒ [1, 2] again). Always test your recursion on an interval of length 2 (Q2b, −1).
Summary card
  • Peak: invariant "both ends uphill" · max of interval is a peak · keep the side of the larger of A[m], A[m+1]: [m+1, r] or [l, m] · O(log n).
  • Any discard-half search: state the invariant, show each branch keeps it, check length-2 intervals shrink.
Recall check
Prove in two sentences that [l, r] with A[l] > A[l−1], A[r] > A[r+1] contains a peak.
Let i be the index of the maximum of A[l..r]; its neighbours inside the interval are smaller. If i = l or i = r, the outside neighbour is smaller by the hypothesis, so i is a peak.
Why must the kept half be [m+1, r] and not [m, r]?
[m+1, r] has the uphill left end A[m+1] > A[m] (the invariant), and it is strictly smaller; [m, r] may equal [l, r] on two elements, so the recursion never ends.
✍ U1A.16A peak exists inside the interval (Exam 1A Q2a): redo Past examguided proof
Source: exams/Exam1_SecA_Soln.pdf p3
A[1..n] holds n ≥ 2 distinct numbers, A[0] = A[n+1] = −∞. Index i is a peak if A[i] > A[i−1] and A[i] > A[i+1]. Let [l, r] be an interval of indices with A[l] > A[l−1] and A[r] > A[r+1]. Prove that [l, r] contains a peak of the original array (a short existence proof, not an algorithm).
Show solution

Extremal choice. Let i ∈ [l, r] be the index of the maximum of A[l..r].

  1. Neighbours inside the interval: every neighbour of i that lies in [l, r] is smaller, because A[i] is the maximum there and entries are distinct.
  2. If i = l: its left neighbour A[l−1] lies outside, but A[l] > A[l−1] by the hypothesis.
  3. If i = r: its right neighbour A[r+1] lies outside, but A[r] > A[r+1] by the hypothesis.
  4. So both neighbours of i in the original array are smaller: i is a peak. (If l = r, both boundary conditions apply to the single index.) ∎
Rubric: what earns the points
  • choose the maximum in [l, r]
  • interior neighbours smaller (distinctness)
  • boundary i = l uses A[l] > A[l−1]
  • boundary i = r uses A[r] > A[r+1]
  • conclude peak
Where partial credit is lost
  • You lost all 6 points here (“wrong answer”). The maximum of the interval is the whole proof; then handle the two boundary cases with the given inequalities.
  • Don't describe the algorithm: the question asks only for existence.
  • Use “distinct” to get strict inequalities inside the interval.
✍ U1A.17Halving search for a peak + its running time (Exam 1A Q2b–c): redo with a trace Past examguided proof
Source: exams/Exam1_SecA_Soln.pdf p3; trace instance new
Same setting. (b) Describe the recursive algorithm: initial interval, base case, and which half to keep after comparing A[m] with A[m+1] for m = ⌊(l+r)/2⌋; explain why the kept interval satisfies the conditions of U1A.16. (c) Give and solve a recurrence for the worst case. (d) Trace your algorithm on A = [2, 5, 9, 4, 3, 8, 6, 1] (1-indexed).
Show solution

(b) Algorithm. Start with l = 1, r = n (valid since A[0] = A[n+1] = −∞).

  1. If l = r, return l.
  2. Else m = ⌊(l+r)/2⌋. If A[m] < A[m+1], recurse on [m+1, r]; if A[m] > A[m+1], recurse on [l, m] (no ties: entries are distinct).

Why the kept interval is valid. In [m+1, r], the new left end satisfies A[m+1] > A[m] (that's the comparison), and the right condition is inherited. In [l, m], the new right end satisfies A[m] > A[m+1], and the left condition is inherited. At l = r the two conditions say exactly that l is a peak.

(c) T(k) ≤ T(⌈k/2⌉) + c, T(1) = Θ(1). The interval halves each call, so after ⌈log₂ n⌉ calls one entry remains: T(n) = O(log n) (master theorem a = 1, b = 2, d = 0: tie case, Θ(log n)).

(d) Trace.

  1. [1,8], m = 4: A[4] = 4 > A[5] = 3 → keep [1,4]
  2. [1,4], m = 2: A[2] = 5 < A[3] = 9 → keep [3,4]
  3. [3,4], m = 3: A[3] = 9 > A[4] = 4 → keep [3,3]

Return index 3 (A[3] = 9 > 5 and > 4) after 3 comparisons.

Rubric: what earns the points
  • initial interval [1, n]
  • base case l = r
  • correct halves [m+1, r] / [l, m]
  • why the conditions are preserved
  • recurrence T(k) ≤ T(⌈k/2⌉) + c
  • solve: O(log n)
Where partial credit is lost
  • Your 1-point loss: keeping [m, r] instead of [m+1, r]. On two elements l = 1, r = 2 gives m = 1 and [m, r] = [1, 2] again: infinite recursion. Test every recursion on an interval of length 2.
  • State the initial interval and the base case explicitly; both are rubric items.
✍ U1A.26Find i with A[i] = i in O(log n) New drilldesign + prove
Source: New drill (classic)
A[1..n] is a sorted array of distinct integers. Design an O(log n) algorithm that returns some i with A[i] = i, or reports none. Prove correctness. Run it on A = [-4, -1, 2, 4, 6, 8, 10].
Show solution

Key fact: B[i] = A[i] − i is non-decreasing: A[i+1] ≥ A[i] + 1 (distinct integers, sorted), so B[i+1] ≥ B[i]. We look for a zero of B.

  1. Binary search on [l, r] = [1, n]: m = ⌊(l+r)/2⌋.
  2. If A[m] = m, return m. If A[m] < m (B[m] < 0), every i ≤ m has B[i] ≤ B[m] < 0, so recurse on [m+1, r]. If A[m] > m, every i ≥ m has B[i] > 0: recurse on [l, m−1].
  3. Empty interval ⇒ none exists.

Invariant: any fixed point lies in [l, r]. T(n) = T(n/2) + O(1) = O(log n). Run: B = [-5, -3, -1, 0, 1, 2, 3]. m = 4: A[4] = 4, return 4.

Rubric: what earns the points
  • A[i] − i monotone (uses distinct integers)
  • correct discard rule both sides
  • invariant / correctness
  • O(log n)
Where partial credit is lost
  • Distinctness and integrality are both needed (with repeats, B can decrease).

22.3 Selection: median of medians (Lec 3, HW1 #3)

Warm-up: try from memory first
What makes a pivot "good" and why does it matter?
Both sides of the partition have at most a constant fraction (e.g. 7/10) of the elements, so the recursion shrinks geometrically: linear time.
Write the median-of-medians recurrence for groups of 5.
T(n) ≤ T(n/5) + T(7n/10) + cn = Θ(n).
The idea in one sentenceFind a pivot that is guaranteed to be near the middle by taking the median of the group medians, then recurse only on the side that contains the k-th element.

Select(A, k) (k-th smallest):

  1. Split A into n/5 groups of 5; find each group's median (constant time per group).
  2. p = Select(medians, n/10): the median of the medians (recursive call on n/5 elements).
  3. Partition: L = elements < p, G = elements > p.
  4. If k ≤ |L|, return Select(L, k). If k = |L| + 1, return p. Else return Select(G, k − |L| − 1).

Why p is good: half of the n/5 groups have median ≥ p, and each contributes 3 elements ≥ its median ≥ p. So at least 3 · (n/10) = 3n/10 elements are ≥ p, and likewise ≤ p. Each side has at most 7n/10 elements.

p← group medians (row 3)red: all ≥ pblue: all ≤ plargerwithina groupgroups (columns) ordered by their mediann = 35: 7 groups of 5, sorted inside each group
Median of medians: p is the median of the 7 group medians. Every red cell is ≥ p (it is ≥ its own median, which is ≥ p): 3 cells × 4 groups. Every blue cell is ≤ p. In general ≥ 3·(1/2)·(n/5) = 3n/10 on each side.
How to read this figure Each column is a sorted group of 5 (smallest at the bottom), and the columns are ordered by their medians. The pivot p is the middle median. Every red cell is ≥ its column's median ≥ p; every blue cell is ≤ p. Counting the coloured cells gives the 3n/10 guarantee on each side.
Group size MRecurrence fractionsSumTime
31/3 + 2/31Θ(n log n): not linear
51/5 + 7/109/10Θ(n)
71/7 + 5/76/7Θ(n)
M (odd)1/M + (3M−1)/(4M)(3M+3)/(4M)Θ(n) iff M ≥ 5
Why is it done this way?
Why does groups of 3 fail?Guarantee: half the groups × 2 elements = n/3 on each side, so the big side has 2n/3, plus the n/3 recursive call on medians: fractions sum to exactly 1, which gives n log n (§21).
Why recurse on only one side?The k-th element is in L, is p, or is in G, and |L| tells you which. Quicksort needs both sides; selection needs one.
Summary card
  • Groups of 5 → medians → recursive median p → partition → recurse on one side with k or k − |L| − 1.
  • ≥ 3n/10 on each side ⇒ T(n) ≤ T(n/5) + T(7n/10) + cn = Θ(n). Groups of 7: T(n/7) + T(5n/7). Groups of 3 fail.
  • Induction for M = 7: T(n) ≤ kn with k ≥ 7c.
Recall check
Derive the 7n/10 in two lines.
n/10 groups have median ≥ p, each with 3 elements ≥ p, so ≥ 3n/10 elements are ≥ p. Hence < p contains at most 7n/10; same for > p.
When recursing into G for the k-th smallest, what rank do you ask for?
k − |L| − 1.
Smallest odd group size with linear time?
5.
✍ U1A.25MoM quick facts (Exam 1A Q1g, Practice Exam U1 Q1.1) Past examshort answer
Source: exams/Exam1_SecA_Soln.pdf p2; Practice Exam U1 Q1.1
(a) For groups of 7, what are the two fractions in T(n) ≤ T(αn) + T(βn) + cn, and why is the second one what it is? (b) What is the smallest odd group size M that still gives linear time? (No justification required.)
Show solution

(a) α = 1/7 (the recursive call on the n/7 group medians), β = 5/7: at least half the medians are ≥ the pivot, each with 4 elements ≥ the pivot, so at least 4 · (n/7) · (1/2) = 2n/7 elements are ≥ p (and 2n/7 are ≤ p); the recursion keeps at most 5n/7.

(b) M = 5. M = 3 gives 1/3 + 2/3 = 1 ⇒ Θ(n log n).

Where partial credit is lost
  • You scored 6/6 on Q1g; this is maintenance.
✍ U1A.24Median of medians by hand on 25 numbers New drillcalculation
Source: New drill (Lec 3 algorithm)
Run one round of median of medians (groups of 5) to find the 20th smallest of [9, 1, 20, 15, 7, 8, 4, 10, 16, 25, 14, 19, 11, 5, 22, 3, 24, 2, 18, 6, 17, 13, 12, 21, 23]. Give the groups, their medians, the pivot, the sizes |L|, |G|, and the recursive call.
Show solution
  1. Groups (each sorted): [1, 7, 9, 15, 20]; [4, 8, 10, 16, 25]; [5, 11, 14, 19, 22]; [2, 3, 6, 18, 24]; [12, 13, 17, 21, 23].
  2. Medians: [9, 10, 14, 6, 17]; their median (recursive call on 5 numbers) is the pivot p = 10.
  3. Partition: |L| = #elements < 10 = 9, |G| = #elements > 10 = 15; p has rank 10.
  4. Recurse: k = 20 > |L| + 1 = 10, so find the (20 − 10) = 10th smallest of G (which is 20).
  5. Guarantee check: 3 groups have median ≥ 10, each with 3 elements ≥ its median: at least 9 elements ≥ p guaranteed (actually 16).
Where partial credit is lost
  • When recursing into G, subtract |L| + 1 from k.
✍ U1A.23Median of medians with groups of M (HW1 #3) HWguided proof
Source: algo-part2-notes/homeworks/hw1.tex §3 (official solution: HW1_Solutions.pdf)
(a) Give the worst-case recurrence for median of medians with groups of size M ≥ 3 (odd). (b) For M = 7, solve it by induction (hypothesis, base, step). (c) Compared to M = 5, does the running time (i) improve to o(n), (ii) stay Θ(n), or (iii) worsen to ω(n)? Briefly explain.
Show solution

(a) There are n/M groups. The pivot p is the median of the n/M group medians: half of those groups (n/(2M)) have median ≥ p, and each contributes its ⌈M/2⌉ = (M+1)/2 elements ≥ its median. So at least (M+1)/2 · n/(2M) elements are ≥ p, and symmetrically ≤ p. The recursive call keeps at most n − (M+1)n/(4M) = (3M−1)n/(4M) elements:

T(n) ≤ T(n/M) + T((3M−1)n/(4M)) + cn.

M = 5: 1/5 + 7/10 = 9/10; M = 7: 1/7 + 5/7 = 6/7; M = 3: 1/3 + 2/3 = 1 (not linear).

(b) M = 7: T(n) ≤ T(n/7) + T(5n/7) + cn. Claim T(n) ≤ kn with k = 7c.

  1. Base: for n ≤ n₀, T(n) is a constant; enlarge k so that T(n) ≤ kn there.
  2. Hypothesis: T(m) ≤ km for all m < n.
  3. Step: T(n) ≤ k·n/7 + k·5n/7 + cn = (6/7)kn + cn ≤ kn ⇔ cn ≤ kn/7 ⇔ k ≥ 7c. ✓

(c) (ii) Θ(n). Still linear (the fractions sum to 6/7 < 1); the constant changes, not the growth rate. It can't be o(n): reading the input already takes n.

Rubric: what earns the points
  • (a) n/M term
  • (a) (3M−1)n/(4M) derivation
  • (b) hypothesis with explicit k
  • (b) base
  • (b) step ⇒ k ≥ 7c
  • (c) (ii) with reason
Where partial credit is lost
  • Derive the second fraction from “half the groups × (M+1)/2 elements each”, not by memory.
  • In the induction, show the inequality that forces k ≥ 7c.
  • For (c), say why not o(n) (must read every element).

23 · Dynamic programming Lec 3–4 · HW2 #4–5 · Exam 1A Q3 · practice problems 3.1–3.3

▸ Collapsed: click to expand (3 subsections)▾ Click to collapse

23.1 The DP recipe (the answer frame for Exam 1A Q3-type questions)

Warm-up: try from memory first
What four things must every DP answer state?
(1) Table entry meaning in words with index ranges; (2) base cases; (3) recurrence + why it's correct; (4) which cell is the answer, fill order, time and space.
DP runtime formula?
(number of table entries) × (work per entry).
What question do you ask about the last element to get a recurrence?
"Is item i used or not?" (or "where does the last piece start?"). Each answer leads to a smaller subproblem.
The idea in one sentenceDefine a table of smaller versions of the problem (usually prefixes), decide what happens to the last element, and each choice points to an entry you've already computed.

Answer frame (Exam 1A Q3 points in brackets; you lost 15 of these 20).

  1. Definition [6]: "D(i, j) = the maximum/minimum ___ using only the first i items, with [limit] at most j." Give ranges 0 ≤ i ≤ n, 0 ≤ j ≤ k. Then the base cases (i = 0, j = 0, and any row the recurrence would read below 0) and the answer cell (e.g. D(n, k)).
  2. Recurrence [10]: one line, max/min over cases for the last item. Then justify: (a) every feasible solution falls into one case, so the max is at least OPT; (b) every case is achievable by a feasible solution, so it is at most OPT. Say which index shift enforces which constraint.
  3. Order + complexity [4]: fill in an order where every entry you read is already filled (e.g. increasing i). Time = entries × work; space = entries (or rolling rows).
ShapeEntryRecurrence patternAnswerTime
1-D "ends at j"M[j] = best ending exactly at jA[j] + max(0, M[j−1])maxj M[j]O(n)
Prefix + limitD(i, j)max(skip i, take i + D(i−2, j−1))D(n, k)O(nk)
Two sequencesD[i, j] on prefixesmatch → diagonal + 1; else max(up, left)D[m, n]O(mn)
Treetwo values per vertex (in / out)sum over childrenat rootO(n)
Last pieceT[i, j] = best for first i in j piecesmin over start of last pieceT[n, k]O(kn²)
BudgetT(i, b)max(skip, vi + T(i−1, b − si))T(n, B)O(nB)
Worked example: largest contiguous sum (Lec 3) A = [5, 15, -30, 10, -5, 40, 10]. "Ends at j" table: M[j] = A[j] + max(0, M[j−1]) gives M = [5, 20, -10, 10, 5, 45, 55]. At j = 3 the best ending there is negative (−10), so j = 4 starts fresh. Answer = max M = 55 (A[4..7]).

Takeaway: with an "ends at" definition the answer is the max over all cells, not the last cell.

Traps (from your Exam 1A Q3)
  • No answer cell stated (−2), base cases incomplete (−1), wrong fill order (−2), empty recurrence (−10).
  • "At most j" vs "exactly j" changes the base cases: decide and write it in the definition.
  • A recurrence that reads D(i−2, ·) needs row 1 (or row −1 = 0) defined.
Recall check
What are the two halves of a full recurrence justification?
Every feasible solution falls into one of the cases (max ≥ OPT), and each case's value is achieved by some feasible solution (max ≤ OPT).
Exam 1A Q3 (no two adjacent, at most k): the recurrence?
D(i, j) = max{ D(i−1, j), vi + D(i−2, j−1) }; i−2 enforces non-adjacency, j−1 the limit.
✍ U1A.27Largest contiguous sum (Lec 3): fill the table Lecturecalculation
Source: Lec 3 board; instance from calc_u1a
For A = [5, 15, -30, 10, -5, 40, 10], define M[j] = the largest sum of a contiguous subarray that ends at j. Give the recurrence, fill M, and report the answer and the subarray.
Show solution

Recurrence: M[1] = A[1]; M[j] = A[j] + max(0, M[j−1]) (either extend the best subarray ending at j−1, or start fresh at j). Answer = maxj M[j] (the best subarray ends somewhere).

M = [5, 20, -10, 10, 5, 45, 55]. Answer 55 = A[3..6] (after M[3] < 0 the next subarray restarts at index 4). O(n) time.

Where partial credit is lost
  • The answer is the max over all j, not M[n] — the classic DP-answer-cell mistake (you lost 2 points for the answer cell on Exam 1A Q3a).
✍ U1A.31Non-adjacent projects, at most k (Exam 1A Q3): full redo Past examguided proof
Source: exams/Exam1_SecA_Soln.pdf p4; (d) instance new
n ≥ 1 projects in a fixed order, project i has non-negative integer value vi. Choose I ⊆ {1..n} maximizing Σ vi, with at most k chosen (1 ≤ k ≤ n) and no two chosen indices consecutive. Choosing nothing is allowed. Design an O(nk) DP (value only). (a) Define D(i, j) via a prefix and a limit; give index ranges, base cases, and the answer cell. (b) Recurrence + justification (both constraints). (c) Fill order, time, space. (d) Fill the table for v = [4, 1, 3, 5, 2, 6], k = 3.
Show solution

(a) For 0 ≤ i ≤ n, 0 ≤ j ≤ k: D(i, j) = max total value from projects 1..i, choosing at most j projects, no two consecutive. Base: D(0, j) = 0 for all j; D(i, 0) = 0 for all i; D(1, j) = v1 for j ≥ 1. Answer: D(n, k).

(b) For i ≥ 2, j ≥ 1: D(i, j) = max{ D(i−1, j), vi + D(i−2, j−1) }.

  • Exclude i: the best is D(i−1, j).
  • Include i: then i−1 must be excluded (non-adjacency) and at most j−1 others come from 1..i−2 (the limit): vi + D(i−2, j−1).
  • Exactness: every feasible solution falls in one case (so the max is ≥ OPT), and each candidate is achieved by a feasible solution: skipping i keeps feasibility; appending i to a solution on 1..i−2 creates no adjacency and uses ≤ j projects (so the max ≤ OPT). Induction on i.

(c) Fill rows i = 2, …, n in increasing order (each row uses only rows i−1 and i−2); within a row any order of j. (n+1)(k+1) entries × O(1) = O(nk) time, O(nk) space (O(k) with three rolling rows).

(d) Rows i = 0..6, columns j = 0..3:

i \ j0123
00000
1 (v=4)0444
2 (v=1)0444
3 (v=3)0477
4 (v=5)0599
5 (v=2)0599
6 (v=6)061115

D(6, 3) = 15 (projects 1, 4, 6); with k = 2 the answer is 11, with k = 1 it is 6.

Rubric: what earns the points
  • (a) D(i,j) in words: prefix + at most j
  • (a) ranges + base cases
  • (a) answer D(n,k)
  • (b) recurrence
  • (b) exclude/include justification
  • (b) exactness both directions
  • (c) increasing-i order
  • (c) O(nk) time and space
Where partial credit is lost
  • This question cost you 15 of 20 points (b empty −10, base cases −1, answer cell −2, fill order −2).
  • Write D's meaning with “first i” and “at most j” in words; state D(n, k) as the answer.
  • The include case jumps to i−2 (non-adjacency) and j−1 (limit): say which constraint each index shift enforces.
  • Fill order: by increasing i, because row i reads rows i−1 and i−2.
  • Handle i = 1 so the recurrence never reads row −1.
✍ U1A.35DP true/false New drillshort answer
Source: New drill

True or False? Justify in 1–2 lines (a counterexample suffices for False).

  1. A DP that fills an n × n table with O(n) work per cell runs in O(n²).
  2. For LCS, a table with two rows suffices to output the LCS string.
  3. Every recursive algorithm with overlapping subproblems runs in polynomial time once memoized.
  4. In a DP whose entries are defined as “ending exactly at j”, the answer can be any cell, so it is maxj.
Show solution
  1. False. n² cells × O(n) = O(n³).
  2. False. Two rows give the length only; recovery needs the full table (or a divide-and-conquer trick not covered).
  3. False. Memoization is polynomial only if the number of distinct subproblems is polynomial (knapsack: nB subproblems, pseudo-polynomial).
  4. True (contiguous sum U1A.27, common substring U1A.30).
Where partial credit is lost
  • Runtime = #subproblems × work per subproblem; say both.

23.2 Two sequences: LCS and its variants (Lec 3–4)

Warm-up: try from memory first
LCS recurrence?
D[i,j] = D[i−1,j−1] + 1 if A[i] = B[j]; else max(D[i−1,j], D[i,j−1]); D[i,0] = D[0,j] = 0.
Subsequence vs substring?
A subsequence may skip positions; a substring is contiguous.
The idea in one sentenceLook at the last characters of both prefixes: either they are paired with each other, or at least one of them is unused.
  • Correctness: if A[i] = B[j], some LCS pairs them (swap argument), so D[i−1,j−1] + 1. Otherwise A[i] or B[j] is not in the LCS, so drop one: max(up, left).
  • Recovery: start at D[m,n]; on a match go diagonal and output the character; else move to the larger of up/left. Needs the whole table.
  • Variants: any "pair elements in order, each pair must pass a test" is the same table with a different test (practice 3.1 parity, 3.3 |x − y| ≤ 1). Substring: mismatch resets to 0 and the answer is the max cell.
εBCDGKABε00000000A00000011B01111112C01222222D01233333E01233333F01233333G01234444j →i ↓a_i = b_j (match)match on the path:emit the letter, go ↖no match: step to aneighbour equal to D[i,j]Traceback from D[7,7] = 4emits G, D, C, B, so theLCS is BCDG.
LCS table D[i,j] for A = ABCDEFG (rows) and B = BCDGKAB (columns). D[i,j] = D[i−1,j−1] + 1 on a match, else max(up, left). Coloured cells: one traceback path.
How to read this figure Rows follow A = ABCDEFG, columns follow B = BCDGKAB. A cell is its diagonal neighbour + 1 on a match, otherwise the larger of up and left. The coloured cells are one traceback path from the bottom-right corner; the diagonal steps spell the LCS BCDG.
Summary card
  • LCS: match → diag + 1; else max(up, left); O(mn); recover by traceback (full table).
  • General match test: max(up, left, diag + 1 if test passes). Substring: else 0, answer = max cell.
Recall check
Why can't a 2-row LCS table recover the string?
Traceback needs earlier rows, which the rolling table has overwritten.
Longest common substring recurrence?
E[i,j] = E[i−1,j−1] + 1 if A[i] = B[j], else 0; answer = max over all cells.
✍ U1A.28LCS: table, value, recovery (Lec 3–4) Lecturecalculation
Source: Lec 3–4 board (LCS); instance from calc_u1a
Fill the LCS table for A = ABCDEFG and B = BCDGKAB, give the length, and recover one LCS by tracing back.
Show solution

D[i, j] = LCS length of A[1..i], B[1..j]; D[i,0] = D[0,j] = 0; D[i,j] = D[i−1,j−1] + 1 if A[i] = B[j], else max(D[i−1,j], D[i,j−1]).

Length 4; tracing back from D[7,7] (diagonal on a match, else move to the larger neighbour) gives BCDG. Time Θ(mn) (64 cells), and recovery is O(m + n) more.

Where partial credit is lost
  • Recovery needs the full table (or stored pointers); a rolling 2-row table gives only the length.
  • On a mismatch, take the max of up and left, never diagonal.
✍ U1A.29LCS variants: non-mod-2 and close subsequences (practice problems 3.1, 3.3) Practice examguided proof
Source: practice-problems1 §3.1, §3.3; (b) instance new
(a) Longest non-mod-2 subsequences: equal-length subsequences S of arr1 (length m) and T of arr2 (length n) with S[i] mod 2 ≠ T[i] mod 2 for all i. Give the table, recurrence and runtime. (Example arr1 = [5,7,6,4,1,8,9], arr2 = [3,10,7,9,4] → 4.) (b) Same for “close” subsequences (|C[i] − D[i]| ≤ 1). Answer for A = [1, 5, 3, 8, 2], B = [4, 2, 7, 3, 9]?
Show solution

(a) T(i, j) = longest such pair using arr1[1..i] and arr2[1..j]. T(i,0) = T(0,j) = 0. T(i, j) = max( T(i−1, j), T(i, j−1), T(i−1, j−1) + 1 if arr1[i] mod 2 ≠ arr2[j] mod 2 ). Justification: either arr1[i] is unused, arr2[j] is unused, or they are the last pair (allowed only if their parities differ). O(mn) time. Example answer 4 ✓.

(b) Same table with the match test |A[i] − B[j]| ≤ 1. Answer 4: (5,4), (3,2), (8,7), (2,3).

Pattern: any “two sequences, pair elements in order, pairs must satisfy a test” problem is LCS with a different match test.

Rubric: what earns the points
  • table definition
  • base cases
  • three-way recurrence with test
  • justification
  • O(mn)
Where partial credit is lost
  • With a general match test, keep all three options in the max (the plain-LCS shortcut “on a match, always take the diagonal” is safe for equality, but just write the full max).
✍ U1A.30Longest common substring vs subsequence New drillshort answer
Source: New drill
For A = ABABC and B = BABCA, find the longest common substring (contiguous) with a DP, and compare with the LCS.
Show solution

E[i, j] = length of the longest common substring ending at A[i] and B[j]: E[i,j] = E[i−1,j−1] + 1 if A[i] = B[j], else 0. Answer = max over all cells.

Longest common substring: BABC, length 4. LCS length here is also 4. Differences from LCS: mismatch resets to 0, and the answer is the max over the table (an “ends at” DP).

Where partial credit is lost
  • “Ends at” definitions always need max over all cells for the answer.

23.3 DP on trees and "last piece" DPs (Lec 4, HW2 #4–5)

Warm-up: try from memory first
Why two values per vertex in a tree DP?
The parent's choice depends on whether the child is in or out (e.g. an edge needs one endpoint lit; an independent set can't contain both).
In which order do you fill a tree DP?
Post-order: children before parents (leaves first).
The idea in one sentenceA rooted subtree is a smaller instance; for each vertex, compute the best answer for its subtree under each state of the vertex (in / out), from its children's answers.
Problemv inv outLeaf
Max independent setI[v] = 1 + Σ X[u]X[v] = Σ max(I[u], X[u])(1, 0)
Min vertex cover (lights)C[v][1] = 1 + Σ min(C[u][0], C[u][1])C[v][0] = Σ C[u][1](1, 0)

Runtime: each vertex is a child of exactly one vertex, so the total work over all children lists is O(n).

1(6, 5)2(3, 3)7(1, 2)3(1, 2)6(1, 0)8(1, 0)9(1, 0)4(1, 0)5(1, 0)
Max independent set on the HW2 tree, root 1. Next to each vertex: (I[v], X[v]) = best size with v included / excluded. Root: max(6, 5) = 6; green vertices form an optimal set.
How to read this figure The HW2 tree rooted at 1. Next to each vertex is (I, X): the best independent set in its subtree with the vertex in / out. Compute from the leaves (1, 0) upward; the root's max(6, 5) = 6 is the answer, and the green vertices form one optimal set.

"Last piece" DPs (balancing array, HW2 #4): when the solution is a sequence of contiguous pieces, guess where the last piece starts: T[i, j] = min over i' of max(sum(A[i'..i]), T[i'−1, j−1]).

Summary card
  • Tree DP: two states per vertex · leaves (1, 0) · post-order · O(n). MIS + MVC = n.
  • Last piece: min over the start of the last piece of (cost of the last piece ⊕ best for the rest).
Recall check
Vertex cover on a tree: recurrence when v is NOT in the cover?
C[v][0] = Σ over children C[u][1]: every edge (v, u) must be covered by u.
Balancing array: table and recurrence?
T[i, j] = min largest sum splitting the first i into j pieces; T[i, j] = minj ≤ i' ≤ i max(sum(A[i'..i]), T[i'−1, j−1]); T[i, 1] = prefix sum.
✍ U1A.33Max independent set on a tree (Lec 4) Lecturecalculation
Source: Lec 4 board (tree MIS); HW2 tree
Same tree as U1A.32. Give the tree DP for a maximum independent set, compute (I[v], X[v]) (best with v included / excluded) at every internal vertex, and the answer. How are the MIS and the minimum vertex cover related here?
Show solution

I[v] = 1 + Σu X[u] (children excluded); X[v] = Σu max(I[u], X[u]). Leaves (1, 0).

(I, X): vertex 3 (1, 2), vertex 7 (1, 2), vertex 2 (3, 3), root 1 (6, 5). MIS = 6 = {1, 4, 5, 6, 8, 9}.

The complement of an independent set is a vertex cover, so MIS + MVC = n: 6 + 3 = 9 ✓.

Where partial credit is lost
  • Lecture writes it as max(1 + Σ grandchildren, Σ children); the two-state version is the same DP and easier to get right.
✍ U1A.32Minimum lights = vertex cover on a tree (HW2 #5) HWguided proof
Source: algo-part1-notes/HW2_Solutions.pdf §5
Find a minimum set S of vertices of a tree such that every edge has an endpoint in S, in O(|V|). Give the table, recurrence + justification, runtime. Run it on the HW2 tree (root 1; children 1: 2, 7; 2: 3, 6; 3: 4, 5; 7: 8, 9).
Show solution
1(4, 3)2(2, 2)7(1, 2)3(1, 2)6(1, 0)8(1, 0)9(1, 0)4(1, 0)5(1, 0)
Minimum lights (vertex cover) on the HW2 tree. Next to each vertex: (C[v][1], C[v][0]) = fewest lights in v's subtree with v lit / unlit. Root: min(4, 3) = 3; green = {2, 3, 7}.
How to read this figure Next to each vertex: (lit, unlit) = fewest lights in its subtree with the vertex lit / unlit. Compute bottom-up from the leaves (1, 0).

Table: for each vertex v, C[v][1] = fewest lights in v's subtree with v lit; C[v][0] = fewest with v unlit (all subtree edges lit).

Base (leaf): C[v] = (1, 0). Recurrence over children u:

  • C[v][1] = 1 + Σu min(C[u][0], C[u][1]): v lights every edge (v, u), so each child is free.
  • C[v][0] = Σu C[u][1]: edge (v, u) must be lit by u, so every child must be lit.

Answer min(C[root][0], C[root][1]). Post-order traversal; each vertex is a child once: O(|V|).

Run: leaves (1, 0); C[3] = (1, 2), C[7] = (1, 2), C[2] = (2, 2), C[1] = (4, 3). Answer 3 = {2, 3, 7}.

Rubric: what earns the points
  • two-state table in words
  • leaf base case
  • lit recurrence (min over child states)
  • unlit recurrence (children lit)
  • justification
  • answer + O(|V|)
Where partial credit is lost
  • Two values per vertex (lit / unlit) are essential; a single value can't enforce the parent-child edge.
  • Runtime argument: each vertex is a child of at most one vertex, so total work over all children lists is O(|V|).
✍ U1A.34Balancing array (HW2 #4) HWguided proof
Source: algo-part1-notes/HW2_Solutions.pdf §4
Partition an array A of n non-negative integers into k contiguous non-empty pieces minimizing the largest piece sum S. Define the table, give the recurrence with justification, and the O(kn²) runtime; explain how to get O(kn log n). Example A = [1,4,6,2,5], k = 3 → 7.
Show solution

Table: T[i, j] = minimum possible largest sum when the first i elements are split into j contiguous non-empty pieces (i ≥ j).

Base: T[i, 1] = A[1] + ⋯ + A[i]. Recurrence (j ≥ 2): T[i, j] = minj ≤ i' ≤ i max( sum(A[i'..i]), T[i'−1, j−1] ). Justification: guess where the last piece starts (i'); the rest is an optimal (j−1)-split of the first i'−1 elements. Answer T[n, k].

Runtime: nk entries, O(n) each with prefix sums: O(kn²). Faster: as i' grows, sum(A[i'..i]) decreases and T[i'−1, j−1] increases, so binary-search the crossing point: O(log n) per entry, O(kn log n).

Example table rows (j = 1, 2, 3) at i = 5: 18, 11, 7.

Rubric: what earns the points
  • table definition
  • base T[i,1]
  • recurrence with max inside min
  • justification (last piece)
  • O(kn²)
  • binary search ⇒ O(kn log n)
Where partial credit is lost
  • The inner min ranges over i' ≥ j so the first j−1 pieces are non-empty.
  • State the monotonicity that justifies the binary search.

24 · Knapsack, FPTAS, greedy, MDPs Lec 4–5 · HW2 #6–7 · Exam 1A Q1c, Q1d · Practice Exam U1 Q1.6–1.7, Q4

▸ Collapsed: click to expand (5 subsections)▾ Click to collapse

24.1 Knapsack: two DPs and pseudo-polynomial time

Warm-up: try from memory first
Budget-indexed knapsack recurrence?
T(i, b) = max(T(i−1, b), vi + T(i−1, b − si)) (second term only if si ≤ b); O(nB).
Why isn't O(nB) a polynomial-time algorithm?
B is written with log B bits; nB is exponential in that.
The idea in one sentenceDecide item by item whether to take it; index the table by the remaining budget (or by the target value), which is a number, so the table is only as small as that number.
Budget-indexedValue-indexed
EntryT(i, b) = max value from items 1..i with size ≤ bD[i, v] = min size from items 1..i with value exactly v
Recurrencemax(T(i−1, b), vi + T(i−1, b − si))min(D[i−1, v], si + D[i−1, v − vi])
AnswerT(n, B)max v with D[n, v] ≤ B
TimeO(nB)O(n·Σv) = O(n² vmax)

Both are pseudo-polynomial: polynomial in the value of a number, exponential in its number of bits. The value-indexed one is what the FPTAS uses: shrink the values and it becomes fast.

b=012345678910i=000000000000i=1 (1: s=6, v=30)0000003030303030i=2 (2: s=3, v=14)0001414143030304444i=3 (3: s=4, v=16)0001416163030304446i=4 (4: s=2, v=9)0091416233030394446green = item taken (value jumps by v_i, budget drops by s_i);yellow = item skipped (copy from the row above).D[4,10] = 46: skip 4, take 3 (16 + D[2,6]), skip 2, take 1 (30 + D[0,0]) → items {1, 3}.
Budget-indexed knapsack table D[i,b] for sizes (6, 3, 4, 2), values (30, 14, 16, 9), B = 10, with the traceback arrows.
How to read this figure Rows are items (sizes 6, 3, 4, 2; values 30, 14, 16, 9), columns are budgets 0..10. A cell is the better of "skip" (the cell above) and "take" (vi + the cell one row up, si columns left). The arrows retrace the choices from the corner: items 1 and 3, value 46.
Summary card
  • Budget DP: T(i, b), O(nB). Value DP: D[i, v] = min size, O(n² vmax). Both pseudo-polynomial.
  • Traceback: T(i, b) ≠ T(i−1, b) ⇒ item i taken; move to b − si.
Recall check
Value-indexed DP: what is stored and what is the answer?
D[i, v] = minimum total size achieving value exactly v with items 1..i; the answer is the largest v with D[n, v] ≤ B.
✍ U1A.36Budget-indexed knapsack DP (Practice Exam U1 Q4) Practice examguided proof
Source: practice-exams/Practice_Exam_Unit_1_Solutions.pdf Q4; instance from Lec 4
Knapsack: budget B, item i has size si ∈ {1..B} and value vi > 0; choose I with Σ si ≤ B maximizing Σ vi. (1) Define DP entries T(i, b) whose running time depends only on n and B. (2) Recurrence with justification. (3) Runtime, and is it polynomial? (4) Fill the table for sizes s = (6, 3, 4, 2), values v = (30, 14, 16, 9), budget B = 10, and recover the items.
Show solution

(1) T(i, b) = maximum total value using only items 1..i with total size at most b (0 ≤ i ≤ n, 0 ≤ b ≤ B).

(2) T(0, b) = 0, T(i, 0) = 0. For i ≥ 1: T(i, b) = T(i−1, b) if si > b; otherwise T(i, b) = max( T(i−1, b), vi + T(i−1, b − si) ). Item i is either skipped (best from 1..i−1 with budget b) or taken (it uses si of the budget, the rest is filled optimally from 1..i−1). Answer T(n, B).

(3) (n+1)(B+1) entries × O(1) = O(nB). Pseudo-polynomial: B is written in log B bits, so nB is exponential in the input size.

(4) Rows i = 0..4, columns b = 0..10:

i=00 0 0 0 0 0 0 0 0 0 0
i=10 0 0 0 0 0 30 30 30 30 30
i=20 0 0 14 14 14 30 30 30 44 44
i=30 0 0 14 16 16 30 30 30 44 46
i=40 0 9 14 16 23 30 30 39 44 46

OPT = T(4, 10) = 46. Traceback: T(4,10) = T(3,10) (item 4 skipped); T(3,10) = 46 ≠ T(2,10) = 44, so item 3 is taken, go to T(2, 6) = 30 = T(1, 6): item 2 skipped, item 1 taken. Items {1, 3}, size 10.

Rubric: what earns the points
  • T(i,b) in words with ranges
  • base cases
  • two-case recurrence with s_i ≤ b guard
  • justification
  • O(nB) + pseudo-polynomial
Where partial credit is lost
  • Say “at most b” (not “exactly b”) or the base cases change.
  • Guard the take-case with si ≤ b.
  • Pseudo-polynomial: explain in terms of bits of B.
✍ U1A.37Value-indexed knapsack DP (Lec 4) Lectureshort answer
Source: Lec 4 board
(a) Give the value-indexed DP: entries, recurrence, answer, runtime. (b) Why is it also only pseudo-polynomial? (c) For sizes s = (6, 3, 4, 2), values v = (30, 14, 16, 9), budget B = 10, how many cells does each DP fill?
Show solution

(a) D[i, v] = minimum total size of a subset of items 1..i with total value exactly v (∞ if none). D[0, 0] = 0, D[0, v > 0] = ∞. D[i, v] = min( D[i−1, v], si + D[i−1, v − vi] ) (second term only if v ≥ vi). Answer: the largest v with D[n, v] ≤ B. Values range over 0..V with V = Σvi ≤ n·vmax: O(nV) = O(n² vmax).

(b) vmax takes log vmax bits, so n²vmax is exponential in the input size. It becomes polynomial if values are small, which is exactly what the FPTAS arranges by scaling.

(c) Budget DP: 55 cells. Value DP: V = 69, so 350 cells. Largest value with size ≤ 10 is still 46 (value 55 needs size 12 > 10).

Where partial credit is lost
  • Here “exactly v” is required (minimizing size for each exact value), and the answer is a search over v, not the last cell.

24.2 FPTAS and reading approximation guarantees

Warm-up: try from memory first
The FPTAS's K and runtime?
K = ε·vmax/n; scaled values ⌊vi/K⌋ ≤ n/ε; value DP in O(n²·n/ε) = O(n³/ε).
ALG = 80 with ALG ≥ (4/5)OPT. Bounds on OPT?
80 ≤ OPT ≤ 100.
The idea in one sentenceRound values down to multiples of K so the value DP is fast; each item loses less than K, so the total loss is less than nK = ε·vmax ≤ ε·OPT.
  1. Algorithm: K = ε·vmax/n; v̂i = ⌊vi/K⌋; solve exactly with the value DP on v̂; output that set.
  2. Guarantee: let I* be optimal. The output S is best for v̂, so K·ΣSv̂ ≥ K·ΣI*v̂ ≥ ΣI*(vi − K) ≥ OPT − nK. And ΣSv ≥ K·ΣSv̂. So ALG ≥ OPT − ε·vmax ≥ (1 − ε)OPT, using OPT ≥ vmax (every item fits alone).
  3. Time: v̂i ≤ vmax/K = n/ε, so O(n² · n/ε) = O(n³/ε).

PTAS vs FPTAS: a PTAS is polynomial for each fixed ε (n1/ε allowed); an FPTAS is polynomial in n and 1/ε. Pushing ε below 1/(n·vmax) would solve knapsack exactly (HW2 #6.3), so no FPTAS can be polynomial there.

Reading a guarantee (Exam 1A Q1c, you scored 0/5):

Problem typeFrom feasibilityFrom the guarantee
Maximization, ALG ≥ α·OPT (α ≤ 1)OPT ≥ ALGOPT ≤ ALG/α
Minimization, ALG ≤ α·OPT (α ≥ 1)OPT ≤ ALGOPT ≥ ALG/α
Traps
  • Always give both bounds; one comes from feasibility, one from the guarantee.
  • "PTAS = polynomial in 1/ε" is false (that's FPTAS).
Summary card
  • K = εvmax/n · round down · value DP · loss < nK ≤ εOPT · O(n³/ε).
  • Max: ALG ≤ OPT ≤ ALG/α. Min: ALG/α ≤ OPT ≤ ALG.
Recall check
Which fact justifies nK = εvmax ≤ εOPT?
OPT ≥ vmax, because the most valuable item fits on its own (si ≤ B).
Minimization, ALG = 12, ALG ≤ 2·OPT: bounds?
6 ≤ OPT ≤ 12.
✍ U1A.40Bounds on OPT from an approximation guarantee (Exam 1A Q1c): redo Past examshort answer
Source: exams/Exam1_SecA_Soln.pdf p1
A knapsack approximation algorithm returns a feasible solution of value 80 and guarantees a value of at least (1 − ε)OPT with ε = 1/5. What lower and upper bounds on OPT follow?
Show solution

80 ≤ OPT ≤ 100.

  1. Lower: the returned solution is feasible, so OPT ≥ 80.
  2. Upper: the guarantee says 80 ≥ (1 − 1/5)·OPT = (4/5)OPT, so OPT ≤ 80·5/4 = 100.

General rule (maximization): ALG ≤ OPT ≤ ALG/α for an α-approximation. (Minimization: ALG/α ≤ OPT ≤ ALG with α ≥ 1.)

Rubric: what earns the points
  • lower bound 80 from feasibility
  • upper bound 100 from the guarantee
Where partial credit is lost
  • You scored 0/5 with “64 ≤ OPT ≤ 120”. Lower bound: you multiplied 80 by 4/5, but feasibility already gives OPT ≥ 80 (a feasible solution can't beat the optimum). Upper bound: 80/(4/5) = 80·5/4 = 100, not 120 (arithmetic slip).
  • Both bounds are needed: feasibility gives one, the guarantee gives the other. Divide by (1 − ε), don't multiply.
✍ U1A.41Bounds drill: three more guarantees New drillshort answer
Source: New drill (Exam 1A Q1c pattern)
For each, give the tightest bounds on OPT. (a) Maximization, ALG = 45 with ALG ≥ (1 − ε)OPT, ε = 1/10. (b) Minimization (vertex cover), ALG = 12 with ALG ≤ 2·OPT. (c) Maximization, ALG = 30 with ALG ≥ OPT/2.
Show solution
  1. 45 ≤ OPT ≤ 45/(9/10) = 50.
  2. For minimization feasibility gives OPT ≤ 12, and 12 ≤ 2·OPT gives OPT ≥ 6: 6 ≤ OPT ≤ 12.
  3. 30 ≤ OPT ≤ 60.
Where partial credit is lost
  • Which side feasibility bounds depends on max vs min: write that first.
✍ U1A.38FPTAS by hand Lecturecalculation
Source: Lec 5 board (FPTAS); instance from Lec 4
Run the knapsack FPTAS with ε = 1/2 on sizes s = (6, 3, 4, 2), values v = (30, 14, 16, 9), budget B = 10: compute K = ε·vmax/n, the scaled values v̂i = ⌊vi/K⌋, the best scaled set, its true value, and check the guarantee.
Show solution
  1. K = (1/2)·30/4 = 15/4 = 3.75.
  2. v̂ = (⌊30/3.75⌋, ⌊14/3.75⌋, ⌊16/3.75⌋, ⌊9/3.75⌋) = [8, 3, 4, 2]. Every scaled value is ≤ n/ε = 8.
  3. Exact DP on scaled values: best scaled value 12 with items {1, 3}.
  4. True value 46. Guarantee: ≥ OPT − nK = 46 − 15 = 31 ≥ (1 − ε)OPT = 23 ✓ (here we even hit OPT).
Where partial credit is lost
  • Round down; the loss per item is < K, so the total loss is < nK = ε·vmax ≤ ε·OPT.
✍ U1A.39FPTAS guarantee and runtime (HW2 #6.1–6.2) HWguided proof
Source: algo-part1-notes/HW2_Solutions.pdf §6
The PTAS from class runs the O(n² max vi) DP on values rounded down to multiples of K. (1) Show it returns a feasible set of value V with 1 − nK/max vi ≤ V/V' ≤ 1, where V' = OPT. (2) Choose K so that V/V' ≥ 1 − ε in poly(n, 1/ε) time.
Show solution

(1) Let I be an optimal set (value V'). It stays feasible (sizes and B unchanged). Rounded values satisfy v'i ≥ vi − K. The algorithm's set is optimal for rounded values, so its true value V is at least its rounded value, which is at least I's rounded value:

V/V' ≥ Σi∈I v'i / Σi∈I vi ≥ Σi∈I(vi − K)/V' = 1 − |I|K/V' ≥ 1 − nK/V' ≥ 1 − nK/max vi.

The last step uses V' ≥ max vi: the single most valuable item fits (si ≤ B). V/V' ≤ 1 since V' is optimal.

(2) K = ε·max vi/n gives V/V' ≥ 1 − ε. Scaled values are ≤ max vi/K = n/ε, so the DP takes O(n² · n/ε) = O(n³/ε): polynomial in n and 1/ε (an FPTAS).

Rubric: what earns the points
  • optimal set stays feasible
  • rounding loses < K per item
  • chain of inequalities
  • V' ≥ max v_i justified
  • K = ε max v / n
  • O(n³/ε)
Where partial credit is lost
  • Name V' ≥ max vi and why (every item fits alone).
  • Compare against the optimal set's rounded value, not the algorithm's.
✍ U1A.42Why no polynomial (1 − ε)-approximation for tiny ε (HW2 #6.3) HWguided proof
Source: algo-part1-notes/HW2_Solutions.pdf §6.3
Suppose a polynomial-time algorithm achieved a (1 − ε)-approximation to knapsack (integer values) for ε < 1/(n·max vi). Show P = NP.
Show solution
  1. Let V be the algorithm's value and V' = OPT. Then V ≥ (1 − ε)V' > V' − V'/(n max vi).
  2. V' ≤ n·max vi (at most all items), so V'/(n max vi) ≤ 1, giving V > V' − 1.
  3. V and V' are integers, so V = V': the algorithm solves knapsack exactly in polynomial time.
  4. Knapsack (decision version) is NP-hard, so P = NP.

Numerically: with n = 4, max v = 30 this needs ε < 1/120. The FPTAS with this ε would take O(n³/ε) = O(n⁴ max v): pseudo-polynomial, no contradiction.

Rubric: what earns the points
  • V > V' − V'/(n max v)
  • V' ≤ n max v ⇒ V > V' − 1
  • integers ⇒ exact
  • NP-hard ⇒ P = NP
Where partial credit is lost
  • The integrality step (V > V' − 1 ⇒ V = V') is the whole trick; state it.
✍ U1A.43PTAS vs FPTAS (Practice Exam U1 Q1.7) Practice examshort answer
Source: practice-exams/Practice_Exam_Unit_1_Solutions.pdf Q1.7
True or false: a PTAS achieves a (1 − ε)-approximation in time polynomial in the input size and in 1/ε.
Show solution

False. That is an FPTAS. A PTAS only needs polynomial time for each fixed ε; e.g. n1/ε is allowed. Knapsack's O(n³/ε) algorithm is an FPTAS (hence also a PTAS).

Where partial credit is lost
  • PTAS: poly(n) for each constant ε. FPTAS: poly(n, 1/ε).

24.3 Greedy for knapsack

The idea in one sentenceGreedy by value per unit size is optimal when items can be split, but for 0/1 items it can be arbitrarily bad unless you also consider the best single item.
  • Fractional: sort by density vi/si, take whole items, then a fraction of the next one. Optimal (exchange argument: moving weight to a denser item never hurts).
  • 0/1: the same greedy can be terrible: items (1, 2) and (B, B) give 2 vs B.
  • Fix: max(greedy prefix, best single item) ≥ OPT/2, because prefix + the first item that doesn't fit ≥ fractional OPT ≥ OPT.
Recall check
Why is max(greedy prefix, best item) ≥ OPT/2?
The prefix plus the first item that doesn't fit is worth at least the fractional optimum, which is ≥ OPT; so one of the two parts is worth ≥ OPT/2, and each part is feasible by itself.
✍ U1A.44Greedy for knapsack: fractional vs 0/1 New drillguided proof
Source: New drill (own instance; Lec 5 knapsack greedy discussion)
Items (size, value): (6, 30), (5, 20), (5, 20); budget 10. (a) Fractional knapsack (items may be split): give the greedy rule, the value, and why it is optimal. (b) Run the same greedy on 0/1 knapsack (stop adding when an item doesn't fit, or skip it). Compare with OPT. (c) Show greedy can be arbitrarily bad for 0/1, and give a simple fix with a factor-2 guarantee.
Show solution

(a) Sort by density vi/si (here 5, 4, 4) and take items fully until the next doesn't fit; take a fraction of it. Value 30 + (4/5)·20 = 46. Optimal by exchange: if a solution has room-weight on a lower-density item while a higher-density item is not fully taken, shifting weight to the denser item never decreases value.

(b) 0/1 greedy takes item 1 (size 6); neither remaining item fits: value 30. OPT = items 2 + 3 = 40. Greedy is not optimal for 0/1.

(c) Items (size 1, value 2) and (size B, value B): greedy takes the dense item (2), then the big one doesn't fit; OPT = B. With B = 100 the ratio is 2/100 → unbounded. Fix: return max(greedy prefix, best single item). The greedy prefix plus the first item that doesn't fit has value ≥ fractional OPT ≥ OPT, so one of the two parts has ≥ OPT/2 (each single item fits on its own since si ≤ B). Here max(30, 30) = 30 ≥ 40/2 ✓.

Rubric: what earns the points
  • density order
  • fractional value and exchange argument
  • 0/1 greedy vs OPT
  • bad example
  • max(prefix, best item) ≥ OPT/2 argument
Where partial credit is lost
  • The fractional greedy is optimal; the 0/1 greedy is not. Keep them apart in T/F questions.
  • For the factor 2, compare with the fractional optimum as the upper bound on OPT.

24.4 Finite-horizon MDPs and the Bellman recurrence (Lec 5)

Warm-up: try from memory first
Bellman recurrence with t steps left?
Vt(s) = maxa [ ra(s) + Σs' P(s'|s, a) Vt−1(s') ], V0 ≡ 0.
Does the optimal first action depend on the horizon?
Yes (HW2 #7.1: a2 for T = 2, a1 for T = 3).
The idea in one sentenceSolve backward from the last step: with one step left take the best immediate reward; with t steps left, take the action maximizing "reward now + expected best value with t − 1 steps left".
  • MDP: states S, actions A, reward ra(s) for taking a at s, transition probabilities P(s'|s, a), horizon T (number of actions).
  • Policy: an action for every (state, steps left). Optimal policies can be taken deterministic, but they depend on the steps left.
  • Algorithm: fill V1, V2, …, VT; store the argmax. Time O(T·|A|·|S|²).
  • Write it as a table of Q-values Qt(s, a) = ra(s) + Σ P·Vt−1: graders check the expectations.
invest, r = 0, p = 1/3invest, p = 2/3cash, r = 3, p = 1retry, r = 0, p = 1/2retry, p = 1/2collect, r = 6, p = 1wait, r = 1, p = 1idle, r = 0suwz
The worked-example MDP: from s, cash pays 3 now and ends in the dead state z; invest pays 0 and lands in u (pays 6 per step forever) w.p. 1/3 or in w w.p. 2/3. At w, wait pays 1 and stays; retry pays 0 and moves to u or z with probability 1/2 each.
How to read this figure The worked MDP of U1A.47. Nodes are states; each arrow is one outcome of an action, labelled with the action, its probability, and the reward paid when the action is taken. Arrows from the same action add up to probability 1.
Worked example (U1A.47, t = 3 at s) Q3(s, cash) = 3 + V2(z) = 3. Q3(s, invest) = 0 + (1/3)V2(u) + (2/3)V2(w) = (1/3)·12 + (2/3)·3 = 6. So invest when 3 steps remain, although cash is better with 1 or 2 steps left.

Takeaway: compute every Vt−1 first, then the Q-values; the best action can change with t.

Traps (Exam 1A Q1d: −3.5)
  • Show each first action's expected value, including its immediate reward.
  • Outcomes of one action are averaged, not chosen.
  • Give the second-step action for every reachable state.
Summary card
  • V0 = 0; Vt(s) = maxa[r + Σ P Vt−1]; policy = argmax per (s, t); O(T|A||S|²).
  • Approximate rewards (±ε): optimal for the wrong rewards loses ≤ 2Tε.
Recall check
Where does the |S|² in the runtime come from?
For each of the |S| states and each action, the expectation sums over |S| successor states.
Why is the approximate-reward loss 2Tε and not Tε?
Two transfers: the true optimal policy loses ≤ Tε in the approximate MDP (so ÔPT ≥ OPT − Tε), and π̂ loses ≤ Tε moving back to the true MDP.
✍ U1A.45Two-step MDP policy (Exam 1A Q1d): redo Past examcalculation
Source: exams/Exam1_SecA_Soln.pdf p1
An edge label (a, p, r) means: choose action a, receive immediate reward r, follow this edge with probability p. From s: action a gives reward 0 and goes to u or v with probability 1/2 each; action b gives reward 1 and goes to v. From u: c gives 8, d gives 3 (both to terminal t). From v: c gives 2, d gives 4. Starting at s, you take exactly two actions. Give an optimal policy and the expected total reward of each first action (with the second chosen optimally).
Show solution
(a, 1/2, 0)(a, 1/2, 0)(b, 1, 1)(c, 1, 8)(d, 1, 3)(c, 1, 2)(d, 1, 4)suvt
Exam 1A Q1d. Label (action, probability, reward). The two a-edges are the two outcomes of ONE action. t is terminal.
How to read this figure Each arrow is one possible outcome, labelled (action, probability, reward). The two arrows labelled a leave s together: they are the two random outcomes of the single action a.
  1. Second step first (backward): at u choose c (8 > 3); at v choose d (4 > 2). So V1(u) = 8, V1(v) = 4.
  2. First step: Q(s, a) = 0 + ½·8 + ½·4 = 6; Q(s, b) = 1 + 4 = 5.
  3. Policy: take a at s; then c if at u, d if at v. Expected total reward 6.
Rubric: what earns the points
  • second-step choices c at u, d at v
  • Q(s,a) = 6 shown
  • Q(s,b) = 5 shown
  • policy for all states
Where partial credit is lost
  • You lost 3.5 of 6: the expectations for a and b were missing/wrong. Write both Q-values explicitly, including b's immediate reward 1.
  • A policy specifies an action for every possible second-step state (u and v).
  • The two a-edges are outcomes of one action: average them, don't choose between them.
✍ U1A.46Small MDPs from HW2 and the practice exam (HW2 #7.1, Practice Exam U1 Q1.6) HWcalculation
Source: algo-part2-notes/homeworks/hw2.tex §7.1 + HW2_Solutions.pdf; Practice Exam U1 Q1.6
(a) HW2: states S1–S4. From S1: a1 → S1 (0.2) or S2 (0.8); a2 → S3 (1.0). From S2: a1 → S4, a2 → S3. S3, S4 loop to themselves. Reward 10 for any action at S3, 100 at S4, 0 at S1, S2. Starting at S1, optimal policy for T = 2? And for T = 3? (b) Practice exam: from S1, a1 → S2 (1.0); a2 → S3 (0.2) or S4 (0.8); S2 and S4 loop, S3 → S4. Rewards 0 at S1, S4; 10 at S2; 100 at S3. Optimal policy for T = 2 from S1?
Show solution

(a) T = 2: a1 leads to S1 or S2, where the next pull earns 0: Q = 0. a2 leads to S3, next pull earns 10: Q = 10. Choose a2, then anything.

T = 3: V2(S2) = 100 (a1 to S4, then 100) and V2(S1) = 10. Q(S1, a1) = 0.2·10 + 0.8·100 = 82; Q(S1, a2) = 10 + 10 = 20. Choose a1. The optimal first action changes with the horizon.

(b) a2: 0.2·100 = 20; a1: then 10 at S2 = 10. Choose a2.

Where partial credit is lost
  • Rewards are for pulling an action at a state: the first pull at S1 earns 0 in both MDPs.
  • Always re-solve when T changes (the T = 3 answer flips).
✍ U1A.47Bellman table for a 4-state MDP (new) New drillcalculation
Source: New drill (code-verified by brute force over all policies)
States s, u, w, z. At s: cash pays 3 and moves to z; invest pays 0 and moves to u w.p. 1/3, to w w.p. 2/3. At u: collect pays 6 and stays. At w: wait pays 1 and stays; retry pays 0 and moves to u or z w.p. 1/2 each. At z: idle pays 0. Compute Vt for t = 0..3 (t = steps left) and the optimal action at s and w for each t.
Show solution

V0 ≡ 0; Vt(x) = maxa [ r(x, a) + Σ P(x'|x, a) Vt−1(x') ].

tV(s)V(u)V(w)V(z)Q(s,cash) / Q(s,invest)Q(w,wait) / Q(w,retry)
136103 / 01 / 0
2312303 / 8/32 / 3
3618603 / 64 / 6

Example cell: Q3(s, invest) = 0 + (1/3)·V2(u) + (2/3)·V2(w) = (1/3)·12 + (2/3)·3 = 6. Policy: at s, cash for t = 1, 2 and invest for t = 3; at w, wait for t = 1 and retry for t ≥ 2 (tie 6 vs 4 → retry at t = 3). The optimal policy is non-stationary: it depends on the steps left.

Where partial credit is lost
  • Fill by increasing t (steps left); each Vt uses only Vt−1.
  • Report Q-values, not just the max: graders check the expectations.
✍ U1A.48MDP with approximate rewards (HW2 #7.2) HWguided proof
Source: algo-part1-notes/HW2_Solutions.pdf §7.2
In a finite-horizon-T MDP, each reward ra(s) is replaced by r̂a(s) with |ra(s) − r̂a(s)| ≤ ε; transitions unchanged. Let π̂ be optimal for the modified MDP. Show that π̂ earns at least OPT − 2Tε in the original MDP.
Show solution
  1. Any fixed policy changes by ≤ Tε between the two MDPs: it visits the same distribution over states and actions in both (transitions are unchanged), and each of the T expected rewards differs by ≤ ε.
  2. Let π* be optimal for the original (value OPT) and ÔPT the optimum of the modified MDP.
  3. π* in the modified MDP earns ≥ OPT − Tε, so ÔPT ≥ OPT − Tε.
  4. π̂ earns ÔPT in the modified MDP, so in the original it earns ≥ ÔPT − Tε ≥ OPT − 2Tε. ∎

E.g. T = 5, ε = 0.1: loss at most 1.

Rubric: what earns the points
  • fixed policy differs by ≤ Tε
  • ÔPT ≥ OPT − Tε via π*
  • π̂ in original ≥ ÔPT − Tε
  • combine to OPT − 2Tε
Where partial credit is lost
  • The bound uses two transfers (π* to the modified MDP, π̂ back), each costing Tε: name both.
✍ U1A.49MDP facts (select all) New drillshort answer
Source: New drill (Lec 5 facts)
Select ALL true statements (finite horizon T, |S| states, |A| actions) and justify each in one line.
  1. The bottom-up Bellman algorithm runs in O(T·|A|·|S|²).
  2. For a fixed MDP, the optimal first action is the same for every horizon T.
  3. There is always an optimal policy that is deterministic (no randomization needed).
  4. The optimal expected reward is non-decreasing in T if all rewards are ≥ 0.
Show solution
  • A true: T layers × |S| states × |A| actions × |S| successor terms. (T = 10, |A| = 3, |S| = 100: 300,000 terms.)
  • B false: U1A.46(a): a2 for T = 2, a1 for T = 3 (also Lec 5's example).
  • C true: at each (state, steps left) pick an action attaining the max in Bellman's equation; randomizing can't beat the best action.
  • D true: with one more step you can play the T-step optimal policy and then collect a non-negative reward.

Answer: A, C, D.

Where partial credit is lost
  • Runtime: don't forget the |S| successor sum inside each Q-value.

24.5 Unit 1a short-answer mix

Practice-problem short answers across §21–24: do them cold after finishing the section.

✍ U1A.50Unit 1a short-answer mix (practice problems 1.1–1.5, §2) Practice examshort answer
Source: practice-problems1 §1.1–1.5, §2 (verdicts checked against Practice Problems Explained Solutions)

True or False? Justify in 1–2 lines (a counterexample suffices for False).

  1. Computing F(n) (F(0) = F(1) = 1, F(i) = F(i−1) + F(i−2)) needs Θ(n) space because the whole DP table must be stored.
  2. If f' = O(f) and g' = O(g), then f'/g' = O(f/g). What if both are Θ?
  3. In an MDP where every transition probability is in {0, 0.5, 1}, V*(s, t) can be computed in o(|S|²|A|T) time.
  4. Median of medians with group size M = √n runs in O(n).
  5. There is a polynomial-time algorithm for knapsack when every value vi ∈ {1, …, 10}.
  6. Strassen: 7 multiplications of (n/2) × (n/2) matrices plus O(n²) additions. Recurrence? Is it O(n2.5)? Is it o(n³)?
Show solution
  1. False. Each value needs only the previous two: keep two variables, Θ(1) space, Θ(n) time.
  2. False for O: f = f' = g = 1, g' = 1/n gives f'/g' = n ∉ O(1) (an upper bound on the denominator points the wrong way). True for Θ: dividing c₁f ≤ f' ≤ c₂f by d₁g ≤ g' ≤ d₂g gives (c₁/d₂)(f/g) ≤ f'/g' ≤ (c₂/d₁)(f/g).
  3. True. Probabilities sum to 1 and each non-zero one is ≥ 0.5, so each (s, a) has ≤ 2 successors: O(1) per Q-value, O(|S||A|T) total (with a sparse transition list).
  4. False. Finding the median of each of the n/M groups by sorting costs (n/M)·Θ(M log M) = Θ(n log M) = Θ(n log n) for M = √n.
  5. True. The value-indexed DP runs in O(n·Σv) ≤ O(n·10n) = O(n²).
  6. T(n) = 7T(n/2) + Θ(n²) = Θ(nlog₂7) ≈ Θ(n2.807). Not O(n2.5); yes o(n³) since log₂7 < 3.
Where partial credit is lost
  • Each T/F needs the one-line reason; for False give the concrete counterexample or cost.

25 · Graphs and BFS Lec 6 · practice problems 4.1–4.2

▸ Collapsed: click to expand (2 subsections)▾ Click to collapse

25.1 Representations and breadth-first search

Warm-up: try from memory first
BFS runtime with adjacency lists? With a matrix?
O(n + m) with lists; O(n²) with a matrix.
What does BFS compute, and in which graphs is that a shortest path?
The number of edges from s to every vertex (layers); it is the shortest-path distance when every edge has the same length.
Degree-sum formula?
Σ deg(v) = 2m (undirected).
The idea in one sentenceExplore the graph in rings around s: first everything one edge away, then two, and so on, using a queue so that closer vertices are always processed first.
  • Graph G = (V, E), n = |V|, m = |E|. Adjacency lists use O(n + m) space; a matrix uses O(n²) but answers "is (u, v) an edge?" in O(1).
  • BFS(s): dist[s] = 0, queue = [s]. Pop u; for each neighbour v not yet discovered: dist[v] = dist[u] + 1, parent[v] = u, push v. Each vertex is pushed once and each edge scanned once (twice if undirected): O(n + m).
  • Layers: Ld = vertices at distance d. Every edge joins equal or adjacent layers. The parent pointers form a shortest-path tree.
  • Multi-source BFS: start with several sources in the queue at distance 0 (equivalently, a super-source joined to all of them). One BFS gives every vertex's distance to the nearest source.
  • Expanded graphs: an integer weight w can be replaced by a path of w unit edges, so BFS works for small integer weights in O(n + m + Σ(we − 1)) (Lec 6 board): pseudo-polynomial.
L0 (dist 0)L1 (dist 1)L2 (dist 2)L3 (dist 3)L4 (dist 4)sabcdefgblue = BFS parent tree · dashed = non-tree edges (they join the same or adjacent layers)
BFS from s visits the graph layer by layer; the parent pointers (blue) form a shortest-path tree.
How to read this figure Vertices are arranged by BFS layer (distance from s, left to right). Blue edges are parent pointers: following them back from any vertex gives a shortest path to s. Grey edges are non-tree edges; none of them skips a layer.
Summary card
  • BFS: queue, discover once, dist = parent's + 1, O(n + m); shortest paths for unit weights.
  • Many sources: put them all in the queue first. Small integer weights: subdivide edges (pseudo-polynomial).
Recall check
Why can no edge join layers d and d + 2?
When the vertex in layer d is processed, all its undiscovered neighbours get distance d + 1; so every neighbour has distance ≤ d + 1.
How do you compute the distance from every cell of a grid to the nearest 0 in O(mn)?
Multi-source BFS starting from all 0-cells at distance 0.
✍ U1B.1BFS by hand New drillcalculation
Source: New drill (Lec 6 BFS)
Undirected graph with edges s–a, s–b, a–c, b–c, b–d, c–e, d–e, d–f, e–g, f–g. Run BFS from s (neighbours in alphabetical order). Give the layers, the visiting order, the parent pointers, the non-tree edges, and dist(s, g).
Show solution
  • Layers: L0 = {s} · L1 = {a, b} · L2 = {c, d} · L3 = {e, f} · L4 = {g}.
  • Order: s, a, b, c, d, e, f, g.
  • Parents: a←s, b←s, c←a, d←b, e←c, f←d, g←e.
  • Non-tree edges: b–c, d–e, f–g. Each joins two vertices in the same or adjacent layers, never layers two apart.
  • dist(s, g) = 4. Time O(n + m) = O(8 + 10).
Where partial credit is lost
  • A vertex gets its parent the first time it is discovered (put in the queue), not when it is dequeued.
✍ U1B.2Distance to the nearest 0 in a grid (practice problems 4.1) Practice examdesign + prove
Source: practice-problems1 §4.1; instance new
Given an m × n binary matrix, return for each cell the distance (4-neighbour steps) to the nearest 0. Describe the algorithm, why it is correct, and its runtime. Run it on 1 1 1 0 / 1 1 1 1 / 0 1 1 1.
Show solution

Multi-source BFS. Put every 0-cell in the queue at distance 0 (equivalently: add a super-source joined to all zeros and run one BFS). Then run BFS on the grid graph; a cell's distance is fixed the first time it is reached.

Correctness: BFS from the super-source computes shortest path lengths; a shortest path from the super-source to a cell is "one free step to some 0, then a grid path", so the BFS distance is exactly (distance to the nearest 0).

Runtime: each of the mn cells is enqueued once and has ≤ 4 neighbours: O(mn). Running a separate BFS from each zero would cost O(k·mn).

Result: 2 2 1 0 / 1 2 2 1 / 0 1 2 2 (max distance 2).

Rubric: what earns the points
  • multi-source initialization
  • BFS on grid neighbours
  • correctness via super-source
  • O(mn)
Where partial credit is lost
  • Start with all zeros in the queue at once; one BFS per cell (or per zero) is too slow.
  • Justify with the super-source picture.
✍ U1B.5Graph basics (select all) New drillshort answer
Source: New drill
Select ALL true statements; justify each in one line.
  1. In any undirected graph, Σv deg(v) = 2m, so the number of odd-degree vertices is even.
  2. BFS on an adjacency matrix runs in O(n + m).
  3. In BFS on an undirected graph, every edge joins vertices whose distances differ by at most 1.
  4. BFS computes shortest paths in graphs with arbitrary positive weights.
Show solution
  • A true: each edge adds 1 to the degree of each endpoint; an even total needs an even number of odd terms.
  • B false: scanning a matrix row costs n per vertex: O(n²).
  • C true: if u is at distance d, every neighbour is discovered by the time u is processed, so it is at distance ≤ d + 1.
  • D false: BFS counts edges. s–t of weight 10 vs s–a–t of weights 1, 1: BFS returns the 1-edge path.

Answer: A, C.

Where partial credit is lost
  • Representation matters for runtime: lists O(n + m), matrix O(n²).

25.2 Paths with extra state: layered graphs and weight tricks

The idea in one sentenceWhen a path must satisfy an extra condition (parity, "passes a checkpoint", "fewest red edges first"), build a bigger graph whose vertices also record that state, or encode the priority in the weights, and run the ordinary algorithm.
  • Layered (product) graph: one copy of V per state value; edges move between copies according to how the state changes. Even-length walks: 2 copies, every edge switches copy.
  • Checkpoint: Dijkstra from s plus Dijkstra to t (reversed graph), then minr∈R ds(r) + dt(r); or 2 layers.
  • Lexicographic objectives: weight the primary criterion by a number bigger than any total of the secondary one (red = |V|, blue = 1).
evenodd1111115566s₀s₁b₀b₁a₀a₁t₀t₁copy 0 = an even number of edges used so farcopy 1 = odd so far; every edge switches copies · green: s₀ → a₁ → t₀, length 6
Layered (parity) graph: two copies of every vertex; each original edge u→v becomes u₀→v₁ and u₁→v₀. A shortest s₀→t₀ path is a shortest walk with an even number of edges.
How to read this figure The top row is copy 0 (even number of edges so far), the bottom row copy 1. Each original edge u→v appears twice, u₀→v₁ and u₁→v₀, so every edge flips the row. A shortest s₀→t₀ path is a shortest walk with an even number of edges.
Recall check
How many copies of the graph do you need to find a shortest path using at most k special edges?
k + 1 copies (copy i = i special edges used so far); special edges go from copy i to copy i + 1.
✍ U1B.4Shortest walk with an even number of edges (layered graph) New drilldesign + prove
Source: New drill (layered-graph technique)
Directed graph with weights s→b 1, b→a 1, a→t 1, s→a 5, b→t 6. Find the shortest s–t walk that uses an even number of edges, with a general method.
Show solution

Parity graph: two copies v₀, v₁ of each vertex (subscript = parity of edges used so far). Each edge u→v of weight w becomes u₀→v₁ and u₁→v₀ with weight w. Run Dijkstra from s₀ to t₀.

Here: the shortest walk overall is s→b→a→t of length 3 (3 edges, odd). The shortest even one is s→a→t of length 6. The new graph has 8 vertices and 10 edges: twice the original, so the runtime is the same order.

Pattern: "shortest path with a state" (parity, number of special edges used up to k, fuel) = copy the graph once per state value.

Rubric: what earns the points
  • two copies per vertex
  • edges switch parity
  • Dijkstra from s₀ to t₀
  • runtime O((n+m) log n)
Where partial credit is lost
  • The edge must switch layers (u₀→v₁), otherwise parity isn't tracked.
✍ U1B.3Fewest red edges, then fewest blue (practice problems 4.2) Practice examdesign + prove
Source: practice-problems1 §4.2
Edges of G are red or blue. Among all s–t paths with the minimum number of red edges, find one with the minimum number of blue edges. Give an algorithm, its correctness, and runtime.
Show solution

Option 1 (weights): give each red edge weight N = |V| and each blue edge weight 1, and run Dijkstra (or BFS on the expanded graph). A simple path has ≤ |V| − 1 blue edges, so one extra red edge (+N) always outweighs any number of blue edges; minimizing N·(#red) + (#blue) minimizes #red first, then #blue.

Option 2 (pairs): Dijkstra with path length (#red, #blue) compared lexicographically; adding a pair is monotone and non-decreasing, so Dijkstra's proof goes through (HW2 #8 appendix).

Runtime O((n + m) log n).

Rubric: what earns the points
  • weights N vs 1 (or lexicographic pairs)
  • why N dominates
  • Dijkstra applies (non-negative / monotone)
  • runtime
Where partial credit is lost
  • Justify why the weight N is large enough (a path has fewer than |V| blue edges).

26 · Shortest paths: Dijkstra Lec 6 · HW2 #8 · Exam 1A Q1f

▸ Collapsed: click to expand (2 subsections)▾ Click to collapse

26.1 Dijkstra's algorithm and why it is correct

Warm-up: try from memory first
Write Dijkstra in four lines.
d[s] = 0, others ∞, all in a min-heap. Extract u with minimum d and mark it settled. For each edge (u, v) to an unsettled v: if d[u] + w(u, v) < d[v], update d[v] and parent[v] = u. Repeat until the heap is empty.
Runtime with a binary heap?
O((n + m) log n).
Which assumption does the correctness proof need?
Non-negative edge weights.
The idea in one sentenceLike BFS, but the "next ring" is chosen by distance: the unsettled vertex with the smallest tentative distance can't be improved by any detour, because every detour leaves the settled region and only gets longer.
  1. d[s] = 0, d[v] = ∞ otherwise; a min-priority queue keyed by d.
  2. Extract the vertex u of minimum key; it is settled.
  3. Relax each edge (u, v) with v unsettled: if d[u] + w(u, v) < d[v], set d[v] = d[u] + w(u, v), parent[v] = u.
  4. Repeat until the queue is empty. n extract-mins and ≤ m decrease-keys: O((n + m) log n) with a binary heap; O(m + n log n) with Fibonacci heaps (optional, Lec 6).

Correctness (proof idea from the board): let u be the first vertex settled with a wrong distance, and take a shortest s–u path. Its first edge (x, y) leaving the settled set was relaxed when x (correct) was settled, so d[y] ≤ dist(s, y). Non-negative weights give dist(s, y) ≤ dist(s, u) < d[u], so y should have been extracted before u. Contradiction (full write-up: U1B.10).

Generalized Dijkstra (HW2 #8 appendix): the proof only uses that extending a path never makes it shorter and that ⊕ is monotone. So path "length" = max edge (bottleneck) or lexicographic pairs also work.

412153sabcdd=0 (1st)d=3 (3rd)d=1 (2nd)d=4 (4th)d=6 (5th)settle order:s, b, a, c, dc–d (3) is not used:4 + 3 = 7 > 6
Dijkstra on the Lec 6 board graph: blue edges form the shortest-path tree; labels give the final distance and the order of settling.
How to read this figure The Lec 6 board graph. Each vertex shows its final distance and its settling order; blue edges form the shortest-path tree. After settling s and b, a's tentative distance drops from 4 to 3 via b.
Why is it done this way?
Why can't Dijkstra handle negative edges?Once u is settled it is never revisited. With a negative edge, a path through a vertex that is still far away can end up shorter (s→a 2, s→b 3, b→a −2: a settles at 2, the true distance is 1).
Why does "add a constant to every edge" not fix negative edges?A path with k edges gains k times the constant, so paths with many edges are penalized and the shortest path can change (U1B.9).
Summary card
  • Extract-min, settle, relax; O((n + m) log n); needs w ≥ 0.
  • Proof: first wrong vertex u; first edge (x, y) leaving the settled set; d[y] ≤ dist(s, y) ≤ dist(s, u) < d[u]: contradiction.
  • Works for any monotone non-decreasing path cost (max edge, lexicographic pairs).
Recall check
In the correctness proof, which exact inequality uses non-negative weights?
dist(s, y) ≤ dist(s, u): the prefix of a shortest path is no longer than the whole path.
How do you change Dijkstra to minimize the maximum edge on a path?
Relax with d[v] = min(d[v], max(d[u], w(u, v))).
✍ U1B.6Dijkstra on the Lec 6 board graph Lecturecalculation
Source: Lec 6 board p3 (graph and d values match the board)
Undirected graph: s–a 4, s–b 1, a–b 2, a–c 1, c–d 3, b–d 5. Run Dijkstra from s: give the settling order, the tentative distances after each settle, the final distances and the shortest-path tree.
Show solution
  1. Settle s (0): d[a] = 4, d[b] = 1.
  2. Settle b (1): d[a] = min(4, 1 + 2) = 3, d[d] = 1 + 5 = 6.
  3. Settle a (3): d[c] = 3 + 1 = 4.
  4. Settle c (4): d[d] = min(6, 4 + 3) = 6 (no change).
  5. Settle d (6).

Order s, b, a, c, d; final d[s] = 0, d[b] = 1, d[a] = 3, d[c] = 4, d[d] = 6; tree b←s, a←b, c←a, d←b.

Where partial credit is lost
  • Write the tentative-distance updates, not only the final answer: that's where partial credit sits.
✍ U1B.7Dijkstra drill (directed) New drillcalculation
Source: New drill
Directed edges: s→a 7, s→b 2, b→a 3, b→c 8, a→c 2, a→d 6, c→d 1, c→t 7, d→t 3, b→d 9. Run Dijkstra from s. Give the order, final distances, and the shortest s–t path.
Show solution

Order: s, b, a, c, d, t. Final: d[s] = 0, d[b] = 2, d[a] = 5, d[c] = 7, d[d] = 8, d[t] = 11.

Key updates: b settles at 2 and lowers a to 2 + 3 = 5; a lowers c to 5 + 2 = 7; c lowers d to 8 (beating 11 via a and via b); d lowers t to 11 (beating 14 via c).

Shortest path s → b → a → c → d → t, length 11.

Where partial credit is lost
  • Recover the path from parent pointers, backwards from t.
✍ U1B.10Dijkstra correctness (Lec 6) Lectureguided proof
Source: Lec 6 board p4 (proof idea)
Prove: if all edge weights are non-negative, then when Dijkstra extracts a vertex u, d[u] = dist(s, u).
Show solution

Minimal counterexample. Suppose not, and let u be the first vertex extracted with d[u] > dist(s, u). Take a shortest s–u path P.

  1. When u is extracted, s is settled and u isn't, so P has a first edge (x, y) with x settled and y unsettled.
  2. x was settled before u, so d[x] = dist(s, x) (u is the first error). When x was settled, the edge (x, y) was relaxed: d[y] ≤ dist(s, x) + w(x, y) = dist(s, y) (P's prefix is a shortest path).
  3. Non-negative weights: the prefix of P up to y is no longer than P: dist(s, y) ≤ dist(s, u).
  4. So d[y] ≤ dist(s, u) < d[u]. But u was extracted with the minimum key, so d[u] ≤ d[y]. Contradiction. ∎

Runtime with a binary heap: n extract-mins and ≤ m decrease-keys, O((n + m) log n).

Rubric: what earns the points
  • first wrong vertex u
  • first edge leaving the settled set
  • d[y] ≤ dist(s,y) by relaxation
  • non-negativity ⇒ dist(s,y) ≤ dist(s,u)
  • contradiction with min key
Where partial credit is lost
  • Point to the exact line that needs non-negative weights (step 3).
  • Use “first incorrectly settled vertex”; otherwise you can't assume x is correct.
✍ U1B.11Walking on the plane: bottleneck paths (HW2 #8) HWdesign + prove
Source: algo-part2-notes/homeworks/hw2.tex §8 + HW2_Solutions.pdf; (3) instance new
n points in the plane; at time t each is the centre of a circle of radius t. Find the earliest t at which you can walk from point u to point v staying inside the union of circles. (1) Solve in O(n² log n) with a modified Dijkstra; explain why it works. (2) If the MST of the complete graph (Euclidean weights) is given, solve it in O(n). (3) Run the modified Dijkstra from A on the graph A–B 4, A–C 2, B–C 5, B–D 10, C–E 3, D–E 7, D–F 6, E–F 8, C–D 9 (bottleneck to F), and compare with the ordinary shortest A–F path.
Show solution

Model: complete graph with Euclidean edge weights. Two circles touch at time t iff their centres are ≤ 2t apart, so u, v are connected at time t iff some u–v path has maximum edge weight ≤ 2t. Answer = (min over paths of the max edge) / 2.

(1) Dijkstra with "path length" = max edge weight: relax d[v] ← min(d[v], max(d[u], w(u,v))). Dijkstra's proof only uses that extending a path never decreases its length and is monotone; max has both properties. On the complete graph: O(n² log n) (or O(n²) with an array).

(2) The MST path between u and v minimizes the maximum edge (exchange argument: if another path had a smaller maximum, removing the MST path's max edge and reconnecting the two sides with an edge of that path gives a lighter spanning tree). DFS in the tree: O(n).

(3) Settling order A, C, E, B, D, F; bottleneck values b[C] = 2, b[E] = 3, b[B] = 4, b[D] = 7, b[F] = 7. Bottleneck to F = 7 along the MST path A–C–E–D–F. The ordinary shortest path A–C–E–F has length 13 but maximum edge 8: shortest ≠ bottleneck.

Rubric: what earns the points
  • reduction to min-max path (both directions)
  • modified relaxation with max
  • why Dijkstra's proof still works
  • O(n² log n)
  • (2) MST path + exchange argument
  • (2) O(n)
Where partial credit is lost
  • Argue both directions of “connected at time t ⇔ a path with all edges ≤ 2t”.
  • Say which property of + Dijkstra's proof needs (monotone, non-decreasing) and that max has it.
  • Return half the bottleneck value.
✍ U1B.12Shortest path through a checkpoint New drilldesign + prove
Source: New drill
Directed graph, non-negative weights, a set R of checkpoint vertices. Find the shortest s–t path that visits at least one vertex of R. Run it on s→a 2, a→t 2, s→r1 4, r1→t 5, a→r2 1, r2→t 2, s→t 3 with R = {r1, r2}.
Show solution
  1. Dijkstra from s gives ds(·). Dijkstra from t on the reversed graph gives dt(x) = dist(x, t).
  2. Answer = minr∈R ds(r) + dt(r); splice the two paths at the best r.
  3. Correct because any path through r costs at least dist(s, r) + dist(r, t), and that value is achieved.

Two Dijkstras: O((n + m) log n). Example: via r1 9, via r2 5 (s→a→r2→t); answer 5 (the unrestricted shortest path costs 3). Alternative: layered graph (copy 0 before visiting R, copy 1 after).

Rubric: what earns the points
  • Dijkstra from s
  • Dijkstra to t on reversed graph
  • min over r with justification
  • runtime
Where partial credit is lost
  • Distances to t need the reversed graph in a directed graph.

26.2 Weight transformations and counterexamples (Exam 1A Q1f)

The idea in one sentenceA transformation preserves shortest paths only if it changes every path's length in an order-preserving way; anything that depends on the number of edges (adding a constant) or is non-linear (squaring) can reorder paths.
TransformationShortest pathsMST
w ↦ c·w, c > 0preservedpreserved
w ↦ w + ccan change (paths have different edge counts)preserved (all trees have n − 1 edges)
w ↦ w² (w > 0)can change (3 vs 2 + 2 → 9 vs 8)preserved (order of weights unchanged)
w ↦ w² with negative weights—can change (−3 becomes 9)
Worked example (Exam 1A Q1f) s→u 1, u→t 1, s→t 3: the two-edge path wins (2 < 3). Add 7: two-edge path 16, direct path 10, so the direct path wins.

Takeaway: for every T/F about transformations, test two paths with different numbers of edges.

Traps
  • You answered "True" on Exam 1A Q1f (−5). A counterexample needs explicit weights and both paths' costs before and after.
Recall check
Give a 3-edge counterexample to "adding a constant preserves shortest paths".
s→u 1, u→t 1, s→t 3; add 7: 16 vs 10.
Why does adding a constant preserve the MST?
Every spanning tree has exactly n − 1 edges, so every tree's weight rises by the same (n − 1)c.
✍ U1B.8Adding a constant to every edge (Exam 1A Q1f): redo Past examshort answer ★ Past exam / HW · B16
Source: exams/Exam1_SecA_Soln.pdf p2
True or false: in a directed graph with positive edge weights, adding 7 to every edge weight leaves the set of shortest paths from s to t unchanged. If false, give a small counterexample with edge weights.
Show solution

False. Edges s→u 1, u→t 1, s→t 3. Before: s→u→t costs 2 < 3. After adding 7: s→t costs 10, s→u→t costs 16. The shortest path changes.

Why: a path with k edges gains 7k, so paths with more edges are penalized more.

Rubric: what earns the points
  • verdict False
  • concrete graph with weights
  • costs before and after shown
Where partial credit is lost
  • You lost all 5 points (“wrong answer”). The question asks for a counterexample with weights: give the graph, both path costs before, both after.
  • Contrast: multiplying every weight by a positive constant does preserve shortest paths, and adding a constant does preserve MSTs (every spanning tree has n − 1 edges).
✍ U1B.9Weight transformations: counterexample bank (select all) New drillshort answer
Source: New drill (calc_u1b counterexample bank, checked by enumeration)
Select ALL transformations that always preserve the set of shortest s–t paths (directed, positive weights). Give a counterexample for each one that doesn't.
  1. w ↦ 5w
  2. w ↦ w + 2
  3. w ↦ w²
  4. w ↦ w/2 + 0 (halving)
Then: (E) Dijkstra with one negative edge s→a 2, s→b 3, b→a −2: what does it output for a? (F) Does "add 2 to every edge to make them non-negative" fix it?
Show solution
  • A, D preserve: every path's length is scaled by the same positive factor, so the order of paths is unchanged.
  • B fails: Exam 1A Q1f (U1B.8).
  • C fails: s→t 3 vs s→u→t 2 + 2: before 3 < 4 (direct wins); squared: 9 vs 8 (two-edge path wins).
  • E: Dijkstra settles a first with d[a] = 2 and never updates it; the true distance is 1 (via b). The proof's step "the prefix to the first unsettled vertex is no longer than the whole path" needs non-negative weights.
  • F: No. Weights become s→a 4, s→b 5, b→a 0: direct 4 beats via-b 5, but in the original graph via-b is shorter. Shifting penalizes paths with more edges (same reason as B).

Answer: A and D.

Where partial credit is lost
  • For any “transformation preserves X” question, check whether it changes paths with different edge counts differently.

27 · Minimum spanning trees Lec 6–7 · Practice Exam U1 Q1.5 · practice problems 1.6

▸ Collapsed: click to expand (1 subsections)▾ Click to collapse

27.1 The cut property, Kruskal and Prim

Warm-up: try from memory first
State the cut property, including the "some / every" distinction.
A lightest edge crossing a cut is in some MST; if it is the unique lightest crossing edge, it is in every MST.
Prim vs Kruskal in one line each?
Prim: grow one tree from a root, always adding the lightest edge leaving it. Kruskal: scan edges by weight, add an edge unless it closes a cycle.
Is an MST a shortest-path tree?
No (triangle 2, 2, 3).
The idea in one sentenceWhenever you split the vertices into two groups, the spanning tree must use some edge between them, and swapping in the cheapest such edge can never hurt.
  • MST: a spanning tree T minimizing w(T) = Σe∈T w(e) in a connected undirected graph. Some optimal connected subgraph is a tree (remove a cycle edge: still connected, not more expensive).
  • Cut (S, V∖S): the edges with one endpoint on each side.
  • Cut property: a minimum-weight crossing edge e is in some MST (exchange: T + e has a cycle, which crosses the cut again at some f ∈ T with w(f) ≥ w(e); T + e − f is an MST). Unique light edge ⇒ in every MST.
  • Cycle property: the unique heaviest edge of a cycle is in no MST.
  • Prim: S = {r}; repeatedly add the lightest edge leaving S (a light edge of the cut (S, V∖S)). Heap keyed by key[v] = lightest edge from S to v: O((n + m) log n) = O(m log n).
  • Kruskal: sort edges; add each edge unless both ends are already connected (union-find): O(m log m). Each added edge is a light edge of the cut "its component vs the rest".
  • Prim's key = one edge's weight; Dijkstra's key = a path length. Negative weights are fine for MSTs.
S = {A, B, C}V∖S4251037689ABCEDFcrossing edges (red): B–D 10, C–D 9, C–E 3 · unique light edge C–E (green) ⇒ in every MST
The cut (S, V∖S) with S = {A, B, C}. Its crossing edges are red; the lightest one, C–E of weight 3, is the unique light edge, so every MST contains it.
How to read this figure The red edges cross the cut between S = {A, B, C} and the rest. The lightest one, C–E (weight 3), is the unique light edge, so every MST contains it. Other cuts certify other edges.
Why is it done this way?
Why only "some" MST when there are ties?With two equally light crossing edges, the exchange can produce an MST with either one, so neither is forced. The strict inequality in the exchange (which forces the edge into every MST) needs uniqueness.
Why are distinct weights enough for a unique MST?Every cut then has a unique light edge, so every edge chosen by Kruskal or Prim is in every MST.
Traps
  • Swapping "some" and "every" in a T/F is the classic trap ★ Flagged in lecture · B10.
  • "MST = shortest-path tree" and "Prim fails with negative weights" are both false.
Summary card
  • Cut property (some / unique ⇒ every) via exchange T + e − f. Cycle property: unique heaviest edge of a cycle is in no MST.
  • Prim O(m log n), Kruskal O(m log m). Distinct weights ⇒ unique MST.
  • Adding a constant keeps MSTs; MST path between u and v minimizes the maximum edge (HW2 #8).
Recall check
In the exchange proof, why must the cycle in T + e contain another crossing edge?
The cycle goes from one side of the cut to the other via e, and must come back to its start, so it crosses the cut an even number of times.
Which cut proves the lightest edge at u is in some MST?
({u}, V∖{u}).
When does Kruskal reject an edge?
When both endpoints are already in the same component (it would close a cycle).
✍ U1B.13Kruskal and Prim by hand New drillcalculation
Source: New drill
Undirected graph GM: A–B 4, A–C 2, B–C 5, B–D 10, C–E 3, D–E 7, D–F 6, E–F 8, C–D 9. (a) Run Kruskal: list accepted and rejected edges in order. (b) Run Prim from A: list edges in the order added. (c) MST weight?
Show solution
4 [3]2 [1]5103 [2]7 [5]6 [4]89ABCEDFgreen = the MST (weight 22); [k] = Kruskal's k-th pick · dashed = rejected (each closes a cycle)
Kruskal on G_M: picks in weight order 2, 3, 4, 6, 7 and rejects 5, 8, 9, 10 because each would close a cycle.
How to read this figure Thick edges are the MST; numbers are weights. Kruskal took them in weight order 2, 3, 4, 6, 7; each thin edge would have closed a cycle when its turn came.

(a) Kruskal (sort, add unless it closes a cycle): accepted AC (2), CE (3), AB (4), DF (6), DE (7); rejected BC (5), EF (8), CD (9), BD (10) (each joins two vertices already connected).

(b) Prim from A (add the lightest edge leaving the tree): AC (2), CE (3), AB (4), ED (7), DF (6). Same tree, different order.

(c) Weight 22. Distinct weights ⇒ this MST is unique.

Where partial credit is lost
  • For each rejected Kruskal edge, name the cycle it would close.
  • Prim compares only edges crossing (tree, rest), not all remaining edges.
✍ U1B.14Cut property: statement and exchange proof (Lec 6) Lectureguided proof ★ Flagged in lecture · B10
Source: Lec 6 board p5
State the cut property and prove it. Include what changes when the light edge is unique.
Show solution
SV∖Sf ∈ T* (removed)e (light edge, added)uxyvT* ∪ {e} has one cycle; it crosses the cut on e and again on some f; swap: T′ = T* + e − f
Exchange argument: the tree path from u to v (blue, plus f) must cross the cut somewhere; replacing that crossing edge f by the light edge e keeps a spanning tree and does not increase the weight.
How to read this figure The tree path from u to v (blue) plus the light edge e forms a cycle; it crosses the cut at e and again at some tree edge f. Swapping f for e keeps a spanning tree and doesn't increase the weight.

Cut property. Let e be a minimum-weight edge crossing a cut (S, V∖S). Then some MST contains e. If e is the unique lightest crossing edge, every MST contains e.

  1. Let T be an MST. If e ∈ T, done. Otherwise T + e contains a cycle through e.
  2. That cycle crosses the cut via e, so it must cross back via another edge f ∈ T that also crosses the cut.
  3. w(e) ≤ w(f) since e is lightest across the cut. T' = T + e − f is a spanning tree (removing a cycle edge keeps it connected, n − 1 edges) with w(T') ≤ w(T), so T' is an MST containing e.
  4. If e is the unique lightest, w(e) < w(f), so w(T') < w(T): impossible for an MST T. Hence every MST contains e. ∎
Rubric: what earns the points
  • statement with some/every
  • T + e has a cycle
  • cycle crosses back via f
  • exchange T + e − f, weight ≤
  • uniqueness ⇒ strict ⇒ every MST
Where partial credit is lost
  • “Some” vs “every”: only a unique light edge is in every MST (ties!).
  • Explain why the cycle must cross the cut a second time.
✍ U1B.15Lightest edge at a vertex (Practice Exam U1 Q1.5) Practice examshort answer ★ Past exam / HW · B19
Source: practice-exams/Practice_Exam_Unit_1_Solutions.pdf Q1.5
Given a weighted graph G, let e = (u, v) be the lightest edge incident to u. True or false: e is in some MST of G.
Show solution

True, by the cut property on the cut ({u}, V∖{u}): the edges crossing it are exactly the edges at u, and e is a lightest one.

Where partial credit is lost
  • Name the cut explicitly: that's the whole justification.
✍ U1B.16Every / some / no MST (ties) New drillcalculation
Source: New drill (Lec 6 board exercise: three cuts, light edges)
Graph: P–Q 1, Q–R 2, P–R 2, R–S 3, Q–S 4, S–T 1, R–T 5. Classify each edge as in every MST, in some but not every MST, or in no MST. Give the MST weight and the number of MSTs. For each of the cuts {P}, {P, Q}, {T}, {P, Q, R}, list the crossing edges and the light edge(s).
Show solution
1223415PQRSTgreen: in every MSTorange: in some MSTdashed: in no MSTMST weight 7,exactly 2 MSTs
A graph with a tie: Q–R and P–R both weigh 2, so each lies in some MST but neither in every MST.
How to read this figure Weights on the edges; the two weight-2 edges Q–R and P–R tie, so each is in one of the two MSTs.

MST weight 7, number of MSTs 2.

  • Every MST: PQ (1), RS (3), ST (1) (each is the unique light edge of some cut, e.g. RS for {P, Q, R}).
  • Some, not every: QR (2), PR (2): the triangle P, Q, R has a tie; either weight-2 edge works.
  • No MST: QS (4), RT (5): each is the unique heaviest edge on a cycle (cycle property).
CutCrossingLight
{P}PQ (1), PR (2)PQ (1)
{P, Q}QR (2), PR (2), QS (4)QR (2), PR (2) (tie)
{T}ST (1), RT (5)ST (1)
{P, Q, R}RS (3), QS (4), RT (5)RS (3)
Where partial credit is lost
  • A tied light edge is certified for some MST only.
  • Cycle property: the unique heaviest edge of a cycle is in no MST.
✍ U1B.17MST true/false New drillshort answer
Source: practice-problems1 §1.6 (a); Lec 7 board p3 (b, e); rest new

True or False? Justify in 1–2 lines (a counterexample suffices for False).

  1. If all edge weights are distinct, the MST is unique.
  2. An MST is a shortest-path tree from any of its vertices.
  3. Adding the same constant to every edge weight leaves the set of MSTs unchanged.
  4. Squaring every weight leaves the set of MSTs unchanged.
  5. Prim's algorithm fails with negative edge weights.
Show solution
  1. True. If T ≠ T' were both MSTs, take the lightest edge e in exactly one of them, say T; T' + e has a cycle with an edge f ∉ T, w(f) > w(e) by choice of e and distinctness; T' + e − f is lighter. Contradiction.
  2. False. Triangle a–b 2, b–c 2, a–c 3: the MST {ab, bc} gives dist(a, c) = 4 in the tree, but the direct edge is 3.
  3. True. Every spanning tree has n − 1 edges, so all trees shift by the same amount.
  4. False with negative weights: x–y −3, y–z 1, x–z 2: MST {xy, yz} (weight -2); squared 9, 1, 4: MST {yz, xz} (weight 5). (With all weights positive, squaring keeps the order and the MST.)
  5. False. The cut-property proof only compares weights; it never needs them to be non-negative (Lec 7 board).
Where partial credit is lost
  • MST vs shortest paths react differently to “add a constant”: MST safe, shortest path not (U1B.8).

28 · Matchings Lec 7 · HW2 #9 · Exam 1A Q4a · Practice Exam U1 Q1.4 · practice problems 1.7, 4.4–4.5

▸ Collapsed: click to expand (2 subsections)▾ Click to collapse

28.1 Augmenting paths and Berge's theorem

Warm-up: try from memory first
Maximal vs maximum matching?
Maximal: no edge can be added (local optimum). Maximum: largest size (global optimum). Maximal ⇒ at least half of maximum.
Define an M-augmenting path.
A simple path whose edges alternate between non-M and M edges and whose two endpoints are unmatched by M.
Berge's theorem?
M is maximum ⇔ there is no M-augmenting path.
The idea in one sentenceIf a matching isn't maximum, there is a chain of reassignments (an alternating path between two free vertices) that frees nothing and gains one edge; if no such chain exists, the matching is optimal.
  • Matching: a set of edges, no two sharing a vertex. Goal: maximum size.
  • Augmenting along P: M △ P = (M ∖ P) ∪ (P ∖ M) is a matching with |M| + 1 edges: internal vertices swap one matched edge for another, the two endpoints become matched.
  • Berge (⇐): if |M*| > |M|, the graph M △ M* has max degree 2, so it splits into alternating paths and cycles. Cycles and even paths contain equally many edges of each matching, so some path has one more M* edge: it is M-augmenting ★ Flagged in lecture · B12.
  • In M △ M' all cycles have even length (Practice Exam U1 Q1.4).
alternating cycle2 from M, 2 from M′a1b1a2b2M-augmenting path1 from M, 2 from M′a3b3a4b4even path1 from M, 1 from M′a5b5a6M (|M| = 4)M′ (|M′| = 5)
M △ M′ for two matchings: every vertex has degree ≤ 2, so the pieces are alternating cycles (even length) and paths; the one extra M′ edge sits on an M-augmenting path.
How to read this figure Solid edges belong to M, dashed edges to M'. Every vertex touches at most one edge of each, so the pieces are alternating cycles (even) and alternating paths. The piece with one more M' edge than M edges is an augmenting path for M.
Summary card
  • Augmenting path: alternating, both ends free; M △ P has |M| + 1 edges.
  • Berge: maximum ⇔ no augmenting path; (⇐) via M △ M* components.
  • No augmenting path shorter than 2k + 1 ⇒ |M| ≥ k/(k+1)·|M*|.
Recall check
Why does every vertex have degree ≤ 2 in M △ M*?
It touches at most one edge of M and at most one of M*.
Can M △ M' contain a 7-cycle?
No: its cycles alternate between the two matchings, so they are even.
✍ U1B.18Augmenting path in the pictured matching (Exam 1A Q4a) Past examshort answer
Source: exams/Exam1_SecA_Soln.pdf p5
Students s1, s2, s3; projects A, B, C (capacity 1). Compatible pairs: s1–A, s1–B, s2–A, s2–B, s2–C, s3–A. Current matching M = {(s1, A), (s2, B)}. Give an M-augmenting path and the larger matching obtained by flipping it.
Show solution
M = {(s1,A), (s2,B)}s1s2s3BACM′ = M △ P, size 3s1s2s3BACflipblue = matched · green = unmatched edges of P: s3–A–s1–B–s2–C · dashed = other edges
Exam 1A Q4a: the augmenting path s3, A, s1, B, s2, C alternates unmatched/matched and has unmatched ends; flipping it gives a matching of size 3.
How to read this figure Bold edges are matched, dashed edges unmatched; the highlighted path alternates and has unmatched ends, so flipping it adds one edge.

Path s3, A, s1, B, s2, C: starts at unmatched s3, ends at unmatched C, edges alternate unmatched (s3A), matched (As1), unmatched (s1B), matched (Bs2), unmatched (s2C).

Flip: remove (s1, A), (s2, B); add (s3, A), (s1, B), (s2, C). New matching (s1, B), (s2, C), (s3, A), size 3.

Where partial credit is lost
  • You scored 6/6 here; keep the habit of checking both endpoints are unmatched.
✍ U1B.19Five augmenting paths (practice problems 4.4) Practice examcalculation
Source: practice-problems1 §4.4 (graph read from Figure 1)
Bipartite graph: u1–v1, u1–v2, u1–v4, u2–v1, u2–v3, u2–v4, u3–v2, u3–v4, u4–v1, u4–v4. Matching M = {(u1, v2), (u2, v3)}. List at least five different M-augmenting paths. What is the maximum matching size?
Show solution

Unmatched: u3, u4 (left), v1, v4 (right). An augmenting path goes from an unmatched u to an unmatched v, alternating.

The 5 paths: u3–v2–u1–v1; u3–v2–u1–v4; u3–v4; u4–v1; u4–v4.

Maximum matching size 4, e.g. (u1, v1), (u2, v3), (u3, v2), (u4, v4).

Where partial credit is lost
  • Length-1 paths count: an edge between two unmatched vertices is an augmenting path.
✍ U1B.20Berge's theorem, both directions (Lec 7) Lectureguided proof ★ Flagged in lecture · B12
Source: Lec 7 board p4; Practice Exam U1 Q1.4
Prove: a matching M is maximum if and only if there is no M-augmenting path. Then answer Practice Exam U1 Q1.4: can M △ M' (two matchings in a bipartite graph) contain a cycle of length 7?
Show solution

(⇒) M maximum ⇒ no augmenting path. Contrapositive: if P is augmenting, M △ P is a matching (internal vertices swap one matched edge for another; the two free endpoints gain one) with |M| + 1 edges, so M is not maximum.

(⇐) No augmenting path ⇒ M maximum. Contrapositive: suppose |M*| > |M|. In M △ M* every vertex has degree ≤ 2 (at most one edge from each matching), so its components are paths and cycles whose edges alternate between M and M*. Alternating cycles and even paths have equally many edges of each. Since M* has more edges in total, some component has more M* edges: a path starting and ending with M* edges. Its endpoints are unmatched in M (an endpoint with an M edge would have that edge in the component, or share it with M*). So it is an M-augmenting path.

Q1.4: No. Cycles in M △ M' alternate between the two matchings, so they have even length; an odd cycle would give some vertex two edges from the same matching.

Rubric: what earns the points
  • (⇒) flipping gives |M|+1
  • (⇐) M △ M* has max degree 2
  • components alternate: paths/cycles
  • counting ⇒ component with more M* edges
  • its endpoints unmatched ⇒ augmenting
  • Q1.4 even cycles
Where partial credit is lost
  • Both directions, labelled; the (⇐) direction is the M △ M* argument.
  • Justify why the extra component's endpoints are free in M.
✍ U1B.21Short augmenting paths give a good matching (practice problems 1.7) Practice examshort answer
Source: practice-problems1 §1.7 (checked against Explained Solutions)
M has no augmenting path with fewer than 11 edges, and M' is a maximum matching. True or false: every path or cycle in M △ M' has (# M edges)/(# M' edges) ≥ 5/6. What does this say about |M|/|M'|?
Show solution

True. Cycles and even paths have ratio 1; paths with an extra M edge have ratio > 1. The only components with more M' edges are M-augmenting paths: k M-edges and k + 1 M'-edges, length 2k + 1 ≥ 11 ⇒ k ≥ 5, ratio k/(k + 1) ≥ 5/6.

Summing over components: |M| ≥ (5/6)|M'|. (Generally: no augmenting path shorter than 2k + 1 ⇒ |M| ≥ k/(k+1)·|M'|.)

Where partial credit is lost
  • Go through every component type, not just augmenting paths.
✍ U1B.25Maximal vs maximum Lectureshort answer ★ Flagged in lecture · B11
Source: Lec 7 board p3 (Maximum vs maximal); (b) new
(a) Define maximal and maximum matchings, and give a graph where a maximal matching is not maximum. (b) Show every maximal matching has at least half the size of a maximum matching.
Show solution

(a) Maximal: no edge can be added (local optimum). Maximum: largest possible size (global optimum). Path a–b–c–d with M = {bc}: maximal (every other edge touches b or c), but {ab, cd} has size 2.

(b) Let M be maximal and M* maximum. Every edge of M* has an endpoint matched by M (else it could be added to M). Each M edge has 2 endpoints, and each endpoint touches at most one M* edge, so |M*| ≤ 2|M|.

Where partial credit is lost
  • The factor-2 argument reappears in Unit 2's vertex-cover approximation.

28.2 Bipartite matching algorithm and Hall's theorem

Warm-up: try from memory first
Hall's condition?
|N(S)| ≥ |S| for every S ⊆ A; it holds iff some matching covers all of A.
Runtime of the augmenting-path bipartite matching algorithm?
O(n(n + m)): at most n/2 augmentations, each found by one BFS/DFS.
The idea in one sentenceIn a bipartite graph, orient unmatched edges A→B and matched edges B→A; then an augmenting path is just a directed path from a free A-vertex to a free B-vertex, which BFS finds.
  1. Start with M = ∅.
  2. Orient edges: unmatched A → B, matched B → A. BFS from all unmatched vertices of A.
  3. If an unmatched vertex of B is reached, follow parent pointers back: that is an augmenting path. Flip it and repeat.
  4. If none is reached, M is maximum (Berge). Each augmentation: O(n + m); at most n/2 of them: O(n(n + m)).

Hall's theorem (practice problems 4.5): if every S ⊆ A has |N(S)| ≥ |S|, every maximum matching covers A. Proof: if x ∈ A is free, the set reachable from x by alternating paths gives S with |N(S)| = |S| − 1. Corollary: a d-regular bipartite graph (d ≥ 1) has a perfect matching.

Using matchings to model other problems (HW2 #9): a perfect matching in a "two copies of V" graph encodes a directed path, with identity edges for vertices not on the path.

Traps
  • A Hall proof needs the alternating-reachable set and the count |S| = |T| + 1, not just "by Hall".
  • For iff problems (HW2 #9) write both directions with headers; each direction constructs the other object.
Recall check
Why does a d-regular bipartite graph satisfy Hall's condition?
The d|S| edges leaving S all end in N(S), which can absorb at most d|N(S)| edges, so |N(S)| ≥ |S|.
In HW2 #9 (⇒), which matching do you start from, and why?
The identity matching on all non-forbidden vertices except vs, vt: exactly vs and v't are free, so Berge gives an augmenting path between them, which is the directed path.
✍ U1B.22Hall's condition and regular bipartite graphs (practice problems 4.5) Practice examguided proof
Source: practice-problems1 §4.5
Bipartite G = ((A, B), E). (1) Prove by contradiction: if |N(S)| ≥ |S| for every S ⊆ A, then every maximum matching matches all of A. (2) Deduce: if every vertex has degree d ≥ 1, G has a perfect matching.
Show solution

(1) Let M be maximum and suppose x ∈ A is unmatched. Let Z = all vertices reachable from x by M-alternating paths (unmatched edge from A to B, matched edge from B to A). Let S = Z ∩ A and T = Z ∩ B.

  1. Every vertex of T is matched (otherwise the alternating path to it would be augmenting, contradicting maximality, Berge).
  2. Each t ∈ T is matched to a vertex of S (we follow its matched edge), and each vertex of S except x is reached through its partner in T. So |S| = |T| + 1.
  3. N(S) ⊆ T: take a ∈ S and a neighbour b. If ab is unmatched, extending the alternating path to a by ab reaches b; if ab is matched, b is a's partner, through which a was reached. Either way b ∈ T.
  4. Hence |N(S)| ≤ |T| = |S| − 1 < |S|, violating Hall's condition. Contradiction.

(2) Count edges: d|A| = |E| = d|B| ⇒ |A| = |B|. For S ⊆ A, the d|S| edges leaving S all land in N(S), and N(S) receives at most d|N(S)| edges, so d|S| ≤ d|N(S)| ⇒ |N(S)| ≥ |S|. By (1) a maximum matching covers A; since |A| = |B| it is perfect.

Rubric: what earns the points
  • unmatched x, alternating-reachable set
  • T all matched (else augmenting)
  • |S| = |T| + 1
  • N(S) ⊆ T ⇒ Hall violated
  • (2) |A| = |B| by counting
  • (2) Hall holds by edge counting
Where partial credit is lost
  • Define the alternating-reachable set precisely; the counting |S| = |T| + 1 is the heart.
  • In (2), show |A| = |B| as well, or “covers A” isn't “perfect”.
✍ U1B.23Find the Hall violator New drillcalculation
Source: New drill
Left vertices 1, 2, 3, 4 with neighbours 1: {w, x}, 2: {w}, 3: {w}, 4: {x, y, z}. Find a maximum matching and every set S that violates Hall's condition.
Show solution

Maximum matching size 3, e.g. (1, x), (2, w), (4, y). Violators (2): S = {2, 3}, N(S) = {w}; S = {1, 2, 3}, N(S) = {w, x}. Either one certifies that no matching covers all four left vertices.

Where partial credit is lost
  • A Hall violator is a short certificate that no left-perfect matching exists: give S and N(S).
✍ U1B.24Forbidden paths via perfect matching (HW2 #9) HWdesign + prove
Source: algo-part2-notes/homeworks/hw2.tex §9 + HW2_Solutions.pdf
Directed G = (V, E), forbidden set F ⊂ V ∖ {vs, vt}. Build bipartite Ĝ: L = copies vi, R = copies v'i; edges {vi, v'i} for all i and {vi, v'j} for each (vi, vj) ∈ E. Delete v's from R, vt from L, and f, f' for every f ∈ F. Show: Ĝ has a perfect matching ⇔ G has a directed vs–vt path avoiding F.
Show solution

(⇐) Path ⇒ perfect matching. Take a path vs → vi1 → ⋯ → vim → vt avoiding F (simple). Match vs–v'i1, vi1–v'i2, …, vim–v't (cross edges = path edges). Every other remaining vertex vℓ is matched to its own copy v'ℓ. Each side has n − |F| − 1 vertices and all are matched exactly once.

(⇒) Perfect matching ⇒ path. Let M₀ = all identity edges vℓ–v'ℓ for ℓ ∉ F ∪ {s, t}: a matching whose only unmatched vertices are vs (left) and v't (right). If a perfect matching exists, M₀ is not maximum, so by Berge there is an M₀-augmenting path from vs to v't. It alternates cross edges (vi, v'j), which are edges of G, and identity edges (v'j, vj), which step from j's right copy to its left copy. Reading the cross edges in order gives vs → ⋯ → vt in G, avoiding F because F's copies were deleted.

Rubric: what earns the points
  • (⇐) cross edges along the path
  • (⇐) identity edges elsewhere ⇒ perfect
  • (⇒) identity matching M₀ with two free vertices
  • (⇒) Berge ⇒ augmenting path
  • (⇒) cross edges = directed path avoiding F
Where partial credit is lost
  • Two labelled directions; each builds the other object explicitly.
  • In (⇒), the trick is the starting matching M₀ with exactly two free vertices, then Berge.

29 · Max flow, min cut, flow modeling Lec 8 · Exam 1A Q1e, Q1h, Q4b–c · Practice Exam U1 Q2 · practice problems 4.3, 4.6

▸ Collapsed: click to expand (3 subsections)▾ Click to collapse

29.1 Flows, residual graphs, Ford–Fulkerson

Warm-up: try from memory first
The two constraints on a flow?
Capacity: 0 ≤ fe ≤ ce. Conservation: flow in = flow out at every vertex except s and t.
Residual capacities of an edge with flow 4 and capacity 9?
Forward 5, backward 4.
Ford–Fulkerson runtime with integer capacities?
O((n + m)(1 + |f*|)): pseudo-polynomial.
The idea in one sentenceKeep pushing flow along any s–t path that still has room, where "room" includes the option of cancelling flow you pushed earlier; when no such path exists, the flow is maximum.
  • Network: directed G, capacities ce ≥ 0, source s, sink t. Value |f| = flow out of s (minus flow into s).
  • Residual graph Gf: for each edge (u, v): forward edge u→v with capacity cuv − fuv and reverse edge v→u with capacity fuv (keep only positive ones) ★ Flagged in lecture · B03.
  • Augmenting path: an s–t path in Gf; bottleneck Δ = its smallest residual capacity. Augmenting adds Δ on forward edges and subtracts Δ on edges traversed backward. Capacity and conservation are preserved.
  • Ford–Fulkerson: start at f = 0; while Gf has an s–t path, augment by Δ (or even by 1 ★ Flagged in lecture · B07). Integer capacities ⇒ every value stays integral and |f| grows by ≥ 1 per round.
  • Runtime: O((n + m)(1 + |f*|)): pseudo-polynomial ★ Flagged in lecture · B04, and bad path choices really do take |f*| rounds (the 100-capacity example). Edmonds–Karp (BFS = fewest edges) needs O(nm) augmentations: O(nm²) total ★ Flagged in lecture · B05.
flow after path 1 (s→a→b→t, Δ = 2)residual graph G_f2/30/12/20/22/2sabt121222sabtorange = backward residual edges (capacity f_e) · green = augmenting path s→b→a→t, bottleneck 1
Left: the flow after the first augmentation. Right: its residual graph. The only s–t path uses the backward edge b→a, so the next augmentation lowers f(a,b) from 2 to 1.
How to read this figure Left: a flow after one augmentation, labelled flow/capacity. Right: its residual graph; solid edges are remaining forward capacity, dashed edges are backward (cancellable) capacity. The only s–t path uses the backward edge b→a, so the next augmentation moves flow off a→b.
Traps
  • Reverse residual capacity = current flow, not capacity.
  • When drawing Gf for an edge with 0 < f < c, draw both directions ★ Flagged in lecture · B02.
Recall check
What happens to an original edge when an augmenting path uses its reverse residual edge?
Its flow decreases by Δ (the path cancels flow).
Why is Ford–Fulkerson only pseudo-polynomial?
Its round count can be |f*|, which is a capacity value, exponential in the number of bits.
✍ U1B.27Residual capacities of one edge (Exam 1A Q1h) Past examshort answer
Source: exams/Exam1_SecA_Soln.pdf p2
An edge (u, v) has capacity 9 and carries flow 4. Give its forward and reverse residual capacities and what each means.
Show solution

Forward u→v: 9 − 4 = 5 (can push 5 more). Reverse v→u: 4 (can cancel up to 4 units of current flow).

Where partial credit is lost
  • Reverse residual = current flow, not capacity.
✍ U1B.28Residual graph, augment, max flow, min cut (Practice Exam U1 Q2) Practice examcalculation
Source: practice-exams/Practice_Exam_Unit_1_Solutions.pdf Q2
Flow f (flow/capacity): s→A 2/8, s→B 2/3, s→C 2/9, A→D 2/2, B→D 2/4, D→C 0/1, C→E 2/7, D→t 4/7, E→t 2/5. (1) Draw the residual graph (residual capacity for each ordered pair). (2) Find an augmenting path that sends at least 3 units, and the new flow. (3) Max flow value? (4) Edges of a minimum cut.
Show solution

(1) Forward: s→A 6, s→B 1, s→C 7, A→D 0, B→D 2, D→C 1, C→E 5, D→t 3, E→t 3. Backward: A→s 2, B→s 2, C→s 2, D→A 2, D→B 2, E→C 2, t→D 4, t→E 2. (|f| = 6.)

(2) s→C→E→t has bottleneck min(7, 5, 3) = 3. Send 3: s→C 5/9, C→E 5/7, E→t 5/5; |f| = 9.

(3) One more path s–B–D–t (Δ = 1) gives 10; then no s–t path remains in the residual graph.

(4) Vertices reachable from s in the final residual graph: X = {s, A, C, E}. Cut edges (s, B), (A, D), (E, t), capacity 3 + 2 + 5 = 10 = |f|, which certifies optimality.

Rubric: what earns the points
  • (1) all forward/backward residuals
  • (2) valid path with Δ ≥ 3 and new flow
  • (3) value 10
  • (4) cut (s,B), (A,D), (E,t)
Where partial credit is lost
  • Draw both residual directions for every edge with 0 < f < c; omit zero-capacity residual edges.
  • Find the min cut by BFS from s in the final residual graph.
✍ U1B.29Ford–Fulkerson where a backward edge saves the day New drillcalculation ★ Flagged in lecture · B02
Source: New drill (Lec 8 running-example idea with new capacities)
Capacities s→a 3, s→b 1, a→b 2, a→t 2, b→t 2. Start with the path s→a→b→t. Continue Ford–Fulkerson; show each residual graph's augmenting path and Δ, the final flow, and all minimum cuts.
Show solution
  1. s→a→b→t, Δ = 2: |f| = 2. Residual: s→a 1, a→s 2, s→b 1, b→a 2, a→t 2, t→b 2.
  2. s→b→a→t uses the backward edge b→a, Δ = 1: the flow on a→b drops to 1; |f| = 3.
  3. s→a→t, Δ = 1: |f| = 4.

Final flow: sa 3/3, sb 1/1, ab 1/2, at 2/2, bt 2/2; value 4. Reachable from s in the final residual graph: {s}. Minimum cuts: {s} and {s, a, b} (both capacity 4).

Where partial credit is lost
  • An augmenting path may use a backward edge: that reduces flow on the original edge.
  • Min cuts need not be unique; the BFS-reachable set gives one of them.
✍ U1B.30Edmonds–Karp full run New drillcalculation
Source: New drill (code-verified)
Capacities s→a 10, s→c 10, a→b 4, a→c 2, a→d 8, c→d 9, d→b 6, b→t 10, d→t 10. Run Edmonds–Karp (shortest augmenting path by BFS). Give each path, its Δ, the final flow, and the min cut.
Show solution

Trace: sabt (Δ = 4, |f| = 4); sadt (Δ = 6, |f| = 10); scdt (Δ = 4, |f| = 14); scdbt (Δ = 5, |f| = 19) (4 augmentations).

Final flow: sa 10/10, sc 9/10, ab 4/4, ac 0/2, ad 6/8, cd 9/9, db 5/6, bt 9/10, dt 10/10; value 19. Reachable from s in the final residual graph: {s, c}; cut edges (s, a), (c, d), capacity 10 + 9 = 19 ✓.

Where partial credit is lost
  • BFS finds the path with the fewest edges; ties broken alphabetically here.

29.2 Minimum cuts and max-flow min-cut

The idea in one sentenceEvery s–t cut is a bottleneck that no flow can exceed; when Ford–Fulkerson gets stuck, the vertices it can still reach form a cut whose capacity equals the flow, so both are optimal.
  • s–t cut (X, V∖X) with s ∈ X, t ∉ X. Capacity c(X, V∖X) = sum of capacities of edges leaving X (directed! entering edges don't count) ★ Flagged in lecture · B01.
  • Weak duality: |f| = (flow out of X) − (flow into X) ≤ c(X, V∖X) for every flow and cut.
  • MFMC: at termination, X = vertices reachable from s in Gf; every edge leaving X is saturated and every edge entering X carries 0, so |f| = c(X, V∖X) ★ Flagged in lecture · B15.
  • Finding a min cut: BFS from s in the final residual graph. Min cuts need not be unique.
  • Certificate for "this flow is maximum": a cut with the same capacity.
  • Integrality: integer capacities ⇒ some max flow is integral (FF finds one) ★ Flagged in lecture · B08.
X = {s}3/31/11/22/22/2sabtfinal flow |f| = 4red cut: X = {s}, edges s→a, s→bcapacity 3 + 1 = 4 = |f| ✓grey cut: X = {s, a, b}edges a→t, b→t: 2 + 2 = 4two minimum cuts
The final flow (value 4) and its min cut. BFS from s in the final residual graph reaches only s, so X = {s}; a second min cut {s, a, b} also exists.
How to read this figure The final flow, labelled flow/capacity. In its residual graph only s is reachable, so X = {s}: both edges leaving s are full, and the cut capacity 3 + 1 = 4 equals the flow value. The cut {s, a, b} also has capacity 4.
Summary card
  • c(X, V∖X) = Σ leaving capacities; |f| ≤ every cut; equality at FF's end with X = reachable set.
  • At the min cut: leaving edges saturated, entering edges empty.
Recall check
How do you extract a minimum cut from a maximum flow?
BFS/DFS from s in the residual graph Gf; X = reachable vertices; the cut edges are the original edges from X to V∖X.
Does increasing the capacity of a min-cut edge always increase the max flow?
No, if another min cut avoids that edge.
✍ U1B.26A cut certifies a flow bound (Exam 1A Q1e) Past examshort answer ★ Flagged in lecture · B01
Source: exams/Exam1_SecA_Soln.pdf p2
Capacities s→a 7, s→b 3, a→b 2, a→t 1, b→t 6. Show the maximum s–t flow is at most 6 by identifying a suitable cut.
Show solution

Take S = {s, a}, V∖S = {b, t}. Edges leaving S: (s, b) 3, (a, b) 2, (a, t) 1: capacity 3 + 2 + 1 = 6. Every flow is at most the capacity of every cut, so max flow ≤ 6 (it equals 6).

Where partial credit is lost
  • Count only edges from S to V∖S; edges entering S don't count toward the capacity.
✍ U1B.33Max-flow min-cut: the proof and the certificate (Lec 8) Lectureguided proof ★ Flagged in lecture · B15
Source: Lec 8 board p4–5
(a) Show |f| ≤ c(X, V∖X) for every flow f and s–t cut. (b) When Ford–Fulkerson stops, let X = vertices reachable from s in Gf. Show |f| = c(X, V∖X). (c) What do you hand someone as a short proof that a flow is maximum?
Show solution

(a) Sum conservation over X ∖ {s}: |f| = (flow out of X) − (flow into X) ≤ Σedges leaving X ce − 0 = c(X, V∖X).

(b) s ∈ X and t ∉ X (no augmenting path). For an edge (u, v) leaving X: if fuv < cuv, the forward residual edge would make v reachable, so fuv = cuv. For an edge (v, u) entering X: if fvu > 0, the backward residual edge u→v would make v reachable, so fvu = 0. Then (a)'s inequality is tight: |f| = c(X, V∖X).

(c) The flow plus a cut with the same value; by (a) no flow can exceed that cut, so both are optimal.

Rubric: what earns the points
  • (a) conservation sum ⇒ ≤ cut
  • (b) leaving edges saturated
  • (b) entering edges zero
  • (b) equality
  • (c) flow + equal cut
Where partial credit is lost
  • Name both facts at the cut: leaving edges saturated, entering edges empty.
✍ U1B.31Why plain Ford–Fulkerson is pseudo-polynomial, and why Edmonds–Karp isn't (Lec 8, practice problems 4.3) Lectureguided proof ★ Flagged in lecture · B04 B05 B06
Source: Lec 8 board p2–4 (FF bound, EK remark, the 100-capacity example); practice-problems1 §4.3
(a) Give a network where Ford–Fulkerson with bad path choices needs a number of augmentations proportional to the capacities. (b) Using the fact that each residual edge (u, v) becomes saturated at most |V|/2 times under Edmonds–Karp, show Edmonds–Karp runs in polynomial time.
Show solution

(a) s→a, s→b, a→t, b→t of capacity C = 100, and a→b of capacity 1. Alternating the paths s→a→b→t and s→b→a→t (using the backward edge) sends 1 unit each time: 200 augmentations for a max flow of 200. Shortest paths (Edmonds–Karp) need only 2. Generally FF takes O((n + m)(1 + |f*|)): pseudo-polynomial, since |f*| can be exponential in the bits of the capacities.

(b) Every augmentation saturates at least one residual edge (the bottleneck). There are at most 2|E| residual edges, each saturated ≤ |V|/2 times, so there are ≤ 2|E| · |V|/2 = |V||E| augmentations; each BFS costs O(|E|). Total O(|V||E|²), independent of capacities.

Rubric: what earns the points
  • (a) bad example + count
  • (a) pseudo-polynomial explanation
  • (b) bottleneck edge saturated each time
  • (b) 2|E| · |V|/2 bound
  • (b) × O(|E|) per BFS = O(|V||E|²)
Where partial credit is lost
  • Count residual edges as 2|E| (both directions).
  • Pseudo-polynomial: depends on capacity values, not their bit lengths.

29.3 Flow modeling: the full-credit frame (Exam 1A Q4)

Warm-up: try from memory first
Bipartite matching as a flow: the network?
s → each left vertex (cap 1), each edge left → right (cap 1), each right vertex → t (cap 1). An integral max flow = a maximum matching.
What are the two directions of a flow-reduction proof?
(i) a solution of value q gives a feasible flow of value q; (ii) an integral flow of value q gives a solution of value q.
The idea in one sentenceTurn each "resource" into vertices, each "may be used at most k times" into a capacity, and each choice into an edge; then show both directions of the correspondence preserve the value.

Answer frame (Exam 1A Q4: 14 points lost; rubric quotes in the problem below).

  1. Vertices, named in the problem's words: "one vertex ai per student, one vertex pj per project, plus s and t" ★ Past exam / HW · B17.
  2. Edges with capacities, each with a one-phrase reason: s→ai cap 1 (a student is assigned at most once), ai→pj cap 1 for compatible pairs, pj→t cap bj (project limit).
  3. Reading the answer: "compute an integral max flow; assign i to j iff f(ai, pj) = 1" ★ Flagged in lecture · B09.
  4. (i) Solution ⇒ flow: route one unit per assigned pair; check capacities and conservation; value q.
  5. (ii) Integral flow ⇒ solution: integrality ⇒ each student carries 0 or 1 unit, to one compatible project; project j receives ≤ bj; value q ★ Past exam / HW · B18.
  6. Runtime: FF with |f*| ≤ n: O(n(n + m)).

Modeling toolbox:

ConstraintGadget
Item used at most k timesedge from s (or to t) with capacity k
Vertex capacity ksplit v into vin → vout with capacity k
Edge-disjoint pathsall capacities 1; max flow = number of paths (Menger)
"i requires j" (closure)∞ edge i → j; min cut (project selection)
Multiple sources/sinkssuper-source / super-sink
studentsprojects1111b=2b=1b=0sa1a2a3a4p1p2p3tmiddle edges (grey) have capacity 1 and exist only for compatible pairs
Flow model for Exam 1A Q4: s → each student (capacity 1), student → compatible project (capacity 1), project j → t (capacity b_j).
How to read this figure The Exam 1A Q4 network, left to right: source, one vertex per student, one per project, sink. Each student edge from s has capacity 1, each compatible pair capacity 1, and project j's edge to t has capacity bj. One unit of integral flow along s → ai → pj → t means "student i does project j".
Traps (from your graded Exam 1)
  • "No mention of student or project here?": vertices must be named in the problem's terms.
  • Capacities unspecified: −3. Only one direction of (i)/(ii): −3.
  • In (ii), say "integral" explicitly; a fractional flow doesn't give an assignment.
Summary card
  • Frame: vertices (named) · edges + capacities + reasons · read-off rule · (i) solution ⇒ flow, same value · (ii) integral flow ⇒ solution, same value · runtime.
  • Gadgets: capacities for "at most k", vertex splitting, unit capacities for disjoint paths, ∞ edges for requirements.
Recall check
Which capacity enforces "project j takes at most bj students"?
The edge pj → t with capacity bj.
Where is integrality used in the correctness proof?
In direction (ii): each student's inflow is 0 or 1, so the flow picks at most one project per student.
How do you enforce a capacity on a vertex?
Split it into vin → vout with that capacity; incoming edges go to vin, outgoing leave vout.
✍ U1B.32Students to projects with capacities (Exam 1A Q4b–c): full redo Past examdesign + prove ★ Flagged in lecture · B09 ★ Past exam / HW · B17 B18
Source: exams/Exam1_SecA_Soln.pdf p5; rubric from your graded Exam 1
n students, k projects; project j accepts at most bj students (bj ≥ 0). A list of m compatible pairs is given; each student gets at most one compatible project. Maximize the number of assigned students. (b) Construct a flow network whose max-flow value equals the maximum number of assigned students: vertices, edges, capacities, source, sink, and how to read an assignment from an integral max flow. (c) Prove it correct: (i) a valid assignment of q students gives a feasible flow of value q; (ii) an integral flow of value q gives a valid assignment of q students. (You may use integrality.)
Show solution

(b) Network.

  • Vertices: source s, sink t, one vertex ai per student, one vertex pj per project.
  • Edges: s → ai capacity 1 (each student assigned at most once); ai → pj capacity 1 for each compatible pair; pj → t capacity bj (project limit).
  • Find an integral max flow (FF with integer capacities). Assign student i to project j iff f(ai, pj) = 1.

(c)(i) Assignment ⇒ flow. For each assigned pair (i, j), send one unit along s → ai → pj → t. Capacities hold: each student is used once (s→ai ≤ 1), each compatible edge carries ≤ 1, and project j receives at most bj units (pj→t ≤ bj). Conservation holds at every ai and pj (in = out). Value = q.

(c)(ii) Integral flow ⇒ assignment. Let f be integral with value q. Each ai receives 0 or 1 unit (capacity 1, integral). By conservation a student receiving 1 sends it along exactly one edge ai→pj, which exists only for compatible pairs. Project j's outflow is ≤ bj, so by conservation at most bj students send flow to it. So the flow-1 middle edges form a valid assignment; the number of assigned students equals the flow out of s, which is q.

Conclusion: both maps preserve value, so max flow = max assignment (an integral max flow exists since capacities are integers).

Example: a1: {p1, p2}, a2: {p1}, a3: {p1}, a4: {p2, p3}, b = (2, 1, 0): max = 3, e.g. a1→p1, a2→p1, a4→p2.

Rubric: what earns the points
  • (b) student and project vertices + s, t
  • (b) capacities 1, 1, b_j
  • (b) read assignment from f = 1 edges
  • (c)(i) one unit per pair; capacities; conservation; value q
  • (c)(ii) integral ⇒ 0/1 per student; one project each
  • (c)(ii) ≤ b_j per project; value q
  • conclusion: optima equal
Where partial credit is lost
  • This cost you 14 points (b: “no mention of student or project here?”; c: not done).
  • Name vertices in the problem's words (students, projects), give every capacity (bj on project→t), say how to read the answer (rubric: “capacities unspecified” −3).
  • (c) needs both directions, each with capacity and conservation checks and “same value” (rubric: one direction only −3).
  • Mention integrality in (ii).
✍ U1B.35Project selection as a min cut New drilldesign + prove
Source: New drill (classic flow model)
Projects A (profit 10), B (4), C (−7), D (−5). Choosing A requires C and D; choosing B requires D. Choose a set closed under requirements with maximum total profit, via a min cut. Give the network, the min cut, and the answer.
Show solution
10475∞∞∞sABCDtprofit p > 0: edge s → i of capacity p · cost (p < 0): edge i → t of capacity −ppurple ∞: “i requires j” edges · min cut 12 = 14 − best profit 2
Project selection as a min cut: the source side of a finite cut is a valid project set, and its capacity is (sum of positive profits) − (profit of that set).
How to read this figure Profitable projects hang from s, costly ones feed t, and ∞ edges encode requirements. Any finite cut's source side is a valid project set.

Network: s → i with capacity pi for profitable projects; i → t with capacity −pi for costly ones; i → j with capacity ∞ for each requirement "i needs j".

Why it works: the source side S of a finite cut is closed (an ∞ edge i→j with i ∈ S, j ∉ S would make the cut infinite). Its capacity = (profits of profitable projects not chosen) + (costs of costly projects chosen) = (sum of positive profits) − profit(S). So min cut ⇔ max profit.

Sum of positive profits 14; min cut 12; best profit 14 − 12 = 2 with {A, B, C, D}. (∞ can be any capacity > 27 − 1, e.g. 27.)

Rubric: what earns the points
  • network with s/t edges and ∞ requirement edges
  • finite cut ⇒ closed set
  • cut = Σpositive − profit(S)
  • answer 2
Where partial credit is lost
  • Write the capacity of a cut in terms of the chosen set: that identity is the proof.
✍ U1B.34Updating a max flow after adding or deleting an edge (practice problems 4.6) Practice examdesign + prove
Source: practice-problems1 §4.6
All capacities are 1, f is an integral max flow. (1) A new edge e (capacity 1) is added. (2) An edge e ∈ E is deleted. In each case get a new max flow in O(|V| + |E|).
Show solution

(1) Add e. The old f is still feasible, and the max flow grows by at most 1 (the new edge adds capacity 1 to every cut it crosses). Build Gf (with e's forward residual edge) and run one BFS for an s–t path; augment by 1 if found. O(|V| + |E|).

(2) Delete e = (u, v). If fe = 0, f is still a max flow (deleting an edge never increases the max). If fe = 1: the unit through e must be removed. Find a flow-carrying path s ⇝ u and v ⇝ t through edges with flow 1 (follow flow edges; O(|V| + |E|)) and cancel one unit along s ⇝ u → v ⇝ t (cycles of flow, if any, can be cancelled too). Now |f| decreased by 1 and f is feasible without e. The new max is either this or one more, so one BFS for an augmenting path in the new residual graph finishes it. O(|V| + |E|).

Rubric: what earns the points
  • (1) max changes by ≤ 1
  • (1) one BFS + augment
  • (2) case f_e = 0
  • (2) cancel a unit through e
  • (2) one augmentation
  • linear time
Where partial credit is lost
  • Argue the max flow changes by at most 1 in each case; that's why one augmentation suffices.
✍ U1B.36Flow modeling and facts (select all) New drillshort answer ★ Flagged in lecture · B08
Source: New drill
Select ALL true statements; justify each in one line.
  1. The maximum number of edge-disjoint s–t paths equals the max flow with all capacities 1.
  2. To limit how much flow passes through a vertex v, split v into vin → vout with that capacity.
  3. If all capacities are integers, every maximum flow is integral.
  4. Increasing the capacity of an edge in a minimum cut always increases the max-flow value.
  5. If all capacities are integers, Ford–Fulkerson returns an integral max flow.
Show solution
  • A true (Menger): an integral unit-capacity flow decomposes into edge-disjoint paths, and vice versa. Example: s→a, s→b, s→c, a→d, b→d, c→e, d→t, e→t, b→e has 2.
  • B true: every unit through v must cross the edge vin→vout.
  • C false: some max flow is integral, not every one. s→a 1, a→b 1, a→c 1, b→t 1, c→t 1: sending ½ along s→a→b→t and ½ along s→a→c→t is a maximum flow (value 1) and is fractional.
  • D false: there may be another min cut not containing that edge (U1B.29 has two min cuts).
  • E true: every residual capacity stays an integer, so every Δ is an integer.

Answer: A, B, E.

Where partial credit is lost
  • Integrality theorem: an integral max flow exists (and FF finds one); not every max flow is integral.