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
- Open the Redo queue and redo yesterday's Missed/Shaky items first (15 min).
- Follow today's row in the plan. Per topic: warm-up → refresher → summary card → recall check → problems (short → calc → guided → design).
- Write answers on paper (front of the page only, no calculator), then open the solution. Check every rubric item, not just the final answer.
- 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.
- §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.
| Part | Problems | Status |
|---|---|---|
| My weak spots | 17 | ✓ |
| Exam craft & short-answer track | 52 | ✓ |
| Unit 1a · Lec 1–5 | 50 | ✓ |
| Unit 1b · Lec 6–8 | 36 | ✓ |
| Unit 2a · LP & duality | 0 | building… |
| Unit 2b · Convexity, GD, approximation | 0 | building… |
| Unit 3 · Randomized, NP, Lec 20–21 | 0 | building… |
| Cross-unit drills & mocks | 0 | building… |
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.
2 · The final's format (evidence so far)
▸ Collapsed: click to expand▾ Click to collapse
| Evidence | What it says | Source |
|---|---|---|
| Exam 1, 2, 3 covers | 70 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 layout | Q1 = 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 set | 8 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).
| Day | Blocks (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
|
| Sat Dec 5 320 min ≈ 5.3 h | Unit 1 rest → then Exam 1 lost parts cold as a check
|
| Sun Dec 6 330 min ≈ 5.5 h | Unit 2 + untested-Unit-2 gaps; evening Exam 1B
|
| Mon Dec 7 225 min ≈ 3.8 h | Unit 3 + Lec 20–21 + technique choosing
|
| Tue Dec 8 220 min ≈ 3.7 h | Official final practice set, timed and AI-free
|
| Wed Dec 9 225 min ≈ 3.8 h | Mock A + redo queue + cheat sheet; sleep
|
| Thu Dec 10 (morning) 75 min ≈ 1.2 h | Light warm-up only; exam 2:00 PM
|
- 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).
- 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
| Technique | Evidence | How 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) practice | Also “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 types | Mixing 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 → problem | Worked 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 practice | Practicing 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. |
| Sleep | Sleep 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 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 length | Points | min / point | 5-pt short | 40-pt short block | 20-pt long | 30-pt long |
|---|---|---|---|---|---|---|
| 120 min | 100 | 1.1 | 5.5 | 44 | 22 | 33 |
| 150 min | 100 | 1.4 | 7 | 56 | 28 | 42 |
| 150 min | 150 | 0.93 | 4.7 | 37 | 19 | 28 |
| 170 min | 100 | 1.6 | 8 | 64 | 32 | 48 |
| 180 min | 150 | 1.13 | 5.7 | 45 | 23 | 34 |
All times in minutes; 10 min reserved in every row.
5.1 The two-pass method
- 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".
- 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.
- 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).
- 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)".
- 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.
- Check (7 min) with the list in §10: both bounds, both directions, k vs k+1, every constraint, final answers bold.
- 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.
A 150-minute, 100-point final: how long for a 20-point long problem?
What do you write in pass 1 of a "prove the reduction is correct" part?
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
6.1 The frames
| Question type | Frame: the headers to write first | Where you lost points |
|---|---|---|
| DP | 1 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, space | E1 Q3: 15 pts (empty recurrence, base cases, answer cell, order) |
| Divide & conquer | Algorithm (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 model | Vertices (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 value | E1 Q4b–c: 14 pts |
| LP / ILP formulation | Variables with meaning · Objective · Every constraint family ("for every element e: …") · Integrality / bounds · Why a feasible solution ↔ a valid choice | E2 Q4.1: 4 pts (only the objective) |
| Dual | Primal 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 algorithm | Algorithm · 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 |
| Randomized | Random variable defined · Indicators + linearity → E[·] as a number · Markov / boosting with independence stated · Derandomization: how each conditional expectation is computed | E1 Q1d, E3 Q1f, Q2c: 11.5 pts |
| NP-hardness reduction | Direction: 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 |
| Existence | Extremal choice (max, min, longest, first/last) · Check every neighbour/boundary case · Conclude | E1 Q2a: 6 pts |
| T/F | Verdict · True: the one-line reason (theorem name + why it applies) · False: the smallest counterexample with numbers before/after | E1 Q1f, E2 Q1b: 10 pts |
| Strongest bounds | Lower = … because … · Upper = … because … · Compare with any extra fact and keep the stronger · Integrality rounding | E1 Q1c, E2 Q1f: 9 pts |
- 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 box | Input → output | Runtime / guarantee |
|---|---|---|
| Merge sort | array → sorted | O(n log n) |
| Median of medians (select) | array, k → k-th smallest | O(n) worst case |
| Karatsuba / Strassen | n-bit numbers / n×n matrices → product | O(nlog₂3) / O(nlog₂7) |
| BFS / DFS | graph, s → distances in edges / reachability, components, topological order (DAG) | O(n + m) |
| Dijkstra | graph, w ≥ 0, s → shortest distances + tree | O((n + m) log n) |
| Kruskal / Prim | connected weighted undirected graph → MST | O(m log n) |
| Bipartite matching (augmenting paths) | bipartite graph → maximum matching | O(n(n + m)) |
| Ford–Fulkerson / Edmonds–Karp | network, integer capacities → integral max flow + min cut | O(m·|f*|) / O(nm²) |
| 0/1 knapsack DP | n items, capacity B → optimum | O(nB) (pseudo-polynomial); value-indexed O(n·Σv) |
| Knapsack FPTAS | items, ε → ≥ (1 − ε)OPT | O(n³/ε) |
| LP solver | LP → optimal vertex, or infeasible / unbounded | polynomial time |
| (Projected) gradient descent | convex f (, convex K) → ε-approximate minimizer | rates in Unit 2 (DG/√T, βD²/2T, (1 − α/β)T) |
| VC via maximal matching | graph → vertex cover | 2-approx, O(n + m) |
| VC LP rounding (x ≥ ½) | weighted graph → vertex cover | 2-approx |
| Set cover rounding (x ≥ 1/f) | elements in ≤ f sets → cover | f-approx |
| Karger contraction | multigraph → a min cut | ≥ 2/(n(n−1)) per run; boost by repetition |
| Random assignment for MAX-SAT | formula → assignment | E ≥ (1 − 2−k)m for clauses of size ≥ k |
| 2-SAT | 2-CNF → satisfying assignment or "no" | O(n + m) (implication graph + SCC) |
| Known NP-complete | SAT, 3SAT, Independent Set, Clique, Vertex Cover, Set Cover, Subset Sum / Knapsack (decision), 2 directed disjoint paths | reduce from these |
- 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.
The six lines of the DP frame?
The seven headers of a flow model?
In an NP-hardness proof, which way does the reduction go?
7 · Hand-arithmetic drills exam craft · no calculator on the final · EC.1–12
▸ Collapsed: click to expand▾ Click to collapse
ln 2, ln 10, ln 100, e−1, e−2 to two digits?
The inequality that turns (1 − p)k into something you can solve for k?
- 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.
- Compute ∇f(x₀), x₁, x₂, x₃.
- Give the smoothness β and strong-convexity α of f.
- Check the descent lemma at η = 1/β: is f(x₁) ≤ f(x₀) − ‖∇f(x₀)‖²/(2β)?
Show solution
- ∇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).
- The Hessian is diag(2, 4) at every point. β = largest eigenvalue = 4, α = smallest = 2. So η = 1/4 is exactly the safe step 1/β.
- 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).
- gradient formula
- each iterate computed with x − η∇f
- β and α from the Hessian eigenvalues
- descent-lemma inequality checked numerically
- 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).
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).
- gradient at x₀
- unprojected point
- notice infeasibility
- Euclidean projection with the normal direction
- check every constraint at the final point
- 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).
- f convex, ‖∇f‖ ≤ G = 5, ‖x₀ − x*‖ ≤ D = 4, ε = 1/2, η = D/(G√T), average iterate.
- f convex and β-smooth with β = 6, D = 2, ε = 1/10, η = 1/β, last iterate.
- f α-strongly convex and β-smooth with α = 2, β = 8, f(x₀) − f* = 50, ε = 1/20, η = 1/β.
Show solution
- DG/√T ≤ ε ⇔ T ≥ (DG/ε)² = (20/(1/2))² = 1600.
- βD²/(2T) ≤ ε ⇔ T ≥ βD²/(2ε) = 6·4/(2/10) = 120.
- (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.
- name the theorem and check its hypotheses
- set bound ≤ ε and solve for T
- round up
- say which iterate the bound is for
- 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.
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).
- η formula
- error formula
- average (or best) iterate stated
- Claiming the bound for the last iterate (a T/F favourite).
- √400 = 20, not 200.
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.
- Markov stated with X ≥ 0
- complement for the lower side
- useless case recognised
- LV→MC: failure event = time exceeds the cap
- Applying Markov to a variable that can be negative.
- Writing Pr[X ≥ 4] ≤ 5/4 as if it were informative.
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.
- V(·, 1) at every reachable state
- Q for each first action as Σ prob × value
- full policy (first action and second-step choices)
- optimal value
- 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).
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.
- identify p
- Geometric ⇒ E = 1/p
- tail as (1 − p)^k
- 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.
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.
- K = εV_max/n
- scaled values
- bound on Σv̂ and DP size
- loss < nK = εV_max ≤ εOPT
- Missing the one fact the proof needs: V_max ≤ OPT (every item fits alone).
- Using K = εV_max (forgetting the 1/n).
Show solution
All k runs fail with probability (1 − p)^k. Need (1 − p)^k ≤ δ ⇔ k ≥ ln(1/δ)/ln(1/(1 − p)).
- (1/2)^k ≤ 1/1000 ⇔ k ≥ log₂ 1000 ≈ 9.97 ⇒ k = 10.
- k ≥ 4.61/0.405 ≈ 11.36 ⇒ k = 12.
- (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).
- independent runs, output the best
- failure = all runs fail = (1 − p)^k
- solve for k and round up
- 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).
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}.
- one-run bound 2/(n(n−1))
- independent repetitions
- (1 − p)^N ≤ e^{−pN}
- Using 1/n² instead of 2/(n(n − 1)) is fine as a bound but say which one you use.
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.
- indicator per clause + linearity
- per-clause conditional probability rule
- E_T and E_F values
- average identity and the choice
- Exam 3 Q2c (−3): you must say how each conditional expectation is computed (the per-clause rule + linearity), not only that it can be.
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.
- feasibility ⇒ one side
- guarantee ⇒ other side
- compare with the extra fact (LP) and keep the stronger
- 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
| Template | Skeleton | Trigger | Drill |
|---|---|---|---|
| Induction | Claim P(n) stated · base case(s) checked · "assume P(k) for [all] k < n" · step that uses the hypothesis on a smaller instance · conclude | recurrences, DP correctness, algorithm invariants | U1A.4, §20 |
| Contradiction / first failure | Suppose the claim fails · take the first (or smallest) failure · derive that something earlier also failed or a bound is broken | greedy correctness, Dijkstra | U1B.10 |
| Extremal | Pick the max / min / longest / last object · check it has the property, case by case on boundaries | "prove there exists" | WS.8–WS.11 |
| Exchange | Take an optimal solution that differs from greedy · swap one element toward greedy's choice · show it is no worse · repeat | MST, 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 inequalities | Target written · numbered steps, each citing a fact (hint, earlier part, definition) · last step = target | GD rates, approximation ratios, Markov | WS.15–WS.17 |
- 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.
Which template proves "a DAG has a source"?
What must each direction of a correspondence proof preserve?
9 · Technique chooser exam craft · from the problem's wording to the tool and its frame
▸ Collapsed: click to expand▾ Click to collapse
| Words in the question | Tool | Notes 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 / Farkas | Unit 2 (§30–34) |
| "step size", "smooth", "convex", "gradient" | GD theorems | Unit 2 (§35–39) |
| "within a factor", "approximation", "relax" | Bound OPT; ILP → LP → round | Unit 2 (§35–39) |
| "expected", "with probability", "random" | Indicators, Markov, boosting, conditional expectations | Unit 3 (§40–49) |
| "NP-hard", "no polynomial algorithm unless P = NP" | Reduction from a known NP-complete problem | Unit 3 (§40–49) |
"Each nurse works at most 3 shifts, each shift needs 2 nurses": which tool?
"Prove the problem has no polynomial-time algorithm unless P = NP": which way does the reduction go?
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)
| Tag | Check |
|---|---|
| BOUNDS | Every "bounds on OPT" answer has a lower and an upper side, each with its reason. |
| IFF | Every "if and only if" / reduction / flow proof has both (⇒) and (⇐) written out. |
| DP | Every DP has all six lines (state, ranges, base cases, recurrence + cases, order, answer + runtime). |
| FORM | Every model names all its parts (vertices/edges/capacities/s/t/read-off; or variables/objective/constraints/integrality; or U/sets/k′/runtime). |
| CHAIN | Every proof chain uses the hint and the earlier parts it was given; term counts (k vs k+1) checked. |
| CEX | Every False has a concrete counterexample with numbers; every tight instance is a family for all n / k / Δ. |
| PROB | Every expectation is a number (or a formula) with the Σ prob × value written; "how to compute" stated. |
| CALC / OFF1 | The last number answers the question as asked (projected? feasible? integer?); constants match the target (Δ vs Δ + 1, m vs m + 1). |
| LP | Complementary slackness used in the right direction: slack ⇒ partner = 0; tight ⇏ positive. |
10.3 Notation used in these notes
| Symbol | Meaning |
|---|---|
| n, m | number of vertices, edges (or items, constraints: stated each time) |
| OPT, ALG | optimal value; value returned by the algorithm |
| c-approximation | min: 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) |
| Gf | residual graph of flow f |
| c(X, V∖X) | capacity of the s–t cut with source side X |
| A ≤p B | A reduces to B in polynomial time (B is at least as hard as A) |
| η, β, α, G, D | step 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
- Verdict first (True / False / letters).
- True: name the theorem or fact and why it applies here (one line).
- False: the smallest counterexample, with numbers before and after.
- Select-all: one line per option, including the ones you don't select.
These are new items, not taken from the final practice set; that set stays AI-free mock material (see START_HERE).
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Writing only “master theorem” without the comparison d vs log_b a.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Confusing with the converse (next drill).
Select ALL that are always true, and justify each option in one line.
- Pr[X ≥ 6] ≤ 1/2.
- Pr[X ≥ 1] ≥ 1/2.
- Some outcome has X ≥ 3.
- Pr[X ≤ 3] > 0.
Show solution
- Exam 3 select-all rubric: −2.5 for one wrong option, −5 for two. Justify each option separately.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Pattern-matching to “two recursive calls ⇒ n log n”. Check whether the fractions sum to < 1, = 1, or > 1.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Forgetting the fourth case of the duality table (infeasible/infeasible).
Show solution
- Answering 3 (the expected number of non-red draws) when the question counts all draws.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Not deriving the kept fraction (Exam 1A Q1g asked for both fractions with justification).
Select ALL that are always true, and justify each option in one line.
- If x*₁ > 0, the first dual constraint is tight.
- If y*₂ > 0, primal row 2 is tight.
- If primal row 3 is tight, then y*₃ > 0.
- If the first dual constraint is slack, then x*₁ = 0.
Show solution
- Exam 2 Q1b (−5): “tight ⇒ positive” is the trap; only “slack ⇒ zero” follows.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Measuring input size by the number of items only.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Confusing with min, which is not convex (min{x, 0}).
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Practice Exam 3 1(d): the “=” version is false, the “≤” version is the union bound.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- “Some MST” vs “every MST”: uniqueness needs the strict version of the cut property.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Convex ⇏ smooth. Check the second derivative on the whole domain.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Forgetting that time is nonnegative (that is what licenses Markov).
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Dropping the “on a cycle” hypothesis.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Mixing up which bound (lower: α, upper: β) each property controls.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Lec 20 warning, verbatim: “A reduction transfers only the properties proved about it.”
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Saying “need Dijkstra”: correct but slower and misses the point.
Select ALL that are always true, and justify each option in one line.
- the last iterate x_T
- the average x̄ = (1/T)Σ_{t<T} x_t
- the best iterate argmin_t f(x_t)
- every iterate
Show solution
- Choosing A; that is the smooth theorem (η = 1/β), which does cover the last iterate.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Confusing with: edges leaving the min-cut side X (reachable set in the final residual graph) are saturated.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Stopping at “≥ 6.5” without using integrality.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Practice exam (Fall 2025) Q7: same definitional trap.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Over-stating the integrality theorem. In a flow reduction say “take an integral maximum flow (exists by integrality)”.
Select ALL that are always true, and justify each option in one line.
- C is NP-hard.
- C is NP-complete.
- If C ∈ P then P = NP.
- Every problem A ∈ NP satisfies A ≤p B.
Show solution
- Missing D because it does not mention C: read every option on its own.
Select ALL that are always true, and justify each option in one line.
- runs in O((n + m) log n)
- is correct if some edges have weight 0
- is correct with one negative edge as long as there is no negative cycle
- settles vertices in nondecreasing order of distance
Show solution
- Not producing the 3-vertex counterexample for C.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Reflexively answering “probability 2/(n(n − 1))”: that is a lower bound, not the exact value.
Show solution
- Giving [15, 30]: the extra fact (LP) is stronger here; always compare.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Hardness flows to generalizations, not to special cases.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Analogy trap: adding a constant also changes shortest paths, but never the MST.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- NP-hard does not require membership in NP.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Thresholds above ½ can be infeasible (single edge with x = (½, ½)); below ½ stay feasible but cost more.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Exam 3 Q2c (−3): state why one of them is ≥ (the average identity), not just that one is.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Knowing maximal ≠ maximum but not the factor-2 relation between them.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Saying “only for small enough η” without the threshold: decrease holds for every η < 2/β.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Answering “NP-hard ⇒ no” without looking at which parameter is small.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Extending linearity of expectation to products or maxima.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Treating the policy as stationary; the Bellman table is indexed by (state, steps remaining).
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- Exam 3 Q3c rubric: “Did the reverse” cost 3.5 of 7.
Show solution
- Giving y without verifying both inequalities numerically.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
Show solution
- 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
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
“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”
“if the capacities were higher or something I kind of have to do every edge I have to do both the moves”
“the definition and so on is very important of the residual graph”
“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”
“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”
“And now in the middle one, I have basically sending 59 on 100.”
“you can do the bottleneck capacity or even like or just one”
“you can just work with integral flows and you don't lose anything because my capacities are integral”
“especially if it's an integral max flow, you can immediately interpret it as, like, a matched edge.”
“Claim: |f| = Cut value (a) f_e = c_e (b) f_e = 0 ⇒ Total flow = Total cut”
“There is no mention of student or project here?”
“Only one direction is correct of (i) and (ii),”
Unit 1b · Shortest paths and MST
“if there are ties”
“O(n+m+Σ_e(w_e−1)) Claim: Suffices to find shortest path in this expanded graph”
“Optional”
“False. Use directed edges s → u and u → t, each of weight 1, and s → t of weight 3.”
“True, by applying the cut property on the cut ({u},V \ {u})”
Unit 1b · Matchings
“Maximum vs Maximal Global opt Local opt”
“If |M| < |M| then ∃ aug path”
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
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.
| Tag | Pattern | Pts | The check | Drills |
|---|---|---|---|---|
| DP | DP write-up incomplete | 15 | All six lines of the frame (§6), ticked | WS.1–WS.4, U1A.31 |
| IFF | Only one direction (or none) | 14 | Write (⇒) and (⇐) headers first; each preserves value | WS.5–WS.7 |
| CEX | Counterexample / tight instance not produced | 12 | Smallest instance; both values with numbers; families in n / k / Δ | §11 False items, U1B.8 |
| CHAIN | Hint / earlier part not used | 12 | List the given facts that must appear; count terms | WS.15–WS.17 |
| FLOW / FORM | Model with missing components | 12 | Every input parameter appears somewhere (bj as a capacity, k′, U) | WS.12–WS.14 |
| PROB | Expectation not computed / "how" not stated | 11.5 | Σ prob × value written; geometric 1/p; per-clause rule | EC.6, EC.7, EC.11 |
| BOUNDS | One side of "bounds on OPT" missing | 9.5 | Feasibility gives one side, the guarantee the other | EC.12, EC.39, U1A.40 |
| LP | Complementary slackness / Farkas select-all | 9 | Slack ⇒ partner 0; tight ⇏ positive; one line per option | EC.20, EC.51 |
| EXIST | Existence proof | 6 | Extremal choice + boundary cases | WS.8–WS.11 |
| OFF1 | Off-by-one constant / index | 2.5 | Re-read the target constant before finishing | U1A.17 |
| CALC | Calculation stopped one step early | 2 | Does 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.
- 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.
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.
- 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).
Max problem, (1 − ε)-approximation with ε = 1/4 returns 90. Strongest bounds?
Why is "a then c" not a policy in a two-step MDP?
VC ≤ SC: what is the universe, and what is Sv?
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 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)
Show solution
Rows i = 0..5, columns j = 0, 1, 2:
| i | D(i,0) · D(i,1) · D(i,2) |
|---|---|
| 0 | 0 · 0 · 0 |
| 1 | 0 · 4 · 4 |
| 2 | 0 · 4 · 4 |
| 3 | 0 · 4 · 7 |
| 4 | 0 · 6 · 10 |
| 5 | 0 · 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.
- base row and column filled with 0
- each cell from the two cases
- answer cell D(n,k)
- optimal set traced back
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.
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).
- i not chosen. The rest is any feasible choice from 1..i−1 with at most j projects: best value D(i−1, j).
- 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.
- 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
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.
Show solution
- State. D(i) = max total value using only projects 1..i with no three consecutive chosen.
- Range. 0 ≤ i ≤ n.
- Base cases. D(0) = 0, D(1) = v1, D(2) = v1 + v2 (values are nonnegative and two in a row is allowed).
- 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.
- Order. Increasing i.
- 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).
- 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)
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).
Show solution
- State. D(i, j) = max value from projects 1..i choosing at most j, pairwise gaps ≥ 3.
- Ranges. 0 ≤ i ≤ n, 0 ≤ j ≤ k.
- 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).
- 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.
- Order. Increasing i; any order of j inside a row.
- Answer. D(n, k); time and space O(nk).
Run: D(7, 2) = 14 (indices 4 and 7: 6 + 8). Verified by brute force.
- 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)
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)
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.
- (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
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.
- Give the network (vertices, edges, capacities, s, t) and how to read the answer.
- Prove both directions: memberships ↔ integral flow of the same value.
- 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.
- vertices + s,t
- capacities 2 / 1 / b_j with reasons
- (⇒) memberships → flow, capacity checks
- (⇐) integral flow → memberships
- numeric answer with upper-bound check
Putting capacity 2 on the middle edges (allows the same project twice). Writing only (⇒).
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}.
- 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.
- 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.
- 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.
- (⇒) flow 1 on path edges, capacity + conservation
- (⇐) find one path using conservation
- cycle removal
- remove path, induct
- paths are edge-disjoint
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)
Show solution
Extremal choice. Let i ∈ [l, r] maximize A over the interval.
- Neighbours inside [l, r] are smaller: i is the maximum and entries are distinct.
- If i = l, the left neighbour l−1 is outside the interval, but A[l] > A[l−1] by hypothesis.
- If i = r, the right neighbour is smaller by A[r] > A[r+1].
- If l = r, both boundary conditions apply to the single index.
So both neighbours of i are smaller: i is a peak. ∎
- 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
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.
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. ∎
- extremal choice (largest index with f < 0)
- existence and i ≤ n−1
- maximality gives f(i+1) ≥ 0
Not checking that i + 1 ≤ n.
Show solution
Let (r*, c*) be the position of the maximum of M over the block of columns c+1..n.
- Neighbours inside the block are smaller (maximum, distinct entries).
- 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).
- 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.)
- max over the block
- inside neighbours
- the one outside neighbour via the chain of three inequalities
- edges of grid
Forgetting the boundary neighbour, or comparing with M[r][c] for the wrong row: the chain needs “column maximum”.
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. ∎
- choose a longest path (and say why it exists)
- case u on path → cycle
- case u off path → longer path
“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)
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.
- 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
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.
- Give the network in the FLOW checklist format (vertices, edges, capacities, s, t, read-off) for general input.
- 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.
- vertices
- three capacity types
- s and t
- read-off rule
- value + certificate
Capacities missing on s→doctor edges (that is where “at most ci days” lives).
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.
- vertices incl. gadget layer
- capacities 2 / 1 / 1 / 1
- decision rule (= r)
- why the gadget enforces one-per-slot
- both directions sketched
- size polynomial
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)
- Compute ‖∇f(xk)‖² for k = 0, 1, 2, 3 and check they are non-increasing (part (a)).
- Check the hint Σi=03‖∇f(xi)‖² ≤ 2β(f(x0) − f*), and the bound of part (b) at k = 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.
- gradient formula
- iterates
- four squared norms
- hint check
- part (b) check at k=3
- k vs k+1 explained
Using η = 1/β with the wrong β (here β = 4 is the largest curvature, from the 4y² term ×½×2).
Show solution
- Count terms. The sum Σi=0k has k + 1 terms, each ≥ the smallest: Σ ≥ (k+1)·min0≤i≤k ‖∇f(xi)‖².
- Use part (a). The norms are non-increasing, so the minimum is the last one: min = ‖∇f(xk)‖².
- Use the hint. (k+1)‖∇f(xk)‖² ≤ Σ ≤ 2β(f(x0) − f(x*)).
- Finish. Divide by k + 1 and take square roots: ‖∇f(xk)‖ ≤ √(2β(f(x0) − f(x*))/(k+1)). ∎
- sum ≥ (k+1)·min
- min is the last term by part (a)
- chain with the hint
- divide by k+1, square root
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.
- 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?
- (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 ✓.
- (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
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
| # | Part | Pts | Rubric line | Pattern | Redo here |
|---|---|---|---|---|---|
| 1 | E1 Q3b DP recurrence + justification | 10 | Empty | DP | WS.1 U1A.31 |
| 2 | E1 Q4c Flow correctness (i) and (ii) | 8 | Not done | IFF | WS.5 U1B.32 |
| 3 | E1 Q2a Peak exists in [l, r] | 6 | Wrong answer | EXIST | WS.8 U1A.16 |
| 4 | E1 Q4b Students → projects network with bj | 6 | Incorrect or not readable; “no mention of student or project here?” | FLOW | WS.12 U1B.32 |
| 5 | E2 Q3b ‖∇f(xk)‖ bound from the hint | 6 | Not done / incorrect | CHAIN | WS.15 WS.16 |
| 6 | E3 Q3b VC ≤ SC, both directions | 6 | Attempt | IFF | §15.3; full redo in Unit 3 |
| 7 | E1 Q1c Bounds on OPT from (1 − ε) | 5 | Lower and upper bound missing/incorrect | BOUNDS | U1A.40 EC.12 |
| 8 | E1 Q1f Add 7 to every edge: shortest paths? | 5 | Wrong answer | CEX | U1B.8 |
| 9 | E2 Q1b Strict primal constraint ⇒ dual variable? | 5 | Chose “strictly positive” | LP | EC.20; Unit 2 |
| 10 | E2 Q4.4 Tight instance for 1/k rounding | 5 | Blank | CEX | Unit 2 (§35–39) |
| 11 | E3 Q1f Expected samples until a PhD | 5 | Incorrect | PROB | EC.7 EC.18 §15.2 |
| 12 | E2 Q1c Farkas select-all | 4 | Selected one of three true options | LP | EC.51; Unit 2 |
| 13 | E2 Q1f Bounds from a 2-approx VC + matching | 4 | Incorrect | BOUNDS | EC.39 §15.1 |
| 14 | E2 Q4.1 ILP for set cover | 4 | Only the objective | FORM | Unit 2 (§35–39) |
| 15 | E1 Q1d Two-step MDP policy + expectations | 3.5 | Expectations missing/wrong | PROB | U1A.45 EC.6 §15.2 |
| 16 | E1 Q3a DP state, ranges, base cases, answer | 3 | Base cases −1, final answer −2 | DP | U1A.31 WS.2 |
| 17 | E2 Q3c ‖∇f(xk)‖ ≤ βD/√(k+1) | 3 | Used f(x₀) − f* ≤ D | CHAIN | Unit 2 (§35–39) |
| 18 | E2 Q4.3 1/k-threshold rounding is a k-approx | 3 | Major error | CHAIN | Unit 2 (§35–39) |
| 19 | E3 Q2c max{E_T, E_F} ≥ E[Y | …], how to compute | 3 | Missing details on how to compute | PROB | EC.11 EC.44 |
| 20 | E1 Q3c Fill order, time, space | 2 | Incorrect order | DP | U1A.31 |
| 21 | E2 Q1d One projected GD step | 2 | Failing to project | CALC | EC.2 |
| 22 | E2 Q2c Family where greedy IS is exactly OPT/Δ | 2 | Incorrect (ratio 1; only Δ = 2) | CEX | Unit 2 (§35–39) |
| 23 | E3 Q3a Construct the SC instance | 2 | Incorrect/missing U (should be the set of edges) | FORM | §15.3; Unit 3 |
| 24 | E2 Q2b Greedy IS is a Δ-approx | 1.5 | Proved Δ + 1, not Δ | OFF1 | Unit 2 (§35–39) |
| 25 | E1 Q2b Peak recursion: m vs m + 1 | 1 | “needs to be m+1, otherwise infinite recursion on 2 elements” | OFF1 | U1A.17 |
| 26 | E3 Q2b Random assignment 7/8 even if unsatisfiable | 0.5 | Didn't say what happens when OPT < m | BOUNDS | Unit 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.
- 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
What exactly must the induction step prove?
When do you need strong induction instead of ordinary induction?
Why can't you induct on the statement “T(n) = O(n)”?
Template that earns full credit.
- 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).
- Base case(s): verify P at the smallest value(s), numerically.
- Induction hypothesis: “assume P(m) for all m with base ≤ m < n” (strong) or “assume P(k)” (ordinary).
- Step: derive P(n), and point to the exact place where the hypothesis is used and on which smaller value(s).
- 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.
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)
| Pattern | What goes wrong | How to spot it |
|---|---|---|
| Missing/false base case | A correct step from a false start proves nothing (U1A.3). | Plug in the base value. |
| Step fails at the smallest n | The 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 size | The step uses P(n) or P(n+1) while proving P(n). | Check every use is on a strictly smaller value. |
| Circular / proving the converse | Assumes the conclusion, or proves Q ⇒ P instead of P ⇒ Q. | Write “want: …” and “given: …” separately. |
| Only one direction of an iff | Proves P ⇒ Q twice (directly and by contrapositive, U1A.5 option B). | Write headers (⇒) and (⇐) first. |
- 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
- 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 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.- 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.
List the five parts of a full-credit induction proof.
What is the first thing to test when asked “where is the mistake?” in an induction proof?
What are the three parts of a loop-invariant proof?
To prove P ⇔ Q, which pairs of implications suffice?
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 ✓.
- 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.
“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”).
- 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.
“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.)
- Always check the base case numerically, even when the step looks right.
“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.
- Name the exact n where the step fails and the exact assumption that fails (“b < n” is false).
- To prove P ⇔ Q it suffices to prove P ⇒ Q and (not P) ⇒ (not Q).
- To prove P ⇔ Q it suffices to prove P ⇒ Q and (not Q) ⇒ (not P).
- One counterexample disproves “for all x, P(x)”.
- 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.
- This is exactly the “both directions” trap that cost 14 points on your exams: B looks like two directions but is one.
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.
- For lengths (3, 1, 2) in that order, compute the sum of completion times. Then compute it for the sorted order.
- 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.
- Jobs before the pair and after the pair finish at exactly the same times (the pair occupies the same total time px + py).
- 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.
- 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. ∎
- (a) both sums computed
- identify an adjacent inverted pair
- show other jobs unchanged
- compute the change p_y − p_x < 0
- conclude optimal ⇒ sorted
- 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”.
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].
- Initialization: l = 1, r = n, so A[l..r] is the whole array.
- 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.
- 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).
- invariant stated precisely
- initialization
- maintenance (both branches)
- termination ⇒ correctness
- runtime O(log n)
- 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
Define f = O(g) precisely.
Order these: n log n, (log n)5, n0.1, 2n, n!, n².
What is the input size of a single integer N?
| Symbol | Meaning | Limit 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·g | lim 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).
- 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.
For which d is n5 = O(dn)?
Is (log n)100 = O(n0.01)?
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.
- “O(√n) is sublinear, so it's polynomial” is the trap: polynomial means polynomial in the number of bits.
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.
- Rewrite with a common base (ab = 2b log a) before comparing growth rates.
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.
- Θ needs both directions; the lower bound is the one people skip.
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.
- (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
- 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
State the master theorem (course form).
Solve T(n) = T(n/5) + T(7n/10) + Θ(n).
Solve T(n) = T(n/3) + T(2n/3) + Θ(n).
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 a | Per-level cost | Answer | Example |
|---|---|---|---|
| d > logb a | shrinks: root dominates | Θ(nd) | T(n/2) + n = Θ(n) |
| d = logb a | equal on all logb n levels | Θ(nd log n) | 2T(n/2) + n = Θ(n log n) |
| d < logb a | grows: leaves dominate | Θ(nlogb a) | 4T(n/2) + n = Θ(n²) |
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.
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:
- Want: T(n) ≤ Kn log₂ n for T(n) = T(⌊n/2⌋) + T(⌈n/2⌉) + cn.
- Trick: for n ≥ 4 both halves are ≤ 2n/3, so log₂(half) ≤ log₂ n − log₂(3/2).
- 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.
- 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.
- 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.
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 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.- 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.
- 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.
Solve 2T(n/2) + Θ(n²).
Solve 8T(n/2) + Θ(n²).
In the n log n induction proof, where does the saving come from and what does it pay for?
- 2T(n/2) + n
- 2T(n/2) + 1
- 4T(n/2) + n
- 4T(n/2) + n²
- 3T(n/2) + n
- T(n/2) + n
- 7T(n/2) + n²
- 8T(n/2) + n³
Show solution
| a, b, d | logb a vs d | Answer | |
|---|---|---|---|
| a | 2, 2, 1 | 1 = 1 (tie) | Θ(n log n) |
| b | 2, 2, 0 | 1 > 0 (leaves) | Θ(n) |
| c | 4, 2, 1 | 2 > 1 (leaves) | Θ(n²) |
| d | 4, 2, 2 | 2 = 2 (tie) | Θ(n² log n) |
| e | 3, 2, 1 | 1.585 > 1 (leaves) | Θ(nlog₂3) ≈ Θ(n1.585) |
| f | 1, 2, 1 | 0 < 1 (root) | Θ(n) |
| g | 7, 2, 2 | 2.807 > 2 (leaves) | Θ(nlog₂7) ≈ Θ(n2.807) (Strassen) |
| h | 8, 2, 3 | 3 = 3 (tie) | Θ(n³ log n) |
- a, b, d identified
- log_b a compared with d
- correct case and answer for each
- 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.
Show solution
T(n) = Θ(n).
- 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).
- Summing: T(n) ≤ n Σd≥0 (3/4)d = n · 1/(1 − 3/4) = 4n = O(n).
- 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.
- answer Θ(n)
- child sizes sum to (3/4) of parent
- geometric sum ⇒ O(n)
- lower bound from the root
- 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”.
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.
- (a) Θ(n) with geometric sum
- (b) Θ(n log n)
- explanation: sum of fractions < 1 vs = 1
- 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).
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.
- Base (n = 2): T(2) = 2T(1) + 2 = 2(T(1) + 1) = K·2·log₂ 2 ✓.
- Hypothesis: T(n/2) ≤ K·(n/2) log₂(n/2) for some power of two n ≥ 4.
- 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 ✓.
- explicit hypothesis with fixed K
- base case verified
- step algebra with log(n/2) = log n − 1
- constant absorbs +n
- conclusion
- 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
What are the three parts of every D&C answer on the exam?
Merge sort's recurrence and solution?
How do you make a combine step O(1) instead of O(n)?
Answer frame (what the rubric checks):
- Algorithm: base case (size 1 or 2), how you split, the recursive calls, and the combine step. Pseudocode or numbered steps.
- 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.
- Runtime: recurrence → master theorem or tree (§21).
| Problem | Each call returns | Combine | Recurrence |
|---|---|---|---|
| Merge sort | sorted array | merge, 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 search | an index | none: discard one half | T(n/2) + 1 = Θ(log n) |
Takeaway: sortedness of X is what lets one comparison count |X| − i pairs at once.
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.- 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).
In counting inversions, what do you add when an element of Y is output during the merge, and why?
Max difference maxi≤j A[i] − A[j]: what summary makes it Θ(n), and what is the crossing term?
HW1 max contiguous product: the 4 returned values and the base case for an entry x < 1?
Show solution
- Left half [3, 8, 6, 1]: inversions (3,1), (8,6), (8,1), (6,1) = 4. Sorted: [1, 3, 6, 8].
- Right half [5, 2, 7, 4]: (5,2), (5,4), (7,4) = 3. Sorted: [2, 4, 5, 7].
- 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.
- Total = 4 + 3 + 8 = 15 (out of at most C(8,2) = 28).
- 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.
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).
- 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)
- 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.
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).
- The crossing term is ML − mR (order matters: i ≤ j).
Show solution
Idea: return a 4-tuple summary so the combine is O(1): (best, best prefix, best suffix, total).
- 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).
- Recurse on both halves: (BL, PL, SL, TL) and (BR, PR, SR, TR).
- 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.
- 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)
- 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.
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:
- 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.
- 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).
- 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.
- separate counting pass
- monotone pointer ⇒ O(n)
- merge still needed
- recurrence O(n log n)
- 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)
Why does every array (with A[0] = A[n+1] = −∞) have a peak?
After comparing A[m] with A[m+1], which half must contain a peak?
- 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.
- 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]).
- Runtime (Q2c): T(k) ≤ T(⌈k/2⌉) + c ⇒ O(log n).
- 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).
- 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.
Prove in two sentences that [l, r] with A[l] > A[l−1], A[r] > A[r+1] contains a peak.
Why must the kept half be [m+1, r] and not [m, r]?
Show solution
Extremal choice. Let i ∈ [l, r] be the index of the maximum of A[l..r].
- 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.
- If i = l: its left neighbour A[l−1] lies outside, but A[l] > A[l−1] by the hypothesis.
- If i = r: its right neighbour A[r+1] lies outside, but A[r] > A[r+1] by the hypothesis.
- 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.) ∎
- 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
- 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.
Show solution
(b) Algorithm. Start with l = 1, r = n (valid since A[0] = A[n+1] = −∞).
- If l = r, return l.
- 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,8], m = 4: A[4] = 4 > A[5] = 3 → keep [1,4]
- [1,4], m = 2: A[2] = 5 < A[3] = 9 → keep [3,4]
- [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.
- 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)
- 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.
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.
- Binary search on [l, r] = [1, n]: m = ⌊(l+r)/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].
- 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.
- A[i] − i monotone (uses distinct integers)
- correct discard rule both sides
- invariant / correctness
- O(log n)
- Distinctness and integrality are both needed (with repeats, B can decrease).
22.3 Selection: median of medians (Lec 3, HW1 #3)
What makes a pivot "good" and why does it matter?
Write the median-of-medians recurrence for groups of 5.
Select(A, k) (k-th smallest):
- Split A into n/5 groups of 5; find each group's median (constant time per group).
- p = Select(medians, n/10): the median of the medians (recursive call on n/5 elements).
- Partition: L = elements < p, G = elements > p.
- 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.
| Group size M | Recurrence fractions | Sum | Time |
|---|---|---|---|
| 3 | 1/3 + 2/3 | 1 | Θ(n log n): not linear |
| 5 | 1/5 + 7/10 | 9/10 | Θ(n) |
| 7 | 1/7 + 5/7 | 6/7 | Θ(n) |
| M (odd) | 1/M + (3M−1)/(4M) | (3M+3)/(4M) | Θ(n) iff M ≥ 5 |
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.- 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.
Derive the 7n/10 in two lines.
When recursing into G for the k-th smallest, what rank do you ask for?
Smallest odd group size with linear time?
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).
- You scored 6/6 on Q1g; this is maintenance.
Show solution
- 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].
- Medians: [9, 10, 14, 6, 17]; their median (recursive call on 5 numbers) is the pivot p = 10.
- Partition: |L| = #elements < 10 = 9, |G| = #elements > 10 = 15; p has rank 10.
- Recurse: k = 20 > |L| + 1 = 10, so find the (20 − 10) = 10th smallest of G (which is 20).
- Guarantee check: 3 groups have median ≥ 10, each with 3 elements ≥ its median: at least 9 elements ≥ p guaranteed (actually 16).
- When recursing into G, subtract |L| + 1 from k.
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.
- Base: for n ≤ n₀, T(n) is a constant; enlarge k so that T(n) ≤ kn there.
- Hypothesis: T(m) ≤ km for all m < n.
- 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.
- (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
- 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)
What four things must every DP answer state?
DP runtime formula?
What question do you ask about the last element to get a recurrence?
Answer frame (Exam 1A Q3 points in brackets; you lost 15 of these 20).
- 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)).
- 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.
- 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).
| Shape | Entry | Recurrence pattern | Answer | Time |
|---|---|---|---|---|
| 1-D "ends at j" | M[j] = best ending exactly at j | A[j] + max(0, M[j−1]) | maxj M[j] | O(n) |
| Prefix + limit | D(i, j) | max(skip i, take i + D(i−2, j−1)) | D(n, k) | O(nk) |
| Two sequences | D[i, j] on prefixes | match → diagonal + 1; else max(up, left) | D[m, n] | O(mn) |
| Tree | two values per vertex (in / out) | sum over children | at root | O(n) |
| Last piece | T[i, j] = best for first i in j pieces | min over start of last piece | T[n, k] | O(kn²) |
| Budget | T(i, b) | max(skip, vi + T(i−1, b − si)) | T(n, B) | O(nB) |
Takeaway: with an "ends at" definition the answer is the max over all cells, not the last cell.
- 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.
What are the two halves of a full recurrence justification?
Exam 1A Q3 (no two adjacent, at most k): the recurrence?
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.
- 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).
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 \ j | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 1 (v=4) | 0 | 4 | 4 | 4 |
| 2 (v=1) | 0 | 4 | 4 | 4 |
| 3 (v=3) | 0 | 4 | 7 | 7 |
| 4 (v=5) | 0 | 5 | 9 | 9 |
| 5 (v=2) | 0 | 5 | 9 | 9 |
| 6 (v=6) | 0 | 6 | 11 | 15 |
D(6, 3) = 15 (projects 1, 4, 6); with k = 2 the answer is 11, with k = 1 it is 6.
- (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
- 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.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
- A DP that fills an n × n table with O(n) work per cell runs in O(n²).
- For LCS, a table with two rows suffices to output the LCS string.
- Every recursive algorithm with overlapping subproblems runs in polynomial time once memoized.
- In a DP whose entries are defined as “ending exactly at j”, the answer can be any cell, so it is maxj.
Show solution
- False. n² cells × O(n) = O(n³).
- False. Two rows give the length only; recovery needs the full table (or a divide-and-conquer trick not covered).
- False. Memoization is polynomial only if the number of distinct subproblems is polynomial (knapsack: nB subproblems, pseudo-polynomial).
- True (contiguous sum U1A.27, common substring U1A.30).
- Runtime = #subproblems × work per subproblem; say both.
23.2 Two sequences: LCS and its variants (Lec 3–4)
LCS recurrence?
Subsequence vs substring?
- 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.
- 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.
Why can't a 2-row LCS table recover the string?
Longest common substring recurrence?
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.
- 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.
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.
- table definition
- base cases
- three-way recurrence with test
- justification
- O(mn)
- 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).
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).
- “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)
Why two values per vertex in a tree DP?
In which order do you fill a tree DP?
| Problem | v in | v out | Leaf |
|---|---|---|---|
| Max independent set | I[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).
"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]).
- 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).
Vertex cover on a tree: recurrence when v is NOT in the cover?
Balancing array: table and recurrence?
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 ✓.
- Lecture writes it as max(1 + Σ grandchildren, Σ children); the two-state version is the same DP and easier to get right.
Show solution
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}.
- two-state table in words
- leaf base case
- lit recurrence (min over child states)
- unlit recurrence (children lit)
- justification
- answer + O(|V|)
- 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|).
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.
- table definition
- base T[i,1]
- recurrence with max inside min
- justification (last piece)
- O(kn²)
- binary search ⇒ O(kn log n)
- 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
Budget-indexed knapsack recurrence?
Why isn't O(nB) a polynomial-time algorithm?
| Budget-indexed | Value-indexed | |
|---|---|---|
| Entry | T(i, b) = max value from items 1..i with size ≤ b | D[i, v] = min size from items 1..i with value exactly v |
| Recurrence | max(T(i−1, b), vi + T(i−1, b − si)) | min(D[i−1, v], si + D[i−1, v − vi]) |
| Answer | T(n, B) | max v with D[n, v] ≤ B |
| Time | O(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.
- 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.
Value-indexed DP: what is stored and what is the answer?
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=0 | 0 0 0 0 0 0 0 0 0 0 0 |
| i=1 | 0 0 0 0 0 0 30 30 30 30 30 |
| i=2 | 0 0 0 14 14 14 30 30 30 44 44 |
| i=3 | 0 0 0 14 16 16 30 30 30 44 46 |
| i=4 | 0 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.
- T(i,b) in words with ranges
- base cases
- two-case recurrence with s_i ≤ b guard
- justification
- O(nB) + pseudo-polynomial
- 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.
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).
- 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
The FPTAS's K and runtime?
ALG = 80 with ALG ≥ (4/5)OPT. Bounds on OPT?
- Algorithm: K = ε·vmax/n; v̂i = ⌊vi/K⌋; solve exactly with the value DP on v̂; output that set.
- 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).
- 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 type | From feasibility | From the guarantee |
|---|---|---|
| Maximization, ALG ≥ α·OPT (α ≤ 1) | OPT ≥ ALG | OPT ≤ ALG/α |
| Minimization, ALG ≤ α·OPT (α ≥ 1) | OPT ≤ ALG | OPT ≥ ALG/α |
- Always give both bounds; one comes from feasibility, one from the guarantee.
- "PTAS = polynomial in 1/ε" is false (that's FPTAS).
- K = εvmax/n · round down · value DP · loss < nK ≤ εOPT · O(n³/ε).
- Max: ALG ≤ OPT ≤ ALG/α. Min: ALG/α ≤ OPT ≤ ALG.
Which fact justifies nK = εvmax ≤ εOPT?
Minimization, ALG = 12, ALG ≤ 2·OPT: bounds?
Show solution
80 ≤ OPT ≤ 100.
- Lower: the returned solution is feasible, so OPT ≥ 80.
- 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.)
- lower bound 80 from feasibility
- upper bound 100 from the guarantee
- 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.
Show solution
- 45 ≤ OPT ≤ 45/(9/10) = 50.
- For minimization feasibility gives OPT ≤ 12, and 12 ≤ 2·OPT gives OPT ≥ 6: 6 ≤ OPT ≤ 12.
- 30 ≤ OPT ≤ 60.
- Which side feasibility bounds depends on max vs min: write that first.
Show solution
- K = (1/2)·30/4 = 15/4 = 3.75.
- v̂ = (⌊30/3.75⌋, ⌊14/3.75⌋, ⌊16/3.75⌋, ⌊9/3.75⌋) = [8, 3, 4, 2]. Every scaled value is ≤ n/ε = 8.
- Exact DP on scaled values: best scaled value 12 with items {1, 3}.
- True value 46. Guarantee: ≥ OPT − nK = 46 − 15 = 31 ≥ (1 − ε)OPT = 23 ✓ (here we even hit OPT).
- Round down; the loss per item is < K, so the total loss is < nK = ε·vmax ≤ ε·OPT.
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).
- optimal set stays feasible
- rounding loses < K per item
- chain of inequalities
- V' ≥ max v_i justified
- K = ε max v / n
- O(n³/ε)
- Name V' ≥ max vi and why (every item fits alone).
- Compare against the optimal set's rounded value, not the algorithm's.
Show solution
- Let V be the algorithm's value and V' = OPT. Then V ≥ (1 − ε)V' > V' − V'/(n max vi).
- V' ≤ n·max vi (at most all items), so V'/(n max vi) ≤ 1, giving V > V' − 1.
- V and V' are integers, so V = V': the algorithm solves knapsack exactly in polynomial time.
- 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.
- V > V' − V'/(n max v)
- V' ≤ n max v ⇒ V > V' − 1
- integers ⇒ exact
- NP-hard ⇒ P = NP
- The integrality step (V > V' − 1 ⇒ V = V') is the whole trick; state it.
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).
- PTAS: poly(n) for each constant ε. FPTAS: poly(n, 1/ε).
24.3 Greedy for knapsack
- 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.
Why is max(greedy prefix, best item) ≥ OPT/2?
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 ✓.
- density order
- fractional value and exchange argument
- 0/1 greedy vs OPT
- bad example
- max(prefix, best item) ≥ OPT/2 argument
- 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)
Bellman recurrence with t steps left?
Does the optimal first action depend on the horizon?
- 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.
Takeaway: compute every Vt−1 first, then the Q-values; the best action can change with t.
- 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.
- 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ε.
Where does the |S|² in the runtime come from?
Why is the approximate-reward loss 2Tε and not Tε?
Show solution
- Second step first (backward): at u choose c (8 > 3); at v choose d (4 > 2). So V1(u) = 8, V1(v) = 4.
- First step: Q(s, a) = 0 + ½·8 + ½·4 = 6; Q(s, b) = 1 + 4 = 5.
- Policy: take a at s; then c if at u, d if at v. Expected total reward 6.
- second-step choices c at u, d at v
- Q(s,a) = 6 shown
- Q(s,b) = 5 shown
- policy for all states
- 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.
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.
- 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).
Show solution
V0 ≡ 0; Vt(x) = maxa [ r(x, a) + Σ P(x'|x, a) Vt−1(x') ].
| t | V(s) | V(u) | V(w) | V(z) | Q(s,cash) / Q(s,invest) | Q(w,wait) / Q(w,retry) |
|---|---|---|---|---|---|---|
| 1 | 3 | 6 | 1 | 0 | 3 / 0 | 1 / 0 |
| 2 | 3 | 12 | 3 | 0 | 3 / 8/3 | 2 / 3 |
| 3 | 6 | 18 | 6 | 0 | 3 / 6 | 4 / 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.
- Fill by increasing t (steps left); each Vt uses only Vt−1.
- Report Q-values, not just the max: graders check the expectations.
Show solution
- 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 ≤ ε.
- Let π* be optimal for the original (value OPT) and ÔPT the optimum of the modified MDP.
- π* in the modified MDP earns ≥ OPT − Tε, so ÔPT ≥ OPT − Tε.
- π̂ 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.
- fixed policy differs by ≤ Tε
- ÔPT ≥ OPT − Tε via π*
- π̂ in original ≥ ÔPT − Tε
- combine to OPT − 2Tε
- The bound uses two transfers (π* to the modified MDP, π̂ back), each costing Tε: name both.
- The bottom-up Bellman algorithm runs in O(T·|A|·|S|²).
- For a fixed MDP, the optimal first action is the same for every horizon T.
- There is always an optimal policy that is deterministic (no randomization needed).
- 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.
- 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.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
- 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.
- If f' = O(f) and g' = O(g), then f'/g' = O(f/g). What if both are Θ?
- 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.
- Median of medians with group size M = √n runs in O(n).
- There is a polynomial-time algorithm for knapsack when every value vi ∈ {1, …, 10}.
- 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
- False. Each value needs only the previous two: keep two variables, Θ(1) space, Θ(n) time.
- 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).
- 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).
- 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.
- True. The value-indexed DP runs in O(n·Σv) ≤ O(n·10n) = O(n²).
- T(n) = 7T(n/2) + Θ(n²) = Θ(nlog₂7) ≈ Θ(n2.807). Not O(n2.5); yes o(n³) since log₂7 < 3.
- 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
BFS runtime with adjacency lists? With a matrix?
What does BFS compute, and in which graphs is that a shortest path?
Degree-sum formula?
- 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.
- 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).
Why can no edge join layers d and d + 2?
How do you compute the distance from every cell of a grid to the nearest 0 in O(mn)?
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).
- A vertex gets its parent the first time it is discovered (put in the queue), not when it is dequeued.
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).
- multi-source initialization
- BFS on grid neighbours
- correctness via super-source
- O(mn)
- 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.
- In any undirected graph, Σv deg(v) = 2m, so the number of odd-degree vertices is even.
- BFS on an adjacency matrix runs in O(n + m).
- In BFS on an undirected graph, every edge joins vertices whose distances differ by at most 1.
- 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.
- Representation matters for runtime: lists O(n + m), matrix O(n²).
25.2 Paths with extra state: layered graphs and weight tricks
- 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).
How many copies of the graph do you need to find a shortest path using at most k special edges?
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.
- two copies per vertex
- edges switch parity
- Dijkstra from s₀ to t₀
- runtime O((n+m) log n)
- The edge must switch layers (u₀→v₁), otherwise parity isn't tracked.
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).
- weights N vs 1 (or lexicographic pairs)
- why N dominates
- Dijkstra applies (non-negative / monotone)
- runtime
- 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
Write Dijkstra in four lines.
Runtime with a binary heap?
Which assumption does the correctness proof need?
- d[s] = 0, d[v] = ∞ otherwise; a min-priority queue keyed by d.
- Extract the vertex u of minimum key; it is settled.
- 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.
- 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.
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).- 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).
In the correctness proof, which exact inequality uses non-negative weights?
How do you change Dijkstra to minimize the maximum edge on a path?
Show solution
- Settle s (0): d[a] = 4, d[b] = 1.
- Settle b (1): d[a] = min(4, 1 + 2) = 3, d[d] = 1 + 5 = 6.
- Settle a (3): d[c] = 3 + 1 = 4.
- Settle c (4): d[d] = min(6, 4 + 3) = 6 (no change).
- 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.
- Write the tentative-distance updates, not only the final answer: that's where partial credit sits.
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.
- Recover the path from parent pointers, backwards from t.
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.
- 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.
- 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).
- Non-negative weights: the prefix of P up to y is no longer than P: dist(s, y) ≤ dist(s, u).
- 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).
- 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
- 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.
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.
- 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)
- 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.
Show solution
- Dijkstra from s gives ds(·). Dijkstra from t on the reversed graph gives dt(x) = dist(x, t).
- Answer = minr∈R ds(r) + dt(r); splice the two paths at the best r.
- 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).
- Dijkstra from s
- Dijkstra to t on reversed graph
- min over r with justification
- runtime
- Distances to t need the reversed graph in a directed graph.
26.2 Weight transformations and counterexamples (Exam 1A Q1f)
| Transformation | Shortest paths | MST |
|---|---|---|
| w ↦ c·w, c > 0 | preserved | preserved |
| w ↦ w + c | can 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) |
Takeaway: for every T/F about transformations, test two paths with different numbers of edges.
- You answered "True" on Exam 1A Q1f (−5). A counterexample needs explicit weights and both paths' costs before and after.
Give a 3-edge counterexample to "adding a constant preserves shortest paths".
Why does adding a constant preserve the MST?
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.
- verdict False
- concrete graph with weights
- costs before and after shown
- 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).
- w ↦ 5w
- w ↦ w + 2
- w ↦ w²
- w ↦ w/2 + 0 (halving)
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.
- 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
State the cut property, including the "some / every" distinction.
Prim vs Kruskal in one line each?
Is an MST a shortest-path tree?
- 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.
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.- 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.
- 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).
In the exchange proof, why must the cycle in T + e contain another crossing edge?
Which cut proves the lightest edge at u is in some MST?
When does Kruskal reject an edge?
Show solution
(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.
- For each rejected Kruskal edge, name the cycle it would close.
- Prim compares only edges crossing (tree, rest), not all remaining edges.
Show solution
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.
- Let T be an MST. If e ∈ T, done. Otherwise T + e contains a cycle through e.
- That cycle crosses the cut via e, so it must cross back via another edge f ∈ T that also crosses the cut.
- 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.
- 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. ∎
- statement with some/every
- T + e has a cycle
- cycle crosses back via f
- exchange T + e − f, weight ≤
- uniqueness ⇒ strict ⇒ every MST
- “Some” vs “every”: only a unique light edge is in every MST (ties!).
- Explain why the cycle must cross the cut a second time.
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.
- Name the cut explicitly: that's the whole justification.
Show solution
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).
| Cut | Crossing | Light |
|---|---|---|
| {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) |
- A tied light edge is certified for some MST only.
- Cycle property: the unique heaviest edge of a cycle is in no MST.
True or False? Justify in 1–2 lines (a counterexample suffices for False).
- If all edge weights are distinct, the MST is unique.
- An MST is a shortest-path tree from any of its vertices.
- Adding the same constant to every edge weight leaves the set of MSTs unchanged.
- Squaring every weight leaves the set of MSTs unchanged.
- Prim's algorithm fails with negative edge weights.
Show solution
- 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.
- 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.
- True. Every spanning tree has n − 1 edges, so all trees shift by the same amount.
- 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.)
- False. The cut-property proof only compares weights; it never needs them to be non-negative (Lec 7 board).
- 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
Maximal vs maximum matching?
Define an M-augmenting path.
Berge's theorem?
- 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).
- 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*|.
Why does every vertex have degree ≤ 2 in M △ M*?
Can M △ M' contain a 7-cycle?
Show solution
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.
- You scored 6/6 here; keep the habit of checking both endpoints are unmatched.
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).
- Length-1 paths count: an edge between two unmatched vertices is an augmenting path.
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.
- (⇒) 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
- Both directions, labelled; the (⇐) direction is the M △ M* argument.
- Justify why the extra component's endpoints are free in 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'|.)
- Go through every component type, not just augmenting paths.
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|.
- The factor-2 argument reappears in Unit 2's vertex-cover approximation.
28.2 Bipartite matching algorithm and Hall's theorem
Hall's condition?
Runtime of the augmenting-path bipartite matching algorithm?
- Start with M = ∅.
- Orient edges: unmatched A → B, matched B → A. BFS from all unmatched vertices of A.
- If an unmatched vertex of B is reached, follow parent pointers back: that is an augmenting path. Flip it and repeat.
- 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.
- 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.
Why does a d-regular bipartite graph satisfy Hall's condition?
In HW2 #9 (⇒), which matching do you start from, and why?
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.
- Every vertex of T is matched (otherwise the alternating path to it would be augmenting, contradicting maximality, Berge).
- 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.
- 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.
- 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.
- 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
- 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”.
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.
- A Hall violator is a short certificate that no left-perfect matching exists: give S and N(S).
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.
- (⇐) 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
- 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
The two constraints on a flow?
Residual capacities of an edge with flow 4 and capacity 9?
Ford–Fulkerson runtime with integer capacities?
- 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.
- Reverse residual capacity = current flow, not capacity.
- When drawing Gf for an edge with 0 < f < c, draw both directions ★ Flagged in lecture · B02.
What happens to an original edge when an augmenting path uses its reverse residual edge?
Why is Ford–Fulkerson only pseudo-polynomial?
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).
- Reverse residual = current flow, not capacity.
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.
- (1) all forward/backward residuals
- (2) valid path with Δ ≥ 3 and new flow
- (3) value 10
- (4) cut (s,B), (A,D), (E,t)
- 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.
Show solution
- 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.
- s→b→a→t uses the backward edge b→a, Δ = 1: the flow on a→b drops to 1; |f| = 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).
- 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.
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 ✓.
- BFS finds the path with the fewest edges; ties broken alphabetically here.
29.2 Minimum cuts and max-flow min-cut
- 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.
- 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.
How do you extract a minimum cut from a maximum flow?
Does increasing the capacity of a min-cut edge always increase the max flow?
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).
- Count only edges from S to V∖S; edges entering S don't count toward the capacity.
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.
- (a) conservation sum ⇒ ≤ cut
- (b) leaving edges saturated
- (b) entering edges zero
- (b) equality
- (c) flow + equal cut
- Name both facts at the cut: leaving edges saturated, entering edges empty.
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.
- (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|²)
- 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)
Bipartite matching as a flow: the network?
What are the two directions of a flow-reduction proof?
Answer frame (Exam 1A Q4: 14 points lost; rubric quotes in the problem below).
- 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.
- 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).
- Reading the answer: "compute an integral max flow; assign i to j iff f(ai, pj) = 1" ★ Flagged in lecture · B09.
- (i) Solution ⇒ flow: route one unit per assigned pair; check capacities and conservation; value q.
- (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.
- Runtime: FF with |f*| ≤ n: O(n(n + m)).
Modeling toolbox:
| Constraint | Gadget |
|---|---|
| Item used at most k times | edge from s (or to t) with capacity k |
| Vertex capacity k | split v into vin → vout with capacity k |
| Edge-disjoint paths | all capacities 1; max flow = number of paths (Menger) |
| "i requires j" (closure) | ∞ edge i → j; min cut (project selection) |
| Multiple sources/sinks | super-source / super-sink |
- "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.
- 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.
Which capacity enforces "project j takes at most bj students"?
Where is integrality used in the correctness proof?
How do you enforce a capacity on a vertex?
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.
- (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
- 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).
Show solution
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.)
- network with s/t edges and ∞ requirement edges
- finite cut ⇒ closed set
- cut = Σpositive − profit(S)
- answer 2
- Write the capacity of a cut in terms of the chosen set: that identity is the proof.
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|).
- (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
- Argue the max flow changes by at most 1 in each case; that's why one augmentation suffices.
- The maximum number of edge-disjoint s–t paths equals the max flow with all capacities 1.
- To limit how much flow passes through a vertex v, split v into vin → vout with that capacity.
- If all capacities are integers, every maximum flow is integral.
- Increasing the capacity of an edge in a minimum cut always increases the max-flow value.
- 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.
- Integrality theorem: an integral max flow exists (and FF finds one); not every max flow is integral.