COMP 550 Final Exam Study Guide
Algorithms and Analysis · UNC-Chapel Hill, Fall 2026 · course Chapters 1–8 except 7, every algorithm with its correctness argument and running time
Follow-along worksheet (PDF) · Reading copy (PDF) · Two-page cheat sheet (PDF) · Cheat sheet (web) · Midterm 1 guide · Midterm 2 guide
0. What the final tests and how to use this guide
The COMP 550 final is a three-hour, closed-everything exam on paper: eight problems worth five points each, 40 points in all, drawn from course Chapters 1–8 except Chapter 7. It asks two kinds of question. Problems 1 and 2 are ten one-point parts, "like short homework", in which you run a course algorithm by hand on a small input (or decide whether a statement is true) and write only the answer, with no explanation and no partial credit. Problems 3 through 8 are "like problem sets": each gives a problem and a target running time, or an algorithm to analyse, and every full answer contains the same three things: an algorithm in pseudocode, an argument for why it is correct, and an analysis of its running time that reaches the target. The official Practice Final of December 1 shows where the weight falls: a quarter of its points (Problems 1 and 2) are hand traces and True/False parts, 14 of its 40 points touch flows and approximation algorithms (course Chapters 6 and 8, which no earlier exam covered), and two of its six long problems are problem-set problems copied word for word (Problem Set 4.5 and 8.1), as the instructor said at least two would be. So the newest chapters, Chapter 8 and Chapter 9 of this guide (course Chapters 6 and 8), carry more weight than their five class days suggest, and the problem-set sections of every chapter carry the most weight per hour of study. Being ready means three things: you can trace every algorithm on the cover page without a slip, you can reproduce the official solution of every problem-set problem from memory in the three-part format, and you can tell which known method a new problem is a disguised version of.
Table of contents
On the web page, the sidebar on the left repeats this list, with every section, and highlights the section you are reading as you scroll down the page.
About the exam
The evidence for this format comes from three places that agree. The instructor's handwritten notes of Tuesday, December 1 (the Practice Final lecture) give the "Final Exam Format (similar to midterms)": "3 hours, closed-everything", "8 problems, 5 points each", "P1–P2: ≈ short HW", "P3–P8: ≈ psets", and, underlined, "≥ 2 identical to pset", with the red margin note "Final Exam: Thu 12/10, 4–7pm, Ch. 1–8 except 7"; the notes of November 17 and November 24 carry the same scope. The cover page of the Practice Final (40 points, 3 hours) prints the rules and the list of algorithms that may be called by name, and its Problems 1 and 2 say "Do not explain your answers. (1p each, no partial credit)". The instructor's reminder relayed on December 4 (Campuswire Post #43) repeats the date, time and room, the 3 hours and the closed-everything rule, and asks you to bring pens or pencils and your One Card. The two midterms followed the same pattern on a smaller scale: five problems of five points, a first problem of five one-point traces, and exactly two of the four long problems copied from problem sets (Midterm 1 used PS 2.1 and 3.4, Midterm 2 used PS 4.5 and 5.4). The syllabus adds the stakes: the final is worth 30% of the grade, and it replaces the lower midterm score if (and only if) it is higher. The course notes themselves open Chapter 7 with "none of this content will be assessed on an exam".
- all algorithms refer to the ones described in the lectures/notes,
- you should describe your algorithms in pseudocode similar to the examples given in lectures, notes, and problem sets (e.g., no hashing allowed),
- array indices start at 1,
- the values in any array A should be listed in order from A[1] through A[n],
- the input graph has vertex set V, edge set E, n = |V|, m = |E|, and the graph is in adjacency list format."
You may call the 31 algorithms listed on the cover page by name and "assume that they have any properties (e.g., correctness, running time) mentioned in the lectures/notes"; Section 1.2 lists them with the notes' running times. "You may also call a slightly modified version, but if your modifications are unclear, you might not get full credit." Ties are broken in favour of the vertex with the smallest label (the lectures' rule, repeated inside each exam question that needs it). "Anything written outside the boxes will be ignored, even if you reference it in a box." A question that says "prove it, or give a counterexample" wants "Yes" or "No" as the first word. A one-point part wants exactly the format it asks for ("Your answer should be 6 numbers").
- Homework 6 (flows and cuts) is missing from the sources. Section 8.7 builds the one-point question types for that chapter from the in-class worksheets, Practice Final 1(a) and fresh instances instead.
- The class forum (Campuswire) is represented only by the seven posts the instructor relayed to the course inbox; anything said only on the forum is not here.
- Course Chapter 9 (Formal Methods, November 24) and course Chapter 7 (Computational Complexity) are not examined. Course Chapter 9 is not covered; course Chapter 7 gets a short context chapter, Chapter 10 of this guide, because course Chapter 8 (guide Chapter 9) builds on its vocabulary.
- The full grading rubrics are not public. What the guide says about partial credit comes from the remarks printed in the official solutions (quoted in Section 14.4).
- The lecture notes are handwritten. Wherever a word or number in them could not be read with certainty, the chapter that uses it says so at that point.
How answers are written
Every long problem in this course is posed as an input, a goal and a target running time ("Describe an O(m + n)-time algorithm for this problem, explain why it's correct, and analyze its running time"), and every official solution has three parts in that order. The algorithm is one or two sentences stating the idea, then pseudocode in the lectures' style (4 to 12 lines, calling listed algorithms by name). The correctness argument is one paragraph whose type you can name: a loop invariant or induction, an exchange argument or the cut and cycle properties, the cases of a recurrence, a correspondence between a new input and an old one, or a bound on OPT. When the problem may have no solution, the argument covers both directions: whatever the algorithm returns is valid, and if a solution exists the algorithm finds one. The running time is one or two sentences that add up the cost of each step and simplify to the target. Dynamic programs use the course's four-step variant (subproblems, recurrence with base cases and the reason it holds, pseudocode filling d, running time = number of subproblems × time per subproblem). Approximation proofs use a bound on OPT, a bound on ALG in terms of it, and the ratio; a "prove it or give a counterexample" question starts with "Yes" or "No", and a counterexample computes both ALG and OPT on an explicit instance. Chapter 1 derives each form from the official solutions (Section 1.1, Section 1.6, Section 1.8), and every worked solution in the guide follows it with the same labels.
What you must be able to do
The table lists every algorithm the Practice Final cover page allows you to call by name, plus the two proof skills that Problems 4 and 8 of the Practice Final test. For each algorithm you need two abilities: trace it by hand on a small input in the format a one-point part asks for, and call it inside a longer answer with its conditions checked and its running time quoted. The running times are the ones stated in the course notes.
| Algorithm or skill | What you need to be able to do | Running time as the course states it | Section |
|---|---|---|---|
| Max-in-Array | keep a running maximum; prove it with the invariant m = max(A[1:i]) | O(n) | 2.1 |
| Two-Sum | run the two pointers on a sorted array and return (i, j) or nothing; prove both directions | O(n) | 2.2 |
| Binary-Search | list the midpoints m it tests; say why the range halves | O(log n) | 2.3 |
| Selection-Sort | write A after each round | O(n²) | 2.4 |
| Merge-Sort | list the comparisons of a merge; write the recurrence T(n) = 2T(n/2) + O(n) | O(n log n) | 2.5 |
| BFS | fill d (∞ if unreachable) and the BFS tree; modify it (2-coloring, component labels) | O(m + n) | 3.2 |
| DFS | fill pre and post with smallest-label ties; classify every edge | O(m + n) | 3.3 |
| Explore | mark every vertex reachable from u (the recursive half of DFS) | part of DFS's O(m + n) | 3.3 |
| Find-Cycle | return a cycle from a back edge, or nothing; state the two directions of its proof | O(m + n) | 3.5 |
| Topological-Sort | order a DAG by decreasing post; use the order to solve DAG problems | O(m + n) | 3.6 |
| Prim | list the edges in the order chosen; justify each by the cut property | O(mn) = O(m²) | 4.3 |
| Kruskal | list the edges kept in increasing weight, skipping those that close a cycle | O(m log m) + m · O(n) = O(m²) | 4.4 |
| Reverse-Delete | list the edges deleted in decreasing weight; justify by the cycle property | O(m log m) + m · O(m) = O(m²) | 4.5 |
| Select-Intervals | sort by end time and pick greedily; write the exchange argument | O(n log n) | 4.6 |
| Fractional-Knapsack | sort by v[i]/w[i], fill greedily, report x in item order | O(n log n) | 4.7 |
| LIS | fill d (LIS ending at A[i]) and return max(d), not d[n] | O(n²) | 5.2 |
| LPS | fill the interval table from the diagonal up and return d[1][n] | O(n²) | 5.3 |
| Edit-Distance | fill the (m + 1) × (n + 1) table with insert, delete and replace | O(mn) | 5.4 |
| Knapsack-DP | fill rows i = 1..n, columns 0..B, and give the last row | O(nB) | 6.1 |
| DAG-DP | compute shortest (or longest, or widest) paths in topological order using GR | O(m + n) | 7.2 |
| Bellman-Ford | fill the table d[v][j] column by column; stop early at j = k | O(mn) | 7.3 |
| Dijkstra | list the order vertices join S and the final d; check ℓ ≥ 0 first | O(n²) | 7.4 |
| Floyd-Warshall | update the n × n table once per intermediate vertex r | O(n³) | 7.5 |
| Ford-Fulkerson | augment along residual paths, give the flow value; build networks for new problems | O(mv), v = max flow value | 8.2 |
| Minimum-st-Cut | read S off the last residual graph; quote max flow = min cut | O(mv) | 8.3 |
| Bipartite-Matching | build the s, L, R, t network and read the matching off f | O(mn) | 8.4 |
| Bipartite-VC | turn a minimum cut S into the cover (L \ S) ∪ (R ∩ S) | O(mn) | 8.5 |
| Vertex-Cover approximation | take both endpoints of a remaining edge; prove |S| = 2|M| ≤ 2 · OPT | polynomial ("an analysis is not even necessary") | 9.2 |
| Load-Balancing approximation | assign jobs in order to the least-loaded machine; prove T ≤ 2T* | polynomial | 9.3 |
| Metric k-Center approximation | start with S = {1}, add the farthest point k − 1 times; prove radius ≤ 2r* | polynomial | 9.4 |
| Maximum Cut approximation | move single vertices while the cut grows; prove ALG ≥ OPT/2 | at most w(E) iterations, not polynomial in general | 9.5 |
| Skill: prove an approximation ratio | feasibility, a bound on OPT, assign each OPT element to an ALG element (Practice Final 4 = PS 8.1) | none needed | 1.8, 9.6 |
| Skill: prove it or give a counterexample | first word Yes or No; a counterexample names the instance, ALG, OPT and the ratio (Practice Final 8) | none needed | 1.8, 9.6 |
What is in scope
One row per class day of the semester, from the lecture file dates in the course's Lectures folder and the syllabus schedule ("(x, y)" in the syllabus means course Chapter x, Day y).
| Lecture file date | Course chapter and day | Core ideas in one line | In this guide |
|---|---|---|---|
| 08-18 (Tue) | Ch. 0, Day 1/1 | Course plan; greedy rules for selecting intervals and their counterexamples; a first knapsack table | Ch 1 |
| 08-20 (Thu) | Ch. 1, Day 1/2 | The answer template; Max in Array, primitive operations and O-notation, proof by induction; Two Sum | 2.1, 2.2 |
| 08-25 (Tue) | Ch. 1, Day 2/2 | Two Sum correctness; Binary Search; Selection Sort; Merge Sort and T(n) = 2T(n/2) + O(n); the container problem | 2.3–2.6 |
| 08-27 (Thu) | Ch. 2, Day 1/3 | Graph representations, adjacency lists by default; BFS and its O(m + n) analysis | 3.1, 3.2 |
| 09-01 (Tue) | Ch. 2, Day 2/3 | BFS parent pointers; DFS, Explore, pre and post; edge types; Find-Cycle | 3.3–3.5 |
| 09-03 (Thu) | Ch. 2, Day 3/3 | Topological sort by decreasing post; DAG problems via the topological order (PS 2.2); strongly connected components | 3.6, 3.7 |
| 09-08 (Tue) | Ch. 3, Day 1/3 | Max k-Sum and the exchange argument; waiting times (PS 3.2); MSTs, the cut property, Prim | 4.1–4.3 |
| 09-10 (Thu) | Ch. 3, Day 2/3 | Kruskal; the cycle property and Reverse-Delete; selecting compatible intervals; fractional knapsack | 4.4–4.7 |
| 09-15 (Tue) | Ch. 3, Day 3/3 | Midterm 1 format; Kruskal with union-find (a tangent, not examined); exchange proof for fractional knapsack; proof of the cycle property | 4.4, 4.5, 4.7 |
| 09-17 (Thu) | Practice Midterm 1 | In-class practice exam on Ch. 1–3 (no worksheet) | 2.9, 3.10, 4.10 |
| Tue Sep 22 | Midterm 1 (no lecture file) | Exam on Ch. 1–3, 65 minutes | 2.9, 3.10, 4.10 |
| 09-24 (Thu) | Ch. 4, Day 1/5 | The DP method on Max and Sum; LIS and the "LIS trick"; longest increasing subarray (PS 4.2) | 5.1, 5.2 |
| 09-29 (Tue) | Ch. 4, Day 2/5 | LIS parent pointers; LPS on intervals; 0/1 Knapsack | 5.2, 5.3, 6.1 |
| 10-01 (Thu) | Ch. 4, Day 3/5 | Minimum-cost jumps (PS 4.3); bottom-up versus top-down (Fibonacci); Edit Distance | 5.4, 6.7 |
| Tue Oct 6 | No class (well-being day) | ||
| 10-08 (Thu) | Ch. 4, Day 4/5 | The DP patterns; Edit Distance recap; independent set in trees | 6.3, 6.4, 6.6 |
| 10-13 (Tue) | Ch. 4, Day 5/5 | Saving space; buying and selling a stock (PS 4.5); the Alice-and-Bob game; matching in a tree | 6.2, 6.5, 6.7 |
| Thu Oct 15 | No class (fall break) | ||
| 10-20 (Tue) | Ch. 5, Day 1/3 | Single-source shortest paths; DAG DP, longest and widest paths (PS 5.1); Bellman-Ford | 7.1–7.3 |
| 10-22 (Thu) | Ch. 5, Day 2/3 | Bellman-Ford-2 (space saving); Dijkstra; heaps (O(m log n), a tangent) | 7.3, 7.4 |
| 10-27 (Tue) | Ch. 5, Day 3/3 | Midterm 2 format; Floyd-Warshall; one negative edge (PS 5.2); shortest walk under a cost budget | 7.5, 7.7 |
| 10-29 (Thu) | Practice Midterm 2 | In-class practice exam on Ch. 4–5 (no worksheet) | 5.7, 6.9, 7.9 |
| Tue Nov 3 | Midterm 2 (no lecture file) | Exam on Ch. 4–5, 65 minutes | 5.7, 6.9, 7.9 |
| 11-05 (Thu) | Ch. 6, Day 1/3 | Flow networks; why greedy augmenting fails; residual graphs and Ford-Fulkerson; minimum cuts introduced | 8.1, 8.2 |
| 11-10 (Tue) | Ch. 6, Day 2/3 | Minimum s-t cut and the max-flow min-cut theorem; reductions; bipartite matching and vertex cover | 8.3–8.5 |
| 11-12 (Thu) | Ch. 6, Day 3/3 | Vertex capacities (PS 6.3); a path through u (PS 6.4); baseball elimination (PS 6.5); image segmentation (extra) | 8.6 |
| 11-17 (Tue) | Ch. 7, Day 1/1 and Ch. 8, Day 1/2 | P, NP and reductions (not examined); α-approximations; Vertex Cover; greedy Load Balancing | Ch 10, 9.1–9.3 |
| 11-19 (Thu) | Ch. 8, Day 2/2 | Load Balancing: sorted 3/2 (PS 8.3) and the tight instance (PS 8.2); Metric k-Center; Maximum Cut by local search | 9.3–9.5, 9.7 |
| 11-24 (Tue) | Ch. 9, Day 1/1 | Formal methods: specifications, Dafny and Lean (not examined) | Not covered |
| Thu Nov 26 | No class (Thanksgiving recess) | ||
| 12-01 (Tue) | Practice Final Exam (last class) | Final exam format; the Practice Final walked through | Ch 11 |
| Thu Dec 10 | Final exam, 4:00–7:00 pm | Ch. 1–8 except 7, 3 hours | All |
The problem sets match the chapters one to one, except that there is no Problem Set 7 (and no Problem Set 9): Problem Set 1 is worked in Section 2.7, 2 in Section 3.8, 3 in Section 4.8, 4 in Section 6.7, 5 in Section 7.7, 6 in Section 8.6 and 8 in Section 9.7, and all 35 problems are collected in one table in Section 14.2.
How to read this guide
Read Chapter 1 first even if you remember the midterms: it fixes the format every long answer must have. After that the order below puts the two chapters that no exam has tested yet, and the problem-set sections, at the start of the week, and leaves the last two days for timed practice. It assumes about five hours a day from Friday, December 4 to Wednesday, December 9; if you have less time, keep the problem-set sections and the practice finals and skim the rest.
| Day | Read and do | Time |
|---|---|---|
| 1 (Fri Dec 4) | Chapter 1; Chapter 8 (flows and cuts) with every check-in, ending with Problem Set 6 | 1.5 h + 3.5 h |
| 2 (Sat Dec 5) | Chapter 9 (approximation) ending with Problem Set 8; then the problem-set bank table, read once from top to bottom | 3.5 h + 1 h |
| 3 (Sun Dec 6) | Problem-set sections 2.7, 3.8, 4.8, 6.7, 7.7: cover each official solution and write it from memory; reread the matching chapter section whenever you cannot | 5 h |
| 4 (Mon Dec 7) | The hand traces of Chapters 2–7: do every check-in and the "homework-style questions" section of each chapter; skim Chapter 10 if Chapter 9's vocabulary is shaky | 5 h |
| 5 (Tue Dec 8) | The official Practice Final (Chapter 11) on paper in 3 hours, then grade it against the solutions and reread the sections its misses point to | 3 h + 1.5 h |
| 6 (Wed Dec 9) | Version A or version B timed (the other if time allows); Chapter 14; Chapter 15 and the cheat sheet the evening before; sleep | 3 h + 1.5 h |
The follow-along worksheet is the same text printed with blank, ruled boxes: dashed check-in questions at the points where you should stop and try something before reading on, a box under every exercise, and exam-sized boxes under every practice-exam problem, with all answers collected in an answer key at the end. Print it and work through it in pencil. On this web page the same check-ins appear as dashed boxes whose answers open on click.
Blue boxes contain definitions and formulas to know by heart. Orange boxes describe mistakes that are easy to make and cost points. Green boxes connect a topic to how it is tested. Grey text marked "extra context" goes beyond the course materials.
Course Ch. 0 · Aug 181. How a 5-point answer is written
This chapter comes first because every later chapter relies on it. The final has eight problems worth 5 points each. Problems 1 and 2 are ten one-point hand traces and True/False questions with no explanation and no partial credit. Problems 3 through 8 are design and proof problems "like problem sets", and the official solutions to every past exam write them in the same few shapes. This chapter takes those shapes apart: what the three parts of an answer are, how the pseudocode should look, how running times are counted, the four ways the course proves correctness (loop invariant or induction, exchange argument with the cut and cycle properties, exhaustive cases of a recurrence, and correspondence for reductions), how approximation ratios are proved or refuted, and how to answer a one-point question safely. Every recipe below is extracted from the course notes (the typed Chapter pages on Canvas), the Chapter 0 lecture of 08-18, and the official solutions to Midterm 1, Midterm 2, the two practice midterms, the Practice Final and the problem sets. A full-credit answer is short and always has the same skeleton: the algorithm (one idea sentence plus pseudocode), a correctness argument of a named kind, and a running-time count; learn the skeleton once and every chapter becomes practice in filling it in.
Chapter 0 of the course set the vocabulary used throughout. The course is about combinatorial optimization: "combinatorial" because the objects are discrete (arrays, graphs) rather than continuous, so there are no derivatives, and "optimization" because the goal is usually to find an object that maximizes or minimizes some number. The notes define a feasible solution as one that satisfies the constraints and an optimal solution as a feasible solution whose value is as large (or small) as possible. The lecture's examples were Selecting Compatible Intervals (five events, the optimal solution is {Event 2, Event 3, Event 5}) and 0/1 Knapsack (items with value and cost 5/2, 2/1, 7/3 and a budget of 5 dollars, optimal value 12 from items 1 and 3). The value of an optimal solution is written OPT and the value of the algorithm's solution ALG; both letters appear in almost every proof below.
1.1 The three parts of an answer and the cover-page conventions
In plain words. Every design problem on the final ends with the same request: describe an algorithm, explain why it is correct, and analyze its running time. The grader therefore looks for three things, in that order, and an answer that is missing one of them loses points even when the idea is right. The course notes present every algorithm in exactly this format, under the headings Problem Statement, Algorithm, Correctness and Running Time, so the notes themselves are the model answers. On top of that, the exam cover page fixes a handful of conventions (indexing, graph format, no hashing) that every answer must follow.
- The three parts are Algorithm (one or two sentences giving the idea, then pseudocode), Correctness (an argument of a named type), and Running time (a count that reaches the target bound).
- Dynamic programs use the course's variant: Subproblems, Recurrence (with base cases and why it holds), Algorithm, Running time. The "why it holds" sentence is the correctness proof.
- Approximation proofs use: a bound on OPT, a bound on ALG in terms of it, and the conclusion (the ratio).
- The target running time in the problem ("Describe an O(m + n)-time algorithm") is a hint about which tool to use; an answer that is correct but slower than the target does not get full credit.
- The five cover-page rules: algorithms mean the ones from the lectures and notes, pseudocode like the lectures with no hashing, indices start at 1, arrays listed from A[1] to A[n], graphs have V, E, n = |V|, m = |E| in adjacency-list format. Tie-breaking is not on the cover page; when it matters the question says so ("As usual, break ties in favor of the vertex with the smallest label").
- Only what is written inside the answer boxes is graded: "Anything written outside the boxes will be ignored, even if you reference it in a box."
The recipe
- Algorithm. One or two sentences that state the idea in English ("Run Dijkstra's on a graph with two copies of G", "Sort A by non-decreasing t and scan"). Then pseudocode in the course's idiom, 4 to 12 lines, calling known algorithms by name where possible.
- Correctness. One paragraph whose argument has a recognisable type: loop invariant or induction (Section 1.4), exchange argument or cut/cycle property (Section 1.5), the cases of a recurrence (Section 1.6), a correspondence between the new input and the old one (Section 1.7), or a bound on OPT (Section 1.8). When the problem can have "no solution", argue both directions: whatever the algorithm returns is valid, and if a solution exists the algorithm finds one.
- Running time. One or two sentences: the cost of each step, added up, simplified to the target bound (Section 1.3).
A worked instance
Midterm 1, Problem 4 is a typical full-credit answer, and its official solution shows how little needs to be written. The problem: the input is a DAG G, and the goal is to return a vertex that can reach every vertex in G, or nothing if no such vertex exists, in O(m + n) time. (Recall that a DAG is a directed graph with no directed cycle, and a topological ordering lists the vertices so that every edge points from left to right.) Here is the official solution, with the three parts labelled.
Algorithm. "Let R = [R[1], …, R[n]] be a topological ordering of G. If R[1] can reach every vertex, we return it; otherwise, we return nothing."
ALG(G):
R = topological-ordering(G)
d = BFS(G, R[1])
if infinity not in d: # check if R[1] can reach every vertex
return R[1]
Correctness. "If the algorithm returns R[1], then R[1] can reach every vertex and the algorithm is correct. Otherwise, we need to show that no vertex can reach every vertex in G. In this case, R[1] cannot reach every vertex in G, and every other vertex is R[i] for some i > 1. Since R is a topological ordering, there are no edges from R[i] to any vertex left of R[i], so no R[i] can reach any vertex before it in R."
Running time. "Topologically ordering G and running BFS both take O(m + n) time, and scanning d takes O(n) time, so the total running time is O(m + n)."
Notice the proportions. The idea is one sentence, the pseudocode is four lines and calls two named algorithms, the correctness paragraph handles both directions (when it returns something, and when it returns nothing), and the running time is one sentence that adds up the named costs. The whole answer is under 200 words. Most official solutions on the past exams and the Practice Final are about this length; the longest ones add an alternative solution or a note on a common mistake, not more proof.
What the grader looks for
The official solutions record the mistakes that cost points, and they are instructive. On Midterm 1, Problem 4, "one common mistake was checking if (T[i], T[i + 1]) ∈ E for all i": a wrong algorithm, no matter how well written up. On Midterm 1, Problem 3 (updating an MST after an edge weight increases), "one common mistake is not explaining why every non-e edge is still in the MST": a correct algorithm whose correctness paragraph skipped half the claim. On Midterm 2, Problem 5, a plausible but wrong approach "received at most 2 points". Read together, these comments suggest how grading works: a wrong idea caps the score near 2 of 5, a right idea with a missing or hand-waved correctness argument loses one or two points, and a right idea with a running time slower than the target also loses points.
1.2 Pseudocode in the course idiom and calling algorithms by name
In plain words. The cover page asks for algorithms "in pseudocode similar to the examples given in lectures, notes, and problem sets". That means a short, indented, Python-like program in which plain English lines are allowed whenever a step is standard ("sort A by non-decreasing t", "e = lightest edge crossing S"). The biggest time-saver on the exam is calling an algorithm the course has already proved correct, by name, instead of rewriting it. The cover page lists exactly which algorithms may be called this way, and allows "a slightly modified version" as long as the modification is clearly described.
- Header line
ALG(inputs):, two-space indentation,for i = 2, ..., n:loops,for v in G[u]:to scan an adjacency list,=for both assignment and comparison,# commentson the right,returnlast. - Arrays are created as
d = [inf]*nord = [0] * (t+1) # starts at index 0; say so in a comment when an index starts at 0. - No hashing: a set of vertices is a binary array (
S = [0]*n; S[1] = 1means S = {1}), as the notes do for Prim's algorithm and Problem Set 1.1 does for "seen" elements. - Call by name with the course's spelling:
R = topological-ordering(G),d = BFS(G, s),d = Dijkstra(G', s0),d = Floyd-Warshall(G). Its correctness and running time may be assumed. - A modified call is fine if the modification is one clear sentence: "run Bellman-Ford until j = 10 and return the d-values at that time" (Practice Final, Problem 5).
- The trap: writing a long implementation of BFS or Dijkstra from scratch wastes time and invites bugs; writing a call to an algorithm that is not on the list (a heap, a hash map, "union-find") is not allowed without describing it.
The recipe
- Name the procedure and its inputs exactly as the problem names them:
ALG(G, s, t),ALG(A, B). - Initialise every array with its size and starting value, and every set as a binary array.
- Prefer one named call plus a short loop over a long hand-written procedure.
- Keep the indexing of the problem: A[1] is the first element; loops run
for i = 1, ..., n. - End with
returnof exactly what the problem asks for (a number, an array, a list of edges, True/False, or nothing).
A worked instance
Problem Set 1.1 asks for the repeated element of an array A of length n + 1 that contains every element of {1, 2, …, n}, one of them twice, in O(n) time. A natural Python answer is "keep a set of seen elements", which uses hashing. The official second solution replaces the set by a binary array, and the notes explain: "The array B acts as a hash table whose keys are elements in A, and B[k] = 1 indicates that the algorithm has already seen k in A."
ALG2(A):
B = [0]*n # array of length n, every element is 0
for i = 1, ..., n+1:
if B[A[i]] = 1:
return A[i]
B[A[i]] = 1
On A = [3, 1, 3, 2] (n = 3) the loop sets B[3] = 1, then B[1] = 1, then finds B[3] = 1 at i = 3 and returns 3. The same trick appears in Prim's algorithm: "creating S = {1} is equivalent to creating S = [0] * n and setting S[1] = 1, and adding v to S is equivalent to setting S[v] = 1."
The algorithms you may call by name
The Practice Final cover page lists the algorithms below, which "you may call … and assume that they have any properties (e.g., correctness, running time) mentioned in the lectures/notes". Every running time in the table is the one stated in the Running Time section of the course notes; when you call one of these, quote this bound in your running-time sentence.
| Algorithm | What it returns | Running time (notes) | Guide |
|---|---|---|---|
| Max-in-Array | the largest element of A | O(n) | Ch 2 |
| Two-Sum | indices (i, j), i < j, with A[i] + A[j] = t in a sorted array, or nothing | O(n) | Ch 2 |
| Binary-Search | an index k with A[k] = t in a sorted array, or nothing | O(log n) | Ch 2 |
| Selection-Sort | A sorted in increasing order | O(n²) | Ch 2 |
| Merge-Sort | A sorted in non-decreasing order | O(n log n) | Ch 2 |
| BFS | array d of distances (number of edges) from s; ∞ if unreachable | O(m + n) | Ch 3 |
| DFS | arrays pre and post (and so the DFS tree and edge classes) | O(m + n) | Ch 3 |
| Explore | explores every not-yet-explored vertex reachable from u (sets pre and post) | part of DFS's O(m + n) | Ch 3 |
| Find-Cycle | a directed cycle, or nothing | O(m + n) | Ch 3 |
| Topological-Sort | a topological ordering of a DAG | O(m + n) | Ch 3 |
| Prim | the MST (as a list F of edges) | O(mn) = O(m²) | Ch 4 |
| Kruskal | the MST | O(m log m) + m · O(n) = O(m²) | Ch 4 |
| Reverse-Delete | the MST | O(m log m) + m · O(m) = O(m²) | Ch 4 |
| Select-Intervals | a maximum list of compatible intervals | O(n log n) | Ch 4 |
| Fractional-Knapsack | array x of fractions, at most one not in {0, 1} | O(n log n) | Ch 4 |
| LIS | length of a longest increasing subsequence | O(n²) | Ch 5 |
| LPS | length of a longest palindromic subsequence | O(n²) | Ch 5 |
| Edit-Distance | edit distance from A (length m) to B (length n) | O(mn) | Ch 5 |
| Knapsack-DP | maximum value of a 0/1 knapsack with budget B | O(nB) | Ch 6 |
| DAG-DP | shortest-path distances from s in a DAG | O(m + n) | Ch 7 |
| Bellman-Ford | distances from s; no negative cycle | O(mn) | Ch 7 |
| Dijkstra | distances from s; all lengths non-negative | O(n²) | Ch 7 |
| Floyd-Warshall | n × n array of all-pairs distances; no negative cycle | O(n³) | Ch 7 |
| Ford-Fulkerson | a maximum s-t flow | O(mv), v = max flow value | Ch 8 |
| Minimum-st-Cut | a minimum s-t cut S (reachable from s in the last residual graph) | O(mv) | Ch 8 |
| Bipartite-Matching | a maximum matching of a bipartite graph | O(mn) | Ch 8 |
| Bipartite-VC | a minimum vertex cover of a bipartite graph | O(mn) | Ch 8 |
| Vertex-Cover approximation | a vertex cover of size at most 2 · OPT | polynomial | Ch 9 |
| Load-Balancing approximation | an assignment with makespan at most 2 · OPT (in fact (2 − 1/m) · OPT) | polynomial | Ch 9 |
| Metric k-Center approximation | k centers with maximum radius at most 2 · OPT | polynomial | Ch 9 |
| Maximum Cut approximation | a cut of weight at least OPT/2 (local search) | at most w(E) iterations | Ch 9 |
Two rows need a comment. The notes never give Explore its own bound, because Explore is the recursive half of DFS; a call Explore(G, u) visits only vertices reachable from u and scans each of their adjacency lists once, so it is safe to charge it O(m + n) (this is the guide's reading of DFS's analysis, not a line from the notes). For the approximation algorithms, the notes say "in this chapter, any polynomial running time is acceptable; an analysis is not even necessary", and they point out that the Maximum Cut local search terminates within w(E) iterations, which "is not actually polynomial because w(E) could be, say, 2ⁿ".
Check-in 1.1. A student writes the following to decide whether a directed graph has a vertex with no in-edges. Rewrite it in the course idiom (no hashing, indices from 1) and state its running time.
def f(G):
has_in = set()
for u in G:
for v in G[u]:
has_in.add(v)
return len(has_in) < len(G)
Answer
Replace the set by a binary array:ALG(G): / B = [0]*n / for u in V: / for v in G[u]: / B[v] = 1 / for u = 1, ..., n: / if B[u] = 0: return True / return False. Creating B and the last loop take O(n); the nested loops scan every adjacency list once, O(m + n); the total is O(m + n).1.3 Running-time analysis
In plain words. The running time of an algorithm is how many basic steps it takes in the worst case, as a function of the size of the input. The course does not count steps exactly; it keeps only the fastest-growing term and drops constants, which is what the O( ) notation means. For almost every algorithm in the course the analysis is one sentence: count the iterations of each loop, multiply by the time per iteration, and add up the pieces. For graphs, the one extra idea is that scanning every adjacency list once costs m in total, not n per vertex.
- The notes' definition: "The running 'time' of an algorithm is the worst-case number of 'primitive operations' it makes, in terms of the input length." Primitive operations are assignment, comparison, arithmetic, indexing into an array, calling another algorithm, and returning a value.
- To convert to O: "replace all coefficients with 1 … and put the largest term inside a capital O", so 4n² + 6n + 3 becomes O(n²).
- The default recipe from the notes: "count the number of loops the algorithm makes, determine how long each loop takes, and multiply the two values together."
- Graphs: Σu∈V out-deg(u) = m, so a loop over all vertices that scans each adjacency list costs O(m + n), not O(n²).
- While-loops: find a quantity that changes by a fixed amount each iteration (j − i in Two-Sum drops by 1; the length of A[i:j] in Binary-Search halves).
- Numbers in the input are not lengths: the notes state that the O(nB)-time Knapsack DP "is not a polynomial-time algorithm", and Ford-Fulkerson's O(mv) depends on the flow value v. Write such bounds exactly as the problem asks; the distinction matters only in the course's Chapter 7 (guide Chapter 10, not on the final).
The recipe
- List the steps of the algorithm in order: preprocessing (sorting, building a new graph, a named call), the main loop(s), the final scan.
- For each loop: (number of iterations) × (time per iteration). For a loop over u ∈ V with an inner loop over G[u], write O(out-deg(u)) per vertex and sum to O(m + n).
- For a named call, quote the table of Section 1.2 with the size of the input you pass it (a graph with 2n vertices and 3m edges is still O(n²) for Dijkstra).
- Add the pieces and keep the largest: O(n log n) + O(n) = O(n log n).
- Simplify with facts the course uses: a connected graph has m ≥ n − 1, so O(m + n) = O(m) and O(mn) = O(m²); every graph has m ≤ n², so O(m) = O(n²).
A worked instance
Problem Set 1.3: the input is (A, B), where A has m distinct positive integers, B has n distinct positive integers and m ≤ n; return their intersection in O(n log m) time. (Here m and n are array lengths, not graph sizes.) The official solution sorts A, then binary-searches A for each element of B. Its running time sentence is a model: "Sorting A takes O(m log m) time. The algorithm then makes n iterations, and each iteration takes O(log m) time. Thus, the total running time is O(m log m) + n · O(log m) = O(n log m)." The last step uses m ≤ n, so m log m ≤ n log m.
The course's standard counts are worth knowing by sight, because most exam answers reuse one of them.
| Loop structure | Count | Bound | Course example |
|---|---|---|---|
| one loop i = 2, …, n with O(1) body | n − 1 iterations × O(1) | O(n) | Max-in-Array, most 1-D DPs |
| while i < j, and j − i drops by 1 | at most n − 1 iterations | O(n) | Two-Sum, PS 1.2, PS 1.4 |
| while the range halves | length ≤ n/2k after k rounds | O(log n) | Binary-Search |
| loop i = 1..n, inner j = i+1..n | n rounds × O(n) | O(n²) | Selection-Sort, LIS |
| u ∈ V, then v ∈ G[u] | Σ (1 + out-deg(u)) = n + m | O(m + n) | BFS, DFS, DAG-DP |
| two recursive calls on halves + linear merge | T(n) = 2T(n/2) + O(n) | O(n log n) | Merge-Sort |
| table with n(B + 1) entries, O(1) each | entries × time per entry | O(nB) | Knapsack-DP |
| n − 1 rounds, each relaxing m edges | (n − 1) · m | O(mn) | Bellman-Ford |
Check-in 1.2. Give the running time of this procedure on a directed graph, step by step.
ALG(G):
c = [0]*n
for u in V:
for v in G[u]:
c[v] += 1
sort V by c # Merge-Sort
for u in V:
d = BFS(G, u)
Answer
Creating c: O(n). The nested loops scan every adjacency list once: O(m + n). Sorting n vertices: O(n log n). The last loop makes n calls to BFS at O(m + n) each: O(n(m + n)) = O(mn + n²). The largest term wins: O(mn + n²), which is O(mn) if G is connected.1.4 Correctness by loop invariant and induction
In plain words. When an algorithm builds its answer step by step, the cleanest proof names a statement that is true after every step and that, after the last step, says the answer is right. Such a statement is called a loop invariant, and proving it is a proof by induction: check it after the first step, then show that if it holds after one step it still holds after the next. The course uses this for Max-in-Array, Selection-Sort and Merge-Sort, and a closely related "the solution is still in the remaining range" argument for Two-Sum and Binary-Search. Search problems that may have no answer add a second ingredient: prove both that anything returned is valid and that an existing answer is never missed.
- An invariant is a precise claim about the variables after iteration i, for example "m = max(A[1:i])".
- Induction has a base case (the first iteration) and an inductive step (if the claim holds after iteration i − 1, it holds after iteration i).
- The last sentence applies the claim at the end of the loop to conclude that the returned value is correct.
- For recursive algorithms (Merge-Sort) the induction is on the input size: arrays of length 1 are sorted, and the recursive calls return sorted halves by the inductive hypothesis.
- Two directions for problems with a "return nothing" option: (1) if the algorithm returns X, X is a valid answer; (2) if a valid answer exists, the algorithm returns one. Two-Sum, Binary-Search, Find-Cycle and Midterm 1, Problem 4 are all proved this way.
- The trap: stating an invariant that is true but does not imply correctness at the end, or proving only direction (1).
The recipe
- Claim. "For all i ∈ {…}, at the end of iteration i, [precise statement]."
- Base case. Check the claim for the first iteration directly.
- Inductive step. Assume the claim at the end of iteration i − 1; show what iteration i does keeps it true.
- Conclusion. At the end of the last iteration the claim says the returned value is what the problem asks for.
A worked instance
The course Chapter 1 worksheet asks: "Formally explain why Max-in-Array is correct." Max-in-Array sets m = A[1], then for i = 2, …, n sets m = max(m, A[i]), and returns m. The official solution, which is the model for every invariant proof:
Correctness. "We claim that for all i ∈ {2, …, n}, at the end of iteration i, m = max(A[1:i]); this implies that the algorithm returns max(A[1:n]) = max(A). When i = 2, the claim is true because m = max(A[1], A[2]) = max(A[1:2]). For all i > 2, the claim is still true because at the beginning of iteration i, m = max(A[1:i−1]), so in iteration i, the algorithm sets m = max(A[1:i−1], A[i]) = max(A[1:i])."
The invariant can be watched on a fresh example, A = [3, 1, 4, 1, 5].
| Iteration i | A[i] | m at the end | max(A[1:i]) |
|---|---|---|---|
| start | A[1] = 3 | 3 | 3 |
| 2 | 1 | 3 | 3 |
| 3 | 4 | 4 | 4 |
| 4 | 1 | 4 | 4 |
| 5 | 5 | 5 | 5 |
Some cells worked out: at i = 3 the algorithm computes max(3, 4) = 4, and indeed the largest of 3, 1, 4 is 4; at i = 4 it computes max(4, 1) = 4, unchanged. The last two columns agree in every row, which is exactly the invariant, and the returned value is 5.
The two-directional form appears in the notes' proof for Two-Sum: "If the algorithm returns some (i, j), then i < j and A[i] + A[j] = t, so the algorithm is correct. Conversely, suppose the input (A, t) has at least one solution. We claim that at any point in the algorithm, there exists a solution in A[i:j]." Increasing i is safe because the old A[i] plus any A[j′] with j′ ≤ j is less than t (A is sorted), so the solution cannot use the old i. Selection-Sort's proof is the same shape as Max-in-Array's with the claim "after round i, A[1:i] contains the i smallest elements of A in sorted order", and Merge-Sort's is induction on n with the base case "any array of length 1 is sorted".
What the grader looks for
A claim precise enough to check (which variable, which iteration, which subarray), a base case, a step that uses the algorithm's actual line, and the final sentence that connects the claim to the returned value. For a design problem the invariant is often one sentence; Problem Set 1.4's official correctness paragraph is just "if A[i] ≤ A[j], then for this particular i, there is no better solution (i, j′) for any j′ < j. Thus, by incrementing i, we cannot miss the optimal solution."
Check-in 1.3. Run Max-in-Array on A = [4, 9, 2, 11, 7]: fill in m at the end of each iteration, then state the invariant for i = 4 in words.
| i | 2 | 3 | 4 | 5 |
|---|---|---|---|---|
| A[i] | 9 | 2 | 11 | 7 |
| m |
Answer
m = 9, 9, 11, 11 and the algorithm returns 11. At the end of iteration 4, m = max(A[1:4]) = max(4, 9, 2, 11) = 11.1.5 Correctness by exchange argument, cut property and cycle property
In plain words. A greedy algorithm makes one locally best choice after another and never reconsiders. To prove it optimal, the course takes any optimal solution and shows that it can be changed, one swap at a time, into the greedy solution without ever getting worse; this is an exchange argument. For minimum spanning trees the exchange is packaged once and for all into two lemmas, the cut property and the cycle property, which later proofs simply cite. When a greedy rule is wrong, the proof is replaced by a small counterexample.
- An exchange argument compares ALG with an optimal OPT, finds where they first differ, and swaps OPT's choice for ALG's to get OPT′ that is still feasible and no worse.
- Repeating the swap turns OPT into ALG, so ALG is optimal. The contradiction form ("if OPT ≠ ALG, OPT′ is strictly better, contradiction") is used for Max k-Sum and Practice Midterm 1, Problem 5.
- Cut property (notes): "For any cut S in G, the lightest edge crossing S is in the MST of G." Used for Prim, Kruskal and Problem Set 3.4.
- Cycle property (notes): "For any cycle C in G, the heaviest edge in C is not in the MST of G." Used for Reverse-Delete and Practice Final, Problem 6.
- Both properties assume distinct edge weights, so the MST is unique; they are proved by the exchange T′ = T + e − f.
- The trap: a greedy rule that sounds right but is not. The Chapter 0 lecture showed three wrong rules for intervals before the right one.
The recipe
- Let ALG be the greedy solution and OPT an optimal solution, both listed in the greedy order. If they agree everywhere, ALG is optimal.
- Let i be the first position where ALG[i] ≠ OPT[i]. Say why the greedy choice ALG[i] is at least as good at position i (ends earlier, is larger, has a higher ratio).
- Build OPT′ = OPT with OPT[i] replaced by ALG[i]. Show OPT′ is feasible and its value is no worse than OPT's.
- OPT′ is optimal and agrees with ALG on one more position; repeat until it equals ALG.
MST version. To show an edge is in the MST, exhibit a cut S that it is the lightest edge crossing, then cite the cut property. To show an edge is not in the MST, exhibit a cycle in which it is the heaviest edge, then cite the cycle property.
A worked instance
Midterm 1, Problem 5: the input is an array A of n intervals [s, t]; return a list P of numbers such that every interval contains at least one number of P and P is as short as possible, in O(n log n) time. Example: for A = [[1, 10], [4, 5], [2, 3]], one optimal solution is P = [5, 2.5]. The official solution:
Algorithm. "The algorithm sorts A by non-decreasing t and iterates; whenever it encounters an interval [s, t] that does not contain the rightmost point in P, it adds t to P."
ALG(A):
sort A by non-decreasing t
P = [empty list], last = -infinity
for [s, t] in A:
if last < s:
append t to P
last = t
return P
Correctness. "Suppose OPT ≠ ALG and the earliest difference occurs when ALG handles [s, t] by picking t while OPT picks some t* < t. Let OPT′ be OPT except we replace t* with t. Then OPT′ is feasible because every later interval [a, b] satisfies t ≤ b, so if [a, b] contains t*, it must also contain t. Since OPT′ agrees with ALG for one additional point than OPT, we can repeat this process to conclude that ALG is optimal (similar to Selecting Compatible Intervals)."
Running time. "Sorting A takes O(n log n) time, and the loop through A takes O(n) time, so the total running time is O(n log n)."
On the example, sorting by end gives [2, 3], [4, 5], [1, 10]. The first interval adds 3 (last = 3); [4, 5] has 3 < 4, so 5 is added (last = 5); [1, 10] contains 5, so nothing is added. ALG returns P = [3, 5], two points, the same size as the example's [5, 2.5]. The four recipe steps are all present in the correctness paragraph: first difference, the greedy point t is at least as far right, the swapped OPT′ is feasible and the same size, repeat.
For the MST version, the official solution of Problem Set 3.4 is the model. After the weight of a tree edge e increases, every other tree edge f stays in the MST because "if we remove f from T, we obtain a cut S, and f is the only edge in T crossing S. By the cut property, f is the lightest edge crossing S, and this holds even if we increase w(e)". This is the sentence whose absence cost points on Midterm 1.
The counterexample side comes from the Chapter 0 worksheet. "Keep picking the shortest interval" fails on {[1, 10], [9, 12], [11, 20]}: the shortest interval [9, 12] conflicts with both others, so the rule ends with one interval while [1, 10] and [11, 20] give two.
What the grader looks for
The first difference named explicitly, the reason the greedy choice is no worse at that point (the one place where the greedy rule is used), a sentence saying OPT′ is feasible, a sentence saying OPT′ is no worse, and "repeat". For MST arguments, the cut or cycle named concretely ("removing e from T creates a cut S") before the property is cited.
Check-in 1.4. Max k-Sum: return k distinct elements of A with the largest sum; the greedy algorithm sorts A in decreasing order and takes the first k. For A = [7, 2, 9, 4] and k = 2, a student proposes OPT = {7, 4}. Carry out one exchange step as the notes do and say what it shows.
Answer
Sorted, A = [9, 7, 4, 2] and ALG = {9, 7}. OPT excludes 9 (in the top k) and includes 4 (outside it). OPT′ = OPT − 4 + 9 = {7, 9} has sum 16 > 11, so OPT was not optimal; in general the exchange never lowers the sum, so the greedy top-k is optimal.1.6 Correctness of a dynamic program
In plain words. A dynamic program solves a problem by first solving all of its smaller versions, called subproblems, and storing their answers in a table. The course writes every DP in four labelled parts: Subproblems, Recurrence, Algorithm, Running time. The correctness proof lives inside the Recurrence part: it is the sentence that says why the formula is right, by listing every case the optimal solution of a subproblem can fall into and checking that the formula scores each case correctly. If the cases are exhaustive and each is scored correctly, the recurrence holds, and the table is correct by induction.
- The notes' format: "Subproblems: Which subproblems will we solve? What will we return? Recurrence: How can we solve each subproblem using solutions to smaller subproblems? What are the base cases? Why does the recurrence hold? (The answer to the last question suffices as a proof that the algorithm is correct.)"
- The subproblem is a sentence: "For all i ∈ {1, …, n}, let OPT[i] denote … given A[1:i]", plus "so we will return OPT[n]" (or max(OPT), or OPT[1]).
- The recurrence lists exhaustive cases: the last element is used or not; the path arrives from some in-neighbour u; the list ends on some A[j].
- The algorithm fills an array d in an order where every entry the recurrence reads is already filled: left to right for prefixes, right to left for suffixes, topological order for DAGs.
- Running time: "typically the number of subproblems multiplied by the time per subproblem."
- The trap: a vague subproblem ("the best so far"), missing base cases, or returning d[n] when the answer is max(d).
The recipe
- Subproblems. Define OPT[i] (or OPT[i][j]) in one sentence, naming the smaller input, and say which entry is returned.
- Recurrence. State the base case(s) and the formula; then one or two sentences: "The recurrence holds because the optimal solution for … either … or …; in the first case its value is …, in the second …."
- Algorithm. Pseudocode that is the recurrence with OPT replaced by d, filled in a valid order, ending with the return.
- Running time. Number of subproblems × time per subproblem, plus any preprocessing.
A worked instance
Midterm 2, Problem 4: the input is (A, t), where A is an array of n distinct positive integers and t is a positive integer; return the number of lists whose sum is exactly t, where every number in each list must be in A, in O(nt) time. Example: for A = [1, 3, 2] and t = 4 the answer is 7: [1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [2, 1, 1], [1, 3], [3, 1], [2, 2]. The official solution:
Subproblems. "For all i ∈ {0, 1, …, t}, let OPT[i] denote the answer given the input (A, i); we'll return OPT[t]."
Recurrence. "The base case is OPT[0] = 1 since the only list whose sum is 0 is the empty list. For all i ∈ {1, …, t}, we have OPT[i] = Σj OPT[i − A[j]], where the sum is over every index j such that i − A[j] ≥ 0. … The recurrence holds because every list whose sum is i must end on some element A[j], so we can calculate OPT[i] by summing over all of the possible A[j]."
ALG(A, t):
d = [0] * (t+1) # start at index 0
d[0] = 1
for i = 1, ..., t:
for j = 1, ..., n:
if i - A[j] >= 0:
d[i] += d[i - A[j]]
return d[t]
Running time. "The algorithm makes t iterations, and each takes O(n) time, so the total running time is O(nt)."
| i | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| terms | base | d[0] | d[1] + d[0] | d[2] + d[0] + d[1] | d[3] + d[1] + d[2] |
| d[i] | 1 | 1 | 2 | 4 | 7 |
Some cells worked out: for i = 2 the terms are A[1] = 1 (giving d[1]) and A[3] = 2 (giving d[0]); A[2] = 3 is too big, so d[2] = 1 + 1 = 2, the lists [1, 1] and [2]. For i = 4 all three elements fit: d[3] + d[1] + d[2] = 4 + 1 + 2 = 7, matching the seven lists in the problem.
What the grader looks for
A subproblem sentence precise enough that the recurrence can be checked against it, base cases that are actually correct (OPT[0] = 1, not 0, because the empty list counts), the "why it holds" sentence naming the exhaustive cases, an evaluation order that respects the recurrence, and the count. Chapter 5 and Chapter 6 apply this recipe to every DP of the course.
Check-in 1.5. Problem Set 4.5 (the stock problem) uses d[j] = A[j] − min(A[1:j−1]) for j = 2, …, n and returns max(d). Fill in d for A = [5, 3, 6, 1, 4] and give the returned value.
| j | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| A[j] | 5 | 3 | 6 | 1 | 4 |
| d[j] | −∞ |
Answer
d = [−∞, −2, 3, −2, 3]: the minimum before day 2 is 5, before day 3 it is 3, before day 4 it is 3, before day 5 it is 1. The algorithm returns max(d) = 3 (buy at 3, sell at 6; or buy at 1, sell at 4).1.7 Solving a problem by reduction
In plain words. Many exam problems are a known problem in disguise. Instead of designing a new algorithm, you change the input into an input for a problem the course already solved, call that algorithm by name, and translate its answer back. The course calls this a reduction: "an algorithm that solves A using an algorithm that solves B". It is the dominant pattern of Problem Sets 5 and 6, and the correctness proof is always the same: show that solutions of the new input correspond exactly to solutions of the original, with the same value.
- Three steps: build a new input (copies of the graph, the reverse graph, a split vertex, a flow network), call a known algorithm on it, translate the output back.
- Correctness is a correspondence in both directions: every solution of the original gives a solution of the new input with the same value, and conversely.
- Running time: the cost of building the new input plus the known algorithm's bound on the new size (2n vertices, 3m edges, n + 2 vertices).
- Common builds in the course: two copies of G for a parity or "one free edge" condition (Problem Set 5.3, Midterm 2, Problem 5), splitting each vertex u into uin → uout to carry a vertex capacity (Problem Set 6.3), the reverse graph GR for distances to a vertex, and s → L → R → t networks for matching (Bipartite-Matching itself).
- A "slight modification" of a named algorithm is also a reduction: Practice Final, Problem 5 runs Bellman-Ford for only 10 rounds.
- The trap: a correspondence argued in one direction only, or forgetting that the new graph's size enters the running time.
The recipe
- Build. Describe the new input in one sentence and in pseudocode (vertices, edges, lengths or capacities).
- Call. One line calling the known algorithm by name; check its conditions (non-negative lengths for Dijkstra, a DAG for DAG-DP).
- Translate. Return the entry or object that answers the original question (d[t0], the flow on original edges).
- Correctness. "Every [original object] corresponds to a [new object] of the same value, and conversely; so the optimum of the new instance is the optimum of the original."
- Running time. Construction O(m + n) plus the called algorithm on the new size.
A worked instance
Problem Set 5.3: the input is (G, s, t), a directed graph with lengths ℓ(e) ≥ 0; a walk is even if it contains an even number of edges; return the length of the shortest even walk from s to t (or ∞), in O(n²) time. The official solution:
Algorithm. "The idea is that we construct a new graph G′, where a path in G′ represents an even walk in G."
ALG(G, s, t):
G' = graph with no vertices or edges
for u in V(G):
add two vertices u0, u1 to G'
for (u,v) in E(G):
add edges (u0, v1) and (u1, v0) to G', each has length l(u,v)
d = Dijkstra(G', s0)
return d[t0]
Correctness. "We think of G′ as two copies of G: the '0' copy and the '1' copy. Edges in G′ alternate between the two copies, and we start at s0, so every s0-t0 path in G′ corresponds to an even s-t walk in G of the same length. Conversely, every even s-t walk in G corresponds to an s0-t0 path in G′ of the same length."
Running time. "Constructing G′ takes O(m + n) time, and Dijkstra's takes O(n²) time (since G′ has 2n vertices), so the total running time is O(n²)."
On the graph below (edge lengths s→t 2, s→a 5, a→t 1, t→x 1, x→y 1, y→t 1), the direct edge s→t is a walk with one edge (odd), the walk s, a, t has 2 edges and length 6, and the highlighted walk s, t, x, y, t has 4 edges and length 2 + 1 + 1 + 1 = 5, which is what Dijkstra returns as d[t0] in G′. Chapter 7 draws G′ and works the whole Problem Set 5.
What the grader looks for
A clear description of the new input (the grader must be able to draw it), the named call with its conditions satisfied, the translation back, both directions of the correspondence, and the running time on the new size. The official solutions to Problem Set 5.2 (remove the negative edge, call Dijkstra twice, take the better of "avoid e" and "use e") and 5.4 (Floyd-Warshall, then the smallest d[u][v] + d[v][u]) are the same recipe with a case split instead of a new graph.
Check-in 1.6. The input is (G, s, u, t), a directed graph with non-negative lengths. Describe an O(n²)-time algorithm that returns the length of a shortest walk from s to t that passes through u, with a one-sentence correctness argument.
Answer
d1 = Dijkstra(G, s); d2 = Dijkstra(G, u); return d1[u] + d2[t]. Every s-t walk through u splits at u into an s-u walk followed by a u-t walk, and the shortest choice for each part is a shortest path, so the minimum is d1[u] + d2[t]; conversely any such pair of paths joins into a walk through u. Two Dijkstra calls: O(n²).1.8 Proving an approximation ratio, and writing a counterexample
In plain words. For some problems no fast exact algorithm is known, so the course settles for a fast algorithm whose answer is guaranteed to be within a fixed factor of the best possible. Proving such a guarantee never requires knowing OPT exactly; it requires a bound on OPT that is easy to compare with what the algorithm does. When the question asks "Is this an α-approximation? Prove it, or give a counterexample", the answer starts with Yes or No and then either gives that proof or gives one small instance on which the algorithm is worse than the factor allows.
- Definition (notes): "An α-approximation algorithm is a polynomial-time algorithm that, for every instance of the problem, returns a solution whose value is within a factor of α times the optimal value of that instance."
- Minimization, α ≥ 1: OPT(X) ≤ ALG(X) ≤ α · OPT(X). Maximization, α ≤ 1: OPT(X) ≥ ALG(X) ≥ α · OPT(X).
- A proof needs feasibility of ALG's output and a bound on OPT (a lower bound for minimization, an upper bound for maximization) that ALG can be compared with.
- Course bounds on OPT: |OPT| ≥ |M| for any matching M (Vertex Cover); T* ≥ (Σ ℓ[j])/m and T* ≥ ℓ[k] (Load Balancing); OPT ≤ w(E) (Maximum Cut); |M*| ≤ 2|M| by assigning each optimal edge to a chosen edge (Problem Set 8.1).
- A counterexample is one specific instance with ALG's value, OPT's value and the ratio, which must be strictly worse than α.
- Polynomial time is enough in this chapter: "any polynomial running time is acceptable; an analysis is not even necessary."
The recipe
- Feasibility. One sentence: the output is a valid solution (a cover, a matching, an assignment).
- Bound on OPT. A structural fact any solution must satisfy: "each vertex in OPT covers at most one edge in M, so |OPT| ≥ |M|".
- Bound on ALG. Express ALG's value in the same terms: "|S| = 2 · |M|".
- Conclusion. Chain them: |S| = 2|M| ≤ 2|OPT|.
Writing a counterexample. (1) First word "No". (2) The instance, fully explicit and small. (3) ALG's run on it with the tie-breaking rule, and ALG's value. (4) OPT's value, with a solution that achieves it. (5) The ratio, compared with α.
A worked instance
Problem Set 8.1 (and Practice Final, Problem 4): the input is an undirected connected graph G; the goal is a maximum matching (a set of edges no two of which share an endpoint). The algorithm repeatedly adds any remaining edge e to F and removes e and every edge sharing an endpoint with it. Prove that this is a 1/2-approximation. The official solution:
Bound on OPT via ALG. "Let M be the output of the algorithm and M* be a maximum matching; we want to show |M*| ≤ 2 · |M|. For each e* ∈ M*, assign e* to any edge in M that shares at least one endpoint with e*. (This assignment is well-defined, because if some e* does not share an endpoint with any edge in M, then M ∪ {e*} would be a matching, so the algorithm should not have returned M.)"
Conclusion. "Every e ∈ M gets assigned at most two edges in M* because e shares an endpoint with at most two edges in M*. Thus, |M*| ≤ 2 · |M|, as desired." Feasibility (M is a matching) holds because every chosen edge removes all edges touching it.
For the counterexample side, Problem Set 8.2 builds the instance that makes the greedy Load Balancing algorithm (assign each job, in order, to the machine with the smallest current load) as bad as possible: m(m − 1) jobs of length 1 followed by one job of length m. With m = 3 the jobs are [1, 1, 1, 1, 1, 1, 3].
| Machine 1 | Machine 2 | Machine 3 | Makespan | |
|---|---|---|---|---|
| ALG after the six 1s | 2 | 2 | 2 | 2 |
| ALG after the 3 | 5 | 2 | 2 | 5 |
| OPT | 3 (the long job) | 1 + 1 + 1 | 1 + 1 + 1 | 3 |
The ratio is 5/3 = 2 − 1/3, matching the notes' improved bound of 2 − 1/m, so the analysis cannot be improved. (With ties broken toward the smallest label, the 3 goes to machine 1.)
Here is a counterexample written in full, for a question invented in the course's style. Is the following a 2-approximation for Vertex Cover: while G has an edge {u, v} with u < v, add u to S and remove u from G? No. Take the star with center 5 and leaves 1, 2, 3, 4. The first edge is {1, 5}, so ALG adds 1; then {2, 5} adds 2, and so on: ALG = {1, 2, 3, 4} (shaded below), of size 4. OPT = {5} covers every edge, of size 1. The ratio is 4/1 = 4 > 2, so the algorithm is not a 2-approximation.
What the grader looks for
For a proof: the named bound on OPT, ALG's value written in the same quantity, and the inequality chain that ends with the ratio. For a counterexample: "No" as the first word (the Practice Final insists: "The first word of your answer should be 'Yes' or 'No'"), an instance specific enough to run, ALG's actual output under the stated tie-breaking, a better solution that shows OPT, and a ratio that is strictly worse than α.
Check-in 1.7. Run the greedy Load Balancing algorithm on ℓ = [2, 3, 4, 1] with m = 2 machines (ties to the smaller machine label). Fill in the machine each job goes to, then give ALG's makespan, OPT's makespan, and check the bound ALG ≤ 2 · OPT.
| job | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| ℓ | 2 | 3 | 4 | 1 |
| machine |
Answer
Machines 1, 2, 1, 2; the loads after each job are (2, 0), (2, 3), (6, 3), (6, 4). ALG = 6. OPT = 5 with {2, 3} and {4, 1}. 6 ≤ 2 · 5 = 10, as guaranteed (the ratio is 6/5).1.9 One-point questions and True/False
In plain words. Problems 1 and 2 are ten one-point parts that say "Do not explain your answers. (1p each, no partial credit)". Each part asks you to run an algorithm from the notes by hand on a tiny input and report a final value or array, or to decide whether a statement is True or False. Because nothing but the answer is read, the answer must be exactly in the requested format, and the only protection against an arithmetic slip is a quick independent check.
- Run the algorithm exactly as the notes write it, not a variant you prefer: the "O(n²)-time DP for LIS" means the notes' d array, "the 2-approximation algorithm for Load Balancing" means jobs in the given order.
- Formats: arrays from A[1] to A[n] in square brackets ([1, 1, 2, 3, 2, 3]); undirected edges as {1, 3}, directed edges as (4, 3); "none" when a list is empty; a single integer when asked for "just an integer".
- Break ties the way the question says; Practice Final 1(b) says "As usual, break ties in favor of the vertex with the smallest label", and this guide uses the same rule for Prim's choice and for which machine gets a job.
- Check each answer a second way: a max flow against a cut of the same capacity, a DP's last entry against a solution you can see, a makespan against the average load.
- True/False about approximation ratios: a minimization α-approximation is also a β-approximation for every β ≥ α; a maximization α-approximation is also a β-approximation for every β ≤ α.
The recipe
- Identify the algorithm and the exact array or value asked for ("the last row of d", "post-values starting with post[1]").
- Write the trace small in the margin of the exam page (only the box is graded).
- Check the answer by a second method or a sanity bound.
- Copy only the final answer into the box, in the requested format.
A worked instance
Problems 1 and 2 of the Practice Final, with their official answers and the check that confirms each one. Parts (a) to (c) use the graph below (directed, with capacities, s = 1, t = 4; for Prim the edges are treated as undirected with these weights).
| Part | Question | Answer | How to check |
|---|---|---|---|
| 1(a) | max s-t flow value | 7 | flow 6 on 1→2→4 and 1 on 1→3→4; the cut {1, 3} has capacity 6 + 1 = 7 |
| 1(b) | DFS post-values from 1 | [8, 7, 6, 5] | the DFS goes 1, 2, 3, 4 in one chain, so posts finish 4, 3, 2, 1 at times 5, 6, 7, 8 |
| 1(c) | Prim's edges in order from 1 | {1, 3}, {3, 4}, {2, 3} | 3 edges for 4 vertices; total weight 2 + 1 + 3 = 6 |
| 1(d) | LIS d for [5, 1, 7, 8, 2, 3] | [1, 1, 2, 3, 2, 3] | max(d) = 3, and 5, 7, 8 (or 1, 2, 3) is increasing of length 3 |
| 1(e) | Knapsack last row, v = [3, 4, 2], w = [2, 2, 1], B = 4 | [0, 2, 4, 6, 7] | the last entry 7 is items 1 and 2 (weight 4) |
| 2(a) | Fractional Knapsack x, v = [3, 4, 5], w = [2, 2, 1], B = 4 | [0.5, 1, 1] | ratios 1.5, 2, 5; total weight 1 + 2 + 1 = 4 = B |
| 2(b) | Edit Distance abbc → babc | 2 | insert b at the front (babbc), then delete one of the two adjacent b's |
| 2(c) | greedy makespan, [3, 1, 2, 3], m = 3 | 4 | loads 3, 1, 2, then the last 3 goes to the load-1 machine |
| 2(d) | a 2-approx for Vertex Cover is a 3-approx | True | ALG ≤ 2 · OPT ≤ 3 · OPT |
| 2(e) | a 1/2-approx for Max Cut is a 1/3-approx | True | ALG ≥ OPT/2 ≥ OPT/3 |
The solution figure shows Prim's three edges from 1(c) highlighted.
Homework 8 asked the same ratio facts as numbers. If a 2-approximation for Vertex Cover runs on a graph whose optimal cover has size 30, the largest possible output size is 60; if it returns a cover of size 30, the smallest possible optimum is 15, because 30 ≤ 2 · |S*|. The rule "a minimization α-approximation is a β-approximation for β ≥ α" gives True for "a 2-approximation for Vertex Cover is also a 3-approximation".
Check-in 1.8. (a) Run the two-pointer Two-Sum algorithm on A = [1, 4, 6, 9], t = 12: list the pairs (i, j) it checks and what it returns. (b) True or False: a 1/2-approximation algorithm for Maximum Cut is also a 2/3-approximation algorithm for Maximum Cut.
Answer
(a) (1, 4): 1 + 9 = 10 < 12, so i = 2; (2, 4): 4 + 9 = 13 > 12, so j = 3; (2, 3): 4 + 6 = 10 < 12, so i = 3 = j and the loop stops: it returns nothing (indeed no two distinct elements sum to 12). (b) False: ALG ≥ OPT/2 does not imply ALG ≥ 2 · OPT/3, since 2/3 > 1/2.Before moving on
- I can name the three parts of a Problem 3–8 answer, the DP variant and the approximation variant, and the five cover-page rules.
- I can write pseudocode in the course idiom without hashing, and I know which algorithms I may call by name, with their running times and conditions.
- I can count a running time with loops, adjacency lists (Σ out-deg = m) and named calls, and simplify it to the target.
- I can write a loop-invariant proof, a two-directional proof and an exchange argument, and cite the cut and cycle properties correctly.
- I can write a DP's "why the recurrence holds" sentence and a reduction's two-way correspondence.
- I can prove an approximation ratio from a bound on OPT, and write a counterexample that starts with "No" and has a ratio strictly worse than α.
Exercises
Solution
The algorithm is the official one, but the correctness paragraph proves only that the new edge belongs to the new MST. It never explains why the other n − 2 edges of T are still in the MST after the weight change, which the official solution calls the common mistake. The fix: "Every edge f ∈ T other than e is still in the MST: removing f from T gives a cut S that f is the only tree edge crossing, so f is the lightest edge crossing S by the cut property, and increasing w(e) does not change that. The algorithm then removes e, and no tree edge crosses the resulting cut, so by the cut property the lightest edge crossing it is in the new MST."Solution
Algorithm. Return a standard MST of G: ALG(G): return Prim(G).
Correctness. Let T be the MST, e its heaviest edge, T* an optimal solution for the new problem and e* the heaviest edge of T*. We claim w(e) ≤ w(e*). For contradiction suppose w(e) > w(e*). Then every edge of T* is lighter than e. Inserting e into T* creates a cycle C, and e is the heaviest edge of C, so by the cycle property e is not in the MST, contradicting e ∈ T. So the MST's heaviest edge is as light as possible.
Running time. Prim's algorithm runs in O(mn) = O(m²) time (Kruskal and Reverse-Delete also run in O(m²)).
Solution
Sorting E takes O(m log m). Then there are m iterations; each checks whether F + e is acyclic by running BFS on (V, F), which has at most n − 1 edges, so O(n) per check. Total: O(m log m) + m · O(n) = O(mn). The graph is connected, so n ≤ m + 1 and O(mn) = O(m²). The sorting term is also within O(m²), because log m ≤ m.Solution
(2, 4). (1, 5): 1 + 11 = 12 > 9, so j = 4. (1, 4): 1 + 7 = 8 < 9, so i = 2. (2, 4): 2 + 7 = 9, return (2, 4).Solution
[1, 0.25, 1]. The ratios v/w are 2, 1, 3, so the order is item 3, item 1, item 2. Item 3 fits whole (weight 1, remaining capacity 4), item 1 fits whole (weight 3, remaining 1), and item 2 gets 1/4 of its weight 4. Total value 3 + 6 + 1 = 10.Solution
ALG: job 1 → machine 1 (2, 0); job 2 → machine 2 (2, 2); job 3 → machine 1 by the tie rule (5, 2); job 4 → machine 2 (5, 3); job 5 → machine 2 (5, 7). Makespan 7. The total length is 12, so OPT ≥ 6, and {2, 4} | {2, 3, 1} achieves 6: OPT = 6. Check: 7 ≤ 2 · 6.Solution
The ratio in the student's instance is 2/1 = 2, which is allowed: a 2-approximation only promises ALG ≤ 2 · OPT, so this instance does not refute it. A correct answer: No. Take m = 3 machines and ℓ = [1, 1, 1]. ALG puts all three jobs on machine 1, makespan 3. OPT puts one job on each machine, makespan 1. The ratio is 3 > 2, so the algorithm is not a 2-approximation (in general its ratio can be as large as m).Solution
(a) False. The notes state that "the O(nB)-time DP algorithm for 0/1 Knapsack is not a polynomial-time algorithm": B is a number in the input, not a length. (b) True: ALG ≥ OPT/2 = 5. (c) False. Dijkstra requires all lengths to be non-negative; with negative lengths but no negative cycle use Bellman-Ford (O(mn)) or Floyd-Warshall (O(n³)). (d) True: a connected graph has m ≥ n − 1, so n ≤ m + 1; Problem Set 3.4 uses exactly this step.Course Ch. 1 · Aug 20–252. Array algorithms
Course Chapter 1, taught in the first two lectures (Thursday, August 20 and Tuesday, August 25), introduces five short algorithms on arrays: Max in Array, Two Sum, Binary Search, Selection Sort and Merge Sort. Each is easy on its own. Their real job in the course is to set up the template that every later chapter uses: the lecture's first page reads "Template for class: Problem (input, goal, target running time). Solution: (1) Algorithm (ALG), (2) Correctness (explanation), (3) Running time." The same two lectures also introduce the three ideas you will reuse on the final: counting running time as (number of iterations) × (time per iteration), proving correctness by induction over the loop, and the two-pointer technique that turns an O(n²) search over all pairs into an O(n) scan. On the final, this chapter feeds the one-point hand traces of Problems 1 and 2 (a Two-Sum return value, a Binary-Search trace) and any Problem 3–8 whose target is O(n) on a sorted array or O(n log n) on an unsorted one. Every algorithm in this chapter may be called by name on the exam. Every array algorithm in this course is a loop (or a recursion) plus a one-line reason why the loop never throws away the answer.
- "Unless stated otherwise, every array has length n and its indices range from 1 through n." The lecture adds, in red, "do not use 'range'": write loops as
for i = 2, ..., n:. - A[i:j] means the subarray [A[i], …, A[j]], both ends included. So A[10:15] has six elements.
- Pseudocode is in the course's idiom ("English → pseudocode → Python/Java → assembly → machine code → electrons", and the course works at the pseudocode level). No hashing: when you need to remember which values you have seen, use an array
B = [0]*nand set B[k] = 1. - "Correct" means, in the lecture's words, "for all input X: ALG(X) returns the correct output".
2.1 Max in Array, and how running time is counted
In plain words. To find the largest number in a list, walk through it once and remember the biggest value seen so far. When you reach the end, the value you remember is the largest of all. The course uses this tiny problem to show how running time is counted and how a loop is proved correct. Both habits carry over to every later algorithm.
- Input: an array A of n distinct positive integers. Output: the largest integer in A. Target: O(n).
- Idea: keep a running maximum m, starting at A[1], and update m = max(m, A[i]) for i = 2, …, n.
- Invariant (the worksheet's claim): at the end of iteration i, m = max(A[1:i]).
- Running time: n − 1 iterations, O(1) each, so O(n).
- Running time in general is the worst-case number of primitive operations, written in Big-O: set every coefficient to 1 and keep the largest term.
- Trap: proving correctness by "it is obvious". The worksheet asks for the formal induction, and the exam grades the claim, the base case and the step.
Problem
The notes state it as: "The input is an array A of n distinct, positive integers. Our goal is to return the largest integer in A. Describe an O(n)-time algorithm for this problem, prove that it's correct, and analyze its running time." For example, on A = [3, 8, 6, 12, 10, 4] the answer is 12.
Algorithm
Set m to the first element. Then scan the rest of the array from i = 2 through i = n; in each iteration replace m by the larger of m and A[i]. After the loop, return m. The notes write it exactly like this:
Max-in-Array(A):
m = A[1]
for i = 2, ..., n:
m = max(m, A[i])
return m
The notes give no example array, so here is a trace on A = [3, 8, 6, 12, 10, 4]; the row "m after" is the value of m at the end of each iteration.
| i | (start) | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| A[i] | A[1] = 3 | 8 | 6 | 12 | 10 | 4 |
| m after | 3 | 8 | 8 | 12 | 12 | 12 |
Some cells worked out: at i = 2, m = max(3, 8) = 8; at i = 3, m = max(8, 6) = 8 (no change); at i = 4, m = max(8, 12) = 12, and nothing later is bigger, so the algorithm returns 12. Notice that every "m after" entry is the maximum of the prefix A[1:i], which is exactly the invariant.
Correctness
The notes say the algorithm "is intuitively correct, but we can also be more formal", and the Day 1 worksheet asks for the formal version. The technique is induction on the loop (a loop invariant). The lecture writes it in green as follows.
- Claim. For all i ∈ {2, …, n}, at the end of iteration i, m = max(A[1:i]). This suffices, because when i = n the claim says m = max(A[1:n]) = max(A), and that is what is returned.
- Base case, i = 2. In iteration 2 the algorithm sets m = max(A[1], A[2]) = max(A[1:2]).
- Inductive step, i ≥ 3. By the inductive hypothesis, at the beginning of iteration i, m = max(A[1:i−1]). In iteration i the algorithm sets m = max(m, A[i]) = max(max(A[1:i−1]), A[i]) = max(A[1:i]), as desired.
The lecture then shows a second, recursive version of the same algorithm, proved by induction on the length n instead of on the loop:
ALG(A): # recursive version from the 08-20 lecture
n = len(A)
if n = 1: return A[1]
m = ALG(A[1:n-1])
return max(m, A[n])
Claim: for all n ≥ 1, ALG is correct on all inputs of length n. Base case n = 1: the only element is the maximum. Inductive step n ≥ 2: the inductive hypothesis says ALG is correct on all inputs of length n − 1, so m = max(A[1:n−1]), and therefore ALG returns max(max(A[1:n−1]), A[n]) = max(A). The two proofs have the same shape: a claim indexed by a number, a base case, and a step that assumes the claim for the previous number.
Running time
The notes define the running "time" as "the worst-case number of 'primitive operations' it makes, in terms of the input length." The lecture lists five kinds of primitive operation (each "≈ 1 line of assembly"): (1) assignment, x = 1; (2) comparison, if x > y; (3) arithmetic, x + y; (4) indexing, A[i]; (5) calling another algorithm or returning a value.
The lecture counts Max-in-Array written with an if-statement (if A[i] > m: m = A[i]): the first line costs 2 (index and assign), the for-loop line at most 2n, the loop body at most 4n, the return 1, for a total of 2 + 2n + 4n + 1 = 6n + 3. A "more careful" count gives 2 + (n − 1) · 4 + 1 = 4n − 1. Either way the answer in Big-O is the same, which is the point of Big-O.
"To convert an expression like 4n² + 6n + 3 into asymptotic notation, we replace all coefficients with 1 to obtain n² + n + 1, and we put the largest term inside a capital O, so our final result is O(n²)." The lecture's examples: 7n³ + 9n² + 5n + 12 → n³ + n² + n + 1 → O(n³); 6n + 3 → n + 1 → O(n); 12 → O(1), "constant time". The growth order written on the 08-25 board: log n < n0.0001 < n0.1 < n0.5 < n < n².
"For almost every ALG in 550: RT = (# iterations) × (time per iteration)." For Max-in-Array: at most n iterations, each O(1), total n · O(1) = O(n).
Check-in 2.1. Run Max-in-Array on A = [5, 9, 2, 11, 7]: write m at the end of each iteration and the returned value.
| i | 2 | 3 | 4 | 5 |
|---|---|---|---|---|
| A[i] | 9 | 2 | 11 | 7 |
| m after |
Answer
m after iterations 2, 3, 4, 5 is 9, 9, 11, 11; the algorithm returns 11. Each entry equals max(A[1:i]), as the invariant says.2.2 Two Sum: the two-pointer technique
In plain words. Given a sorted list and a target, find two entries that add up to the target. Put one finger on the smallest entry and one on the largest, and add them. If the total is too small, the left finger moves right to a bigger number; if it is too large, the right finger moves left to a smaller number. Because each step moves one finger, the search ends after about n steps instead of checking all pairs.
- Input: (A, t), A an array of n distinct integers sorted in increasing order, t an integer. Output: indices (i, j) with i < j and A[i] + A[j] = t, or nothing. Target: O(n).
- Brute force over all pairs is O(n²); sortedness is what lets one pointer move per step.
- Rule: start at (1, n); if A[i] + A[j] = t return (i, j); if the sum is less than t, i += 1; otherwise j −= 1.
- Invariant: if a solution exists, one lies inside A[i:j] at every moment.
- Running time: j − i starts at n − 1, drops by 1 per iteration and cannot go below 0, so at most n iterations of O(1): O(n).
- Correctness has two directions: a returned pair is a solution, and if a solution exists, something is returned.
- Trap: answering with values instead of indices, or with 0-based indices. The answer is a pair of 1-based indices.
Problem
From the notes: "The input is (A, t), where A is an array of n distinct integers sorted in increasing order and t ∈ ℤ. Our goal is to return a pair of indices (i, j) such that i < j and A[i] + A[j] = t (or nothing if no such pair exists). Describe an O(n)-time algorithm for this problem, prove that it's correct, and analyze its running time." The lecture's example is A = [1, 3, 4, 5, 7, 10, 11], t = 10, where the algorithm should return (2, 5) because A[2] + A[5] = 3 + 7 = 10.
Why the naive approach is too slow
The lecture first writes the brute force: two nested loops, for i = 1, ..., n-1: and for j = i+1, ..., n:, returning (i, j) when A[i] + A[j] = t. The outer loop makes at most n iterations and each one runs an inner loop of O(n), so the total is n · O(n) = O(n²). It never uses the fact that A is sorted.
Algorithm
The notes call it a "two-pointer" technique. Start with the candidate (i, j) = (1, n), the smallest and the largest element. Check whether A[i] + A[j] = t; if so, return (i, j). If the sum is too small, the only way to make it bigger is to replace A[i] with something larger, so increment i. If the sum is too large, replace A[j] with something smaller, so decrement j. Repeat until a solution is returned or i = j, in which case nothing is returned.
Two-Sum(A, t):
i, j = 1, n
while i < j:
if A[i] + A[j] = t:
return (i, j)
if A[i] + A[j] < t:
i += 1
else:
j -= 1
Trace on the lecture's example A = [1, 3, 4, 5, 7, 10, 11], t = 10:
| Iteration | i | j | A[i] + A[j] | Compared with t = 10 | Action |
|---|---|---|---|---|---|
| 1 | 1 | 7 | 1 + 11 = 12 | too large | j = 6 |
| 2 | 1 | 6 | 1 + 10 = 11 | too large | j = 5 |
| 3 | 1 | 5 | 1 + 7 = 8 | too small | i = 2 |
| 4 | 2 | 5 | 3 + 7 = 10 | equal | return (2, 5) |
Some cells worked out: in iteration 1, 12 > 10, and since 11 is the largest value, pairing it with anything at index 1 or later gives at least 12, so index 7 is useless and j drops. In iteration 3 the sum 8 is too small, and since index 5 is now the largest index still in play, pairing A[1] = 1 with anything gives at most 8, so index 1 is useless and i rises.
The 08-25 lecture also draws the search as a grid of all sums A[i] + A[j] with i < j, for A = [1, 4, 5, 7] and t = 5. Each step of the algorithm crosses out a whole row (i += 1) or a whole column (j −= 1) of the grid:
| i \ j | 2 | 3 | 4 |
|---|---|---|---|
| 1 | 5 (step 3: found) | 6 (step 2: > 5, cross out column 3) | 8 (step 1: > 5, cross out column 4) |
| 2 | 9 | 11 | |
| 3 | 12 |
The algorithm looks at only 3 of the 6 sums and returns (1, 2). Because the grid increases to the right and downward (A is sorted), a sum that is too large rules out the whole column below it, and a sum that is too small rules out the whole row to its left. That is the correctness argument in picture form.
Correctness
The lecture is explicit that "correct" has two parts for Two Sum, for every input (A, t):
- If ALG returns a pair, that pair is a solution. The algorithm only returns (i, j) inside the test A[i] + A[j] = t, and the loop guarantees i < j. Done.
- If ALG returns nothing, there is no solution. The lecture proves the contrapositive ("the contrapositive of p ⇒ q is ¬q ⇒ ¬p"): if (A, t) has a solution, ALG returns something.
- Claim (invariant): during the algorithm, A[i:j] always contains a solution. Base case: initially A[i:j] = A[1:n] = A, which has a solution by assumption.
- Step, case A[i] + A[j] > t. Then j is not in any solution inside A[i:j], because for every i′ with i ≤ i′ < j, A[i′] + A[j] ≥ A[i] + A[j] > t (A is sorted). So "we can safely decrease j": the solution in A[i:j] is also in A[i:j−1].
- Step, case A[i] + A[j] < t. Symmetric: for every j′ with i < j′ ≤ j, A[i] + A[j′] ≤ A[i] + A[j] < t, so i is in no solution and the solution survives in A[i+1:j].
- Conclusion. A[i:j] always contains a solution, and a solution needs two distinct indices, so the range never shrinks to one element; the algorithm must return a solution when j = i + 1 or earlier.
Running time
This is Problem 2 of the Day 1 worksheet, because a while-loop needs a different count from a for-loop. The official solution: "Notice that j − i is initially n − 1, decreases by 1 in each iteration, and cannot decrease below 0. Thus, the algorithm makes O(n) iterations. Each iteration takes O(1) time, so the total running time is O(n)."
Variant: several solutions. When more than one pair sums to t, the algorithm returns the pair with the smallest i (and therefore the largest j), because that outermost pair is never discarded before it is reached. Homework 1's second instance has seven solutions, and the accepted answer is the outermost one, (16, 29). Extra context beyond the notes: this follows from the invariant argument above applied to the outermost solution; it is a handy check, not something you are asked to prove.
Variant: A sorted in decreasing order. The same idea works with the moves swapped: if the sum is too small, decrement j (toward larger values); if it is too large, increment i.
Check-in 2.2. Run Two-Sum on A = [1, 3, 4, 5, 7, 10, 11] with t = 15. Fill in one column per iteration and write what is returned.
| Iteration | 1 | 2 | 3 |
|---|---|---|---|
| (i, j) | |||
| A[i] + A[j] | |||
| Action |
Answer
(1, 7): 1 + 11 = 12 < 15, so i = 2. (2, 7): 3 + 11 = 14 < 15, so i = 3. (3, 7): 4 + 11 = 15, so the algorithm returns (3, 7).2.3 Binary Search
In plain words. To find a number in a sorted list, look at the middle entry. If it is the number, stop; if it is too small, the number can only be in the right half, and if it is too big, only in the left half. Each look throws away half of what remains. So even a list of a million entries needs only about twenty looks.
- Input: (A, t), A an array of n distinct integers sorted in increasing order, t an integer. Output: an index k with A[k] = t, or nothing. Target: O(log n).
- Idea: two pointers i, j bracket the part of A that could still hold t; test the middle m = ⌊(i + j)/2⌋ (round down).
- Update: if A[m] < t, set i = m + 1; if A[m] > t, set j = m − 1. Loop while i ≤ j.
- Invariant: if t is in A, then t is in A[i:j].
- Running time: the length of A[i:j] at least halves every iteration, so O(log n) iterations of O(1).
- The homework's "trace" is the sequence of m values at which A[m] = t is tested.
- Trap: rounding m up, or writing while i < j, which skips the last one-element range.
Problem
From the notes: "The input is (A, t), where A [is] an array of n distinct integers sorted in increasing order and t ∈ ℤ. Our goal is to return an index k such that A[k] = t (or nothing if no such index exists). Describe an O(log n)-time algorithm for this problem, prove that it's correct, and analyze its running time." The lecture calls it "One Sum" and notes that brute force (scan everything) is O(n). Homework 1's example: on A = [1, 3, 4, 5, 8, 9] with t = 8 the algorithm returns 5, and its trace is "3, 5".
Algorithm
Set (i, j) = (1, n). While the range A[i:j] is non-empty (i ≤ j), compute the middle index m = (i + j)/2 rounded down and compare A[m] with t. If they are equal, return m. If A[m] < t, then every entry at or left of m is also smaller than t (A is sorted), so continue in the right part by setting i = m + 1. Otherwise A[m] > t, and continue in the left part by setting j = m − 1. If the range becomes empty, return nothing.
Binary-Search(A, t):
i, j = 1, n
while i <= j:
m = (i+j) / 2 # round down
if A[m] = t:
return m
if A[m] < t:
i = m + 1
else:
j = m - 1
Trace on Homework 1's instance A = [1, 3, 4, 5, 8, 9]. First t = 8, then t = 2 (not in A):
| t | Iteration | i | j | m = ⌊(i + j)/2⌋ | A[m] | Action |
|---|---|---|---|---|---|---|
| 8 | 1 | 1 | 6 | 3 | 4 | 4 < 8, so i = 4 |
| 8 | 2 | 4 | 6 | 5 | 8 | return 5; trace "3, 5" |
| 2 | 1 | 1 | 6 | 3 | 4 | 4 > 2, so j = 2 |
| 2 | 2 | 1 | 2 | 1 | 1 | 1 < 2, so i = 2 |
| 2 | 3 | 2 | 2 | 2 | 3 | 3 > 2, so j = 1; now i > j, return nothing; trace "3, 1, 2" |
Some cells worked out: (1 + 6)/2 = 3.5 rounds down to 3; (4 + 6)/2 = 5 exactly; (1 + 2)/2 = 1.5 rounds down to 1. In the last row the range A[2:2] has one element, and the loop still runs because i ≤ j; that iteration is what puts the final 2 into the trace.
Correctness
The notes' argument has the same two directions as Two Sum, and the lecture writes "Correctness: ≈ Two Sum".
- If the algorithm returns some m, then A[m] = t, so the answer is correct.
- Conversely, assume t is in A. Invariant: t is in A[i:j] at every point. It holds at the start (the whole array). When A[m] < t, every index k ≤ m has A[k] ≤ A[m] < t because A is sorted, so discarding A[i:m] keeps t; the case A[m] > t is symmetric.
- Termination. The length of A[i:j] strictly decreases each iteration, so the loop cannot run forever, and while t is in A[i:j] the range is non-empty; the only way out is to find t. In the notes' words, "by the iteration in which i = j and A[i:j] only contains t, the algorithm sets m = i and returns m" (or it returns earlier).
Running time
The notes prove that the length halves. Let ℓ = j − i + 1 be the length of A[i:j] at the start of an iteration and ℓ′ its length at the end. If the algorithm sets i = m + 1, then
ℓ′ = j − (m + 1) + 1 = j − ⌊(i + j)/2⌋ ≤ j − i + j2 + 12 = j − i + 12 = ℓ2.
Similarly, if it sets j = m − 1, then ℓ′ = m − i ≤ (j − i)/2 < ℓ/2. So after k iterations the length is at most n/2k, and the lecture finishes the count: the range is down to about one element when n/2k = 1, that is, 2k = n, so k = log₂ n. The algorithm terminates within O(log n) iterations, each O(1), for a total of O(log n).
Check-in 2.3. Run Binary-Search on A = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] with t = 50. Fill in each iteration, then write the trace and the return value.
| Iteration | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| i, j | ||||
| m | ||||
| A[m] |
Answer
(i, j) = (1, 10): m = 5, A[5] = 25 < 50, i = 6. (6, 10): m = 8, A[8] = 64 > 50, j = 7. (6, 7): m = 6, A[6] = 36 < 50, i = 7. (7, 7): m = 7, A[7] = 49 < 50, i = 8 > j. Trace 5, 8, 6, 7; the algorithm returns nothing.2.4 Selection Sort
In plain words. To sort a list, find the smallest entry and swap it to the front. Then find the smallest of the rest and swap it into the second position, and so on. After round i, the first i positions hold the i smallest entries in order and are never touched again. It is simple but slow: each round scans everything that is left.
- Input: an array A of n distinct integers. Output: A rearranged so that A[1] < A[2] < ⋯ < A[n]. Target: O(n²).
- Round i: find the index m of the smallest element of A[i:n] and swap A[i] with A[m].
- Invariant: after round i, A[1:i] contains the i smallest elements of A in sorted order.
- Correctness by induction on the round number i.
- Running time: n rounds, O(n) each, O(n²); exactly n + (n − 1) + ⋯ + 1 = n(n + 1)/2 = O(n²) as the lecture writes.
- Trap: in a trace, only two positions change per round (or none, when A[i] is already the minimum); do not re-sort the unsorted part.
Problem
From the notes: "The input is an array A of n distinct integers. Our goal is to sort A by increasing value (i.e., rearrange A such that A[1] < A[2] < ⋯ < A[n]). Describe an O(n²)-time algorithm for this problem, prove that it's correct, and analyze its running time." Example from the Day 2 worksheet: A = [3, 1, 4, 2] becomes [1, 2, 3, 4].
Algorithm
"The algorithm executes n rounds, one for each i ∈ [n]. In round i, it finds the smallest element A[m] in A[i:n] and swaps it with A[i]." Finding the smallest is an inner loop that remembers the index m of the smallest element seen so far (Max-in-Array with the comparison flipped, and storing an index instead of a value).
Selection-Sort(A):
for i = 1, ..., n:
m = i
for j = i+1, ..., n: # find min of A[i:n]
if A[j] < A[m]:
m = j
swap A[i], A[m]
Trace on the worksheet's A = [3, 1, 4, 2] (Worksheet for Day 2/2, Problem 1: "Your answer should consist of four rows, labeled from i = 1 through i = 4"):
| Round i | A[i:n] before | Smallest, at index m | Swap | A after round i |
|---|---|---|---|---|
| 1 | [3, 1, 4, 2] | 1, m = 2 | A[1] ↔ A[2] | [1, 3, 4, 2] |
| 2 | [3, 4, 2] | 2, m = 4 | A[2] ↔ A[4] | [1, 2, 4, 3] |
| 3 | [4, 3] | 3, m = 4 | A[3] ↔ A[4] | [1, 2, 3, 4] |
| 4 | [4] | 4, m = 4 | none (A[4] with itself) | [1, 2, 3, 4] |
Some cells worked out: in round 2 the scan compares A[3] = 4 with A[2] = 3 (no change, m stays 2), then A[4] = 2 with A[m] = 3 (smaller, m = 4); the swap moves 2 to position 2 and sends 3 to where 2 was. The official answer: "After iteration i = 1, A = [1, 3, 4, 2]. After iteration i = 2, A = [1, 2, 4, 3]. After iterations i = 3 and i = 4, A = [1, 2, 3, 4]."
Correctness
The notes use induction on i to prove: for all i ∈ [n], after round i, A[1:i] contains the i smallest elements of A in sorted order. When i = n this says the whole array is sorted.
- Base case, round 1. The algorithm finds the smallest element in A and swaps it with A[1], so A[1] = min(A).
- Inductive step, round i ≥ 2. By the hypothesis, A[1:i−1] holds the i − 1 smallest elements in order. The algorithm finds the smallest element of A[i:n], which is the i-th smallest element of A, "since A[1:i−1] contains i − 1 smaller elements", and places it at index i. So A[1:i] holds the i smallest elements in sorted order.
Running time
"There are n rounds, and each takes O(n) time, so the total running time is O(n²)." The lecture asks "Better RT?" and counts more carefully: the rounds scan n, n − 1, n − 2, …, 1 elements, and n + (n − 1) + ⋯ + 1 = n(n + 1)/2, which is still O(n²). A tighter count does not change the Big-O.
Check-in 2.4. Write A after each iteration of Selection-Sort on A = [6, 3, 8, 1, 5].
| i | A[1] | A[2] | A[3] | A[4] | A[5] |
|---|---|---|---|---|---|
| 1 | |||||
| 2 | |||||
| 3 | |||||
| 4 | |||||
| 5 |
Answer
i = 1: [1, 3, 8, 6, 5] (swap 6 and 1). i = 2: [1, 3, 8, 6, 5] (3 is already the smallest of A[2:5]). i = 3: [1, 3, 5, 6, 8] (swap 8 and 5). i = 4 and i = 5: [1, 3, 5, 6, 8].2.5 Merge Sort
In plain words. To sort a list, cut it in half, sort each half (by the same method), and then merge the two sorted halves. Merging is easy because the smallest remaining item is always at the front of one of the two halves, so you repeatedly take the smaller front item. This is called divide and conquer. It sorts in O(n log n) time, much faster than Selection Sort.
- Input: an array A of n integers (repeats allowed). Output: A in non-decreasing order, A[1] ≤ A[2] ≤ ⋯ ≤ A[n]. Target: O(n log n).
- Recursion: if n = 1 return A; otherwise k = ⌊n/2⌋, sort A[1:k] into AL and A[k+1:n] into AR, then merge.
- Merge: two pointers i, j at the fronts of AL and AR; append the smaller (ties go to AL, since the test is ≤) and advance that pointer; when one half runs out, append the rest of the other.
- Correctness: induction on n (both halves are sorted by hypothesis; the merge keeps B sorted).
- Recurrence: T(n) = 2 · T(n/2) + O(n), which solves to O(n log n).
- Trap: in a merge trace, list the pairs actually compared; once one half is exhausted the remaining elements are appended with no comparisons.
Problem
From the notes: "The input is an array A of n integers. Our goal is to sort A by non-decreasing value (i.e., rearrange A such that A[1] ≤ A[2] ≤ ⋯ ≤ A[n]). Describe an O(n log n)-time algorithm for this problem, prove that it's correct, and analyze its running time." The lecture's example is A = [4, 8, 1, 3, 2, 6, 5, 7], which becomes [1, 2, 3, 4, 5, 6, 7, 8].
Algorithm
"The algorithm is recursive: if n = 1, simply return A. Otherwise, split A into its left and right halves and recursively sort each half. Then merge the two halves using a two-pointer approach." In the merge, pointer i walks along AL (length k) and pointer j along AR (length n − k). While both have elements left, compare AL[i] with AR[j], append the smaller to the output list B, and advance that pointer. When one half is used up, append everything left in the other half. The notes' pseudocode, split in two blocks:
Merge-Sort(A):
if n = 1: return A
k = n / 2 # round down
A_L = Merge-Sort(A[1:k])
A_R = Merge-Sort(A[k+1:n])
(merge A_L and A_R into B, below)
A = B (as an array)
return A
i, j, B = 1, 1, empty list # the merge step
while i <= k and j <= n-k:
if A_L[i] <= A_R[j]:
append A_L[i] to B; i += 1
else:
append A_R[j] to B; j += 1
if i > k:
append each element of A_R[j:n-k] to B
else:
append each element of A_L[i:k] to B
The whole recursion on the lecture's example. The board shows only the top split into AL = [1, 3, 4, 8] and AR = [2, 5, 6, 7] and the final merge; the lower levels below are filled in here (split down, merge up):
The last merge in detail, with AL = [1, 3, 4, 8] and AR = [2, 5, 6, 7] (k = 4, n − k = 4):
| Step | i | j | Compare AL[i], AR[j] | Append | B after |
|---|---|---|---|---|---|
| 1 | 1 | 1 | 1, 2 | 1 | [1] |
| 2 | 2 | 1 | 3, 2 | 2 | [1, 2] |
| 3 | 2 | 2 | 3, 5 | 3 | [1, 2, 3] |
| 4 | 3 | 2 | 4, 5 | 4 | [1, 2, 3, 4] |
| 5 | 4 | 2 | 8, 5 | 5 | [1, 2, 3, 4, 5] |
| 6 | 4 | 3 | 8, 6 | 6 | [1, 2, 3, 4, 5, 6] |
| 7 | 4 | 4 | 8, 7 | 7 | [1, 2, 3, 4, 5, 6, 7] |
| after loop | 4 | 5 | none (j > n − k) | AL[4:4] = [8] | [1, 2, 3, 4, 5, 6, 7, 8] |
Some cells worked out: in step 2, 3 > 2, so the element from AR is appended and j advances while i stays at 2. After step 7, j = 5 exceeds n − k = 4, so the while-loop stops; since i = 4 ≤ k, the else-branch appends AL[4:4] = [8] without comparing it to anything. This merge makes 7 comparisons for 8 elements.
Correctness
The notes "again proceed by induction" on n.
- Base case, n = 1. "Any array of length 1 is sorted", and the algorithm returns it.
- Inductive step, n ≥ 2. The inductive hypothesis (on the shorter lengths k and n − k) implies that AL and AR are both sorted.
- The merge produces a sorted B. It "combines them into a sorted list B by iteratively appending min(AL[i], AR[j]) to B". Because each half is sorted, AL[i] is the smallest remaining element of AL and AR[j] the smallest remaining of AR, so their minimum is the smallest element not yet in B; appending it keeps B sorted.
- The leftovers. "If i > k, then the algorithm has finished traversing AL, so AR[j:n−k] contains the remaining elements of A, and they are appended to B. (The same logic applies if j > n − k.)" These are all at least the last element of B and already in order. So B is the sorted version of A.
Running time
Let T(n) be the running time on an input of size n, with T(1) ≤ k for some constant k (this k is a constant in the proof, not the split index). For n ≥ 2 the algorithm calls itself twice on inputs of size n/2 (the notes assume n is a power of 2 for simplicity), which contributes 2 · T(n/2). In the merge, each iteration of the while-loop increases i + j by 1, and i + j ≤ n, so merging takes O(n) time. Hence, for some constant c,
T(n) ≤ 2 · T(n/2) + cn.
The Day 2 worksheet's Problem 2 asks for exactly this recurrence, and its official answer is "T(n) = 2 · T(n/2) + O(n)". The notes then solve it by induction, choosing k ≥ c and proving T(n) ≤ kn(log n + 1), with log base 2:
- Base case, n = 1: k · 1 · (log 1 + 1) = k ≥ T(1).
- Inductive step: T(n) ≤ 2 · kn2(log n2 + 1) + cn = kn((log n − 1) + 1) + cn = kn log n + cn.
- Since c ≤ k, this is at most kn log n + kn = kn(log n + 1), which is the claim for n.
- For n ≥ 2, log n ≥ 1, so T(n) ≤ kn(log n + 1) ≤ kn · (2 log n) = O(n log n).
The lecture states it more briefly: "T(n) = 2 · T(n/2) + O(n) ⇒ O(n log n)", and labels the strategy "Divide and Conquer". You will not be asked to re-derive the solution on the final, but you should be able to write the recurrence and say what each term counts.
sort A # Merge Sort as the first line and charge O(n log n) for it. The merge itself is a two-pointer loop, and the "compared pairs" trace from Homework 1 is a one-point question type.Check-in 2.5. Merge AL = [1, 5, 6, 10] and AR = [2, 3, 8, 9]. List every pair compared (AL element first) and the final B.
Answer
The pairs are (1, 2), (5, 2), (5, 3), (5, 8), (6, 8), (10, 8), (10, 9): seven comparisons. After the last one AR is used up and 10 is appended without a comparison. B = [1, 2, 3, 5, 6, 8, 9, 10].Check-in 2.6. Cover the running-time paragraph above. Write the recurrence for Merge Sort, say what each of its two terms counts, and state its solution.
Answer
T(n) = 2 · T(n/2) + O(n). The term 2 · T(n/2) is the two recursive calls, each on half of the array; the O(n) is the merge, whose while-loop increases i + j by 1 per iteration with i + j ≤ n. The solution is T(n) = O(n log n) (the notes prove T(n) ≤ kn(log n + 1) by induction).2.6 Two pointers for an optimization problem: the container problem
In plain words. Think of the array entries as the heights of vertical walls standing at positions 1 through n. Two walls hold water between them: the width between them times the height of the shorter wall. To find the best pair, start with the two outermost walls and repeatedly move the shorter wall inward, remembering the best amount seen. Moving the taller wall could never help, because the shorter wall already limits the height and the width only shrinks.
- Input: an array A of n positive integers. Output: indices (i, j), i < j, maximizing (j − i) · min(A[i], A[j]). Target: O(n).
- Brute force over all pairs is O(n²); the lecture solves it with two pointers "(≈ Two Sum)". Unlike Two Sum, A is not sorted.
- Rule: start at (1, n); record the value; if A[i] ≤ A[j], i += 1; otherwise j −= 1. "Keep track of max."
- Why it is safe, in the lecture's words: "when we i += 1 we've already found best solution w/ this i so we can safely increase i."
- Running time: j − i drops by 1 per iteration, O(n).
- Trap: forgetting to record the value before moving, or returning the last pair instead of the best one.
Problem
This is Problem 1.4 of Problem Set 1, Problem 3 of the Day 2 worksheet, and Problem 2 of Practice Midterm 1, word for word: "The input is an array A of n positive integers. Our goal is to return indices (i, j) such that i < j and (j − i) · min(A[i], A[j]) is maximized. Describe an O(n)-time algorithm for this problem, explain why it's correct, and analyze its running time." The 08-25 lecture's example is A = [1, 3, 2, 5, 2, 2], drawn as bars; the best pair is (2, 6) with value 4 · min(3, 2) = 8.
Algorithm
Start with i = 1 and j = n. In each iteration compute val = (j − i) · min(A[i], A[j]) and, if it beats the best value so far, record (i, j). Then move the pointer at the shorter wall: if A[i] ≤ A[j], increment i; otherwise decrement j. Stop when i = j and return the recorded pair. The official solution's pseudocode:
ALG(A):
i, best_i, j, best_j, m = 1, 1, n, n, -inf
while i < j:
val = (j-i)*min(A[i], A[j])
if val > m:
m, best_i, best_j = val, i, j
if A[i] <= A[j]:
i += 1
else:
j -= 1
return best_i, best_j
Trace on the lecture's A = [1, 3, 2, 5, 2, 2]:
| Iteration | (i, j) | A[i], A[j] | val = (j − i) · min | Best so far | Move |
|---|---|---|---|---|---|
| 1 | (1, 6) | 1, 2 | 5 · 1 = 5 | 5 at (1, 6) | 1 ≤ 2: i = 2 |
| 2 | (2, 6) | 3, 2 | 4 · 2 = 8 | 8 at (2, 6) | 3 > 2: j = 5 |
| 3 | (2, 5) | 3, 2 | 3 · 2 = 6 | 8 at (2, 6) | 3 > 2: j = 4 |
| 4 | (2, 4) | 3, 5 | 2 · 3 = 6 | 8 at (2, 6) | 3 ≤ 5: i = 3 |
| 5 | (3, 4) | 2, 5 | 1 · 2 = 2 | 8 at (2, 6) | 2 ≤ 5: i = 4 = j, stop |
Some cells worked out: in iteration 1 the left wall (height 1) is shorter, so every other pair using index 1 is narrower and still at most 1 tall; index 1 is finished. In iteration 2 the right wall is shorter (2 < 3), so index 6 is finished. The algorithm returns (2, 6); checking all 15 pairs by brute force confirms that 8 is the maximum. It examined only 5 pairs.
Correctness
The technique is the same "never discard the answer" invariant as Two Sum. The official solution: "We are not checking every pair (i, j), but that is not necessary: if A[i] ≤ A[j], then for this particular i, there is no better solution (i, j′) for any j′ < j. Thus, by incrementing i, we cannot miss the optimal solution." Spelled out: if A[i] ≤ A[j] and i < j′ < j, then (j′ − i) < (j − i) and min(A[i], A[j′]) ≤ A[i] = min(A[i], A[j]), so (j′ − i) · min(A[i], A[j′]) < (j − i) · min(A[i], A[j]), the value already recorded. Pairs (i′, j′) with i′ < i or j′ > j were ruled out the same way at earlier steps. So every pair is either examined or beaten by a pair that was examined, and the recorded maximum is optimal. The case A[i] > A[j] is symmetric.
Running time
"The algorithm makes O(n) iterations because j − i decreases by 1 in each one, and each iteration takes O(1) time, so the total running time is O(n)."
Check-in 2.7. Run the container algorithm on A = [2, 6, 3, 4, 5, 1]. Fill in each iteration and write the returned pair.
| Iteration | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| (i, j) | |||||
| val | |||||
| Move |
Answer
(1, 6): 5 · 1 = 5, j = 5 (2 > 1). (1, 5): 4 · 2 = 8, i = 2. (2, 5): 3 · 5 = 15, j = 4 (6 > 5). (2, 4): 2 · 4 = 8, j = 3. (2, 3): 1 · 3 = 3, j = 2, stop. The algorithm returns (2, 5) with value 15.2.7 Worked problems from Problem Set 1
Problem Set 1 was released on August 20 "with solutions, nothing to submit", as the lecture's margin note says. All five problems are below with their statements copied verbatim from the course page; the solutions follow the official ones and use the answer recipe (Algorithm, Correctness, Running time). PS 1.4 has already appeared on an exam word for word.
PS 1.1. The repeated element
Solution
The official solution gives two algorithms; either earns full credit.
Algorithm 1 (sum). Return the sum of A minus n(n + 1)/2.
ALG1(A):
return sum(A) - n(n+1)/2
Correctness. Let k be the repeated element. A contains each of 1, 2, …, n once plus one extra copy of k, so sum(A) = 1 + 2 + ⋯ + n + k = n(n + 1)/2 + k. Subtracting n(n + 1)/2 leaves exactly k. Example: A = [3, 1, 4, 2, 3] with n = 4 has sum 13, and 13 − 10 = 3.
Running time. Computing the sum is a single loop over n + 1 elements, O(n); the subtraction is O(1). Total O(n).
Algorithm 2 (seen-array). Scan A and mark each value in an array B of n zeros; the first value found already marked is the repeat.
ALG2(A):
B = [0]*n # B[k] = 1 means k was seen
for i = 1, ..., n+1:
if B[A[i]] = 1:
return A[i]
B[A[i]] = 1
Correctness. "The array B acts as a hash table whose keys are elements in A, and B[k] = 1 indicates that the algorithm has already seen k in A." Every value is in {1, …, n}, so B[A[i]] is a valid index. The first time a value appears it is marked; the second time, B[k] = 1 and the algorithm returns k. Only the repeated element is ever seen twice. On [3, 1, 4, 2, 3], it marks 3, 1, 4, 2 and returns 3 at i = 5.
Running time. Creating B takes O(n); the loop makes at most n + 1 iterations of O(1). Total O(n).
Pattern: an O(n) scan with either arithmetic or a 0/1 "seen" array standing in for hashing.
PS 1.2. Sorted squares
Solution
Algorithm. (The official solution notes this is LeetCode 977.) Negative numbers make the squares out of order at the left end, but the largest square is always at one of the two ends of A. So use two pointers i = 1 and j = n and fill B from the back: write the larger of A[i]² and A[j]² into B[k], move that pointer inward, and decrease k. A third variable k, initially n, tracks the current index in B.
ALG(A):
i, j, k = 1, n, n
B = [0]*n
while i <= j:
if A[i]^2 >= A[j]^2:
B[k] = A[i]^2
i += 1
else:
B[k] = A[j]^2
j -= 1
k -= 1
return B
Trace on the example A = [−1, 0, 1, 2]:
| (i, j, k) | A[i]², A[j]² | Write | B after |
|---|---|---|---|
| (1, 4, 4) | 1, 4 | B[4] = 4, j = 3 | [0, 0, 0, 4] |
| (1, 3, 3) | 1, 1 | B[3] = 1, i = 2 (tie: ≥ holds) | [0, 0, 1, 4] |
| (2, 3, 2) | 0, 1 | B[2] = 1, j = 2 | [0, 1, 1, 4] |
| (2, 2, 1) | 0, 0 | B[1] = 0, i = 3 | [0, 1, 1, 4] |
Correctness. At every step the unwritten elements are exactly A[i:j], and since A is sorted, the largest square among them is A[i]² or A[j]² (the most negative or the most positive remaining element). In the notes' words: "Since A is sorted, the last element of B is either A[1]² or A[n]². If A[1]² ≥ A[n]², then again since A is sorted, the second-to-last element of B is either A[2]² or A[n]². This logic continues until i = j." So B is filled from position n down to 1 with the largest remaining square each time, and ends up in non-decreasing order.
Running time. Each iteration writes one entry of B and moves one pointer, so j − i decreases by 1 per iteration and there are n iterations of O(1). Creating B is O(n). Total O(n).
Pattern: two pointers from the ends of a sorted array, with a third pointer writing the output from the back.
PS 1.3. Intersection of two arrays
Solution
Algorithm. Sort A (the shorter array). Then, for each element b of B, binary search for b in A; if it is found, append b to C (initially empty).
ALG(A, B):
sort A # Merge Sort
C = [empty list]
for b in B:
if b in A: # use Binary-Search(A, b)
add b to C
return C
Correctness. (Not required by this problem's statement, but one sentence costs nothing.) An element belongs to the intersection exactly when it is in B and in A; the loop visits every element of B once, and Binary-Search on the sorted A correctly reports whether it is in A. Since B has distinct elements, nothing is added twice. Example: A = [7, 2, 9], B = [1, 9, 4, 7, 3] gives C = [9, 7].
Running time. Sorting A takes O(m log m). The loop makes n iterations, each a binary search in an array of length m, O(log m). Total O(m log m) + n · O(log m) = O(n log m), because m ≤ n.
Pattern: a target of O(n log m) means "sort the array of length m, then binary search in it n times". Sorting B instead would cost O(n log n), which is too slow when m is much smaller than n.
PS 1.4. The container problem
Solution
Algorithm. (LeetCode 11.) Two pointers, similar to Two Sum: start with (i, j) = (1, n). In each iteration compute (j − i) · min(A[i], A[j]) and keep track of the maximum and the pair achieving it. If A[i] ≤ A[j], increment i; otherwise decrement j. Stop when i = j and return the best pair.
ALG(A):
i, best_i, j, best_j, m = 1, 1, n, n, -inf
while i < j:
val = (j-i)*min(A[i], A[j])
if val > m:
m, best_i, best_j = val, i, j
if A[i] <= A[j]:
i += 1
else:
j -= 1
return best_i, best_j
Correctness. The algorithm does not check every pair, but it never skips a pair that could be better than one it checked. Suppose A[i] ≤ A[j]. For any j′ with i < j′ < j, the pair (i, j′) is narrower (j′ − i < j − i) and no taller (min(A[i], A[j′]) ≤ A[i] = min(A[i], A[j])), so its value is less than the value of (i, j), which was just recorded. Hence "for this particular i, there is no better solution (i, j′) for any j′ < j", and incrementing i cannot miss the optimal solution. The case A[i] > A[j] is symmetric: no (i′, j) with i < i′ < j beats (i, j), so decrementing j is safe. Since every discarded index has had its best remaining pair examined, the optimal pair's value is recorded, and the algorithm returns it.
Running time. j − i starts at n − 1 and decreases by 1 in each iteration, so there are at most n − 1 iterations, each O(1). Total O(n).
Pattern: two pointers on an unsorted array for an optimization problem; move the pointer that limits the objective. This was Practice Midterm 1, Problem 2, verbatim.
PS 1.5. Minimum difference
Solution
Algorithm. Sort A, then traverse it and keep track of the minimum difference between consecutive elements.
ALG(A):
sort A # Merge Sort
diff = ∞
for i = 2, ..., n:
diff = min(diff, A[i] - A[i-1])
return diff
On the example, sorted A = [1, 5, 7, 10], the consecutive differences are 4, 2, 3, and the algorithm returns 2 (from 7 − 5).
Correctness. After sorting, the minimum difference must be a difference of two consecutive elements. Formally, if A is sorted then for every j < i − 1, A[j] < A[i−1] (distinct values), so A[i] − A[i−1] < A[i] − A[j]: any non-consecutive pair is beaten by a consecutive pair. Hence it suffices to check the n − 1 consecutive differences, which the loop does (Max-in-Array with min). Every difference is positive because larger minus smaller of distinct values.
Running time. Merge Sort takes O(n log n). The loop makes n − 1 iterations of O(1). Total O(n log n) + O(n) = O(n log n).
Pattern: a target of O(n log n) on an unsorted array means "sort first, then one linear pass".
2.8 Homework-style one-point questions
Homework 1 (released August 20, due Thursday, August 27) had four groups of auto-graded one-point questions, one per algorithm except Max in Array. These are exactly the "like short homework" parts of the final's Problems 1 and 2. Each type is worked once below on a homework instance, with the accepted answer.
Type 1: what does Two-Sum return?
"Suppose we run the two-pointer algorithm for Two Sum on the following instance: A = [1, 3, 4, 5, 8, 9], t = 8. What does the algorithm return? Your answer should either be "i, j" (note the space) where i and j are integers, or the string "nothing"." Trace: (1, 6) gives 10 > 8, j = 5; (1, 5) gives 9 > 8, j = 4; (1, 4) gives 6 < 8, i = 2; (2, 4) gives 3 + 5 = 8. Accepted answer: 2, 4. The other two homework instances had 30 and 60 elements (accepted answers "16, 29" and "nothing"). On a long array, do not panic: the pointers still move one step at a time, and the first match found is the pair with the smallest i. To double-check a "nothing", scan i from the left and ask whether t − A[i] appears to its right.
Type 2: the Binary-Search trace
"The 'trace' of the algorithm is the sequence of m's where we test if A[m] = t." On A = [1, 3, 4, 5, 8, 9] with t = 2, the trace is 3, 1, 2 (worked in Section 2.3). On the homework's 50-element array with t = 33, the accepted trace was 25, 12, 18: m = ⌊(1 + 50)/2⌋ = 25 and A[25] = 50 > 33, so j = 24; m = ⌊(1 + 24)/2⌋ = 12 and A[12] = 19 < 33, so i = 13; m = ⌊(13 + 24)/2⌋ = 18 and A[18] = 33, found. Write down i and j at each step; computing m from them is mechanical, and only the elements A[m] need to be looked up.
Type 3: a slice of A after iteration k of Selection-Sort
"Suppose we run Selection Sort on A = [18, 73, 98, 9, 33]. After iteration 1, A[2:4] = [73, 98, 18]. After iteration 2, what is A[2:4]?" Iteration 1 swaps 18 with the minimum 9: A = [9, 73, 98, 18, 33]. Iteration 2 finds the minimum of A[2:5] = [73, 98, 18, 33], which is 18 at index 4, and swaps it with A[2]: A = [9, 18, 98, 73, 33]. Accepted answer: [18, 98, 73]. The 50-element version asked for A[10:15] (six elements) after iterations 1 and 10; the accepted answers were [49, 27, 13, 63, 4, 50] and [16, 27, 58, 63, 33, 50]. Only the slots touched by a swap change, so follow each round's two swapped positions.
Type 4: the compared pairs in a merge
"Suppose we run Merge Sort on A = [18, 73, 98, 9, 33, 16, 64, 58], and suppose we have already obtained AL = [9, 18, 73, 98] and AR = [16, 33, 58, 64], so we are ready to merge. The first pair of integers we compare is "9, 16"." The questions asked for the second through sixth pairs, AL element first:
| Pair | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| Compared | 9, 16 | 18, 16 | 18, 33 | 73, 33 | 73, 58 | 73, 64 |
| Appended | 9 | 16 | 18 | 33 | 58 | 64 |
After the sixth comparison AR is exhausted, and 73 and 98 are appended without comparisons. The rule for each step: the pointer whose element was appended advances, and the other one stays.
2.9 Past exam problems on this chapter
Two exams covered course Chapter 1: Practice Midterm 1 (September 17, 2026, 25 points, 65 minutes) and Midterm 1. On each, Problem 1(a) was a one-point Two-Sum trace, and Practice Midterm 1's Problem 2 was PS 1.4 verbatim. Both exams used the same cover-page rules as the final, including "array indices start at 1" and "the values in any array A should be listed in order from A[1] through A[n]". (The Practice Final's array problems, such as its Problem 3 on stock prices, are dynamic programs and are worked in Chapter 6.)
Practice Midterm 1, Problem 1(a)
Solution
(2, 4). (1, 4): 1 + 7 = 8 < 10, so i = 2; (2, 4): 3 + 7 = 10, return.Midterm 1, Problem 1(a)
Solution
(1, 2). (1, 4): 2 + 6 = 8 > 5, j = 3; (1, 3): 2 + 5 = 7 > 5, j = 2; (1, 2): 2 + 3 = 5, return.Practice Midterm 1, Problem 2
Solution
The official solution reads, in full: "This is Problem 1.4 from Problem Set 1; the solution is on Canvas/Pages." Here is that solution compressed to what fits in the exam box.
Algorithm. Two pointers i = 1, j = n. While i < j: compute val = (j − i) · min(A[i], A[j]) and record (i, j) if val is the largest so far; then if A[i] ≤ A[j], i += 1, else j −= 1. Return the recorded pair.
ALG(A):
i, j, m, best = 1, n, -inf, (1, n)
while i < j:
val = (j-i)*min(A[i], A[j])
if val > m: m, best = val, (i, j)
if A[i] <= A[j]: i += 1
else: j -= 1
return best
Correctness. If A[i] ≤ A[j], every pair (i, j′) with i < j′ < j is narrower and has height at most A[i] = min(A[i], A[j]), so it is worse than (i, j), which was already recorded; hence discarding i loses nothing. Symmetrically when A[i] > A[j]. So the optimal pair is examined (or tied by an examined pair), and the maximum recorded is optimal.
Running time. j − i decreases by 1 per iteration from n − 1, so O(n) iterations of O(1): O(n).
Before moving on
- I can convert an operation count to Big-O and state "iterations × time per iteration" for any loop.
- I can write the loop-invariant induction for Max-in-Array (claim, base case i = 2, step).
- I can trace Two-Sum and Binary-Search by hand and give the answer in the exact format (1-based indices, or the trace of m values, or "nothing").
- I can write A after each round of Selection-Sort and list the compared pairs of a merge.
- I can state Merge Sort's recurrence T(n) = 2 · T(n/2) + O(n) and say why it gives O(n log n).
- I can reproduce the full answer to PS 1.4 (the container problem), including why moving the shorter wall is safe.
Exercises
Solution
(a) O(n). (b) n(n + 1)/2 = n²/2 + n/2, so O(n²). (c) O(n³). (d) O(1), constant time. (e) Since m ≤ n, m log m ≤ n log m, so the sum is at most 2n log m: O(n log m) (this is PS 1.3's bound).Solution
(1, 6): 1 + 15 = 16 < 18, i = 2. (2, 6): 2 + 15 = 17 < 18, i = 3. (3, 6): 4 + 15 = 19 > 18, j = 5. (3, 5): 4 + 11 = 15 < 18, i = 4. (4, 5): 7 + 11 = 18, return (4, 5).Solution
(i, j) = (1, 11): m = 6, A[6] = 19 > 5, j = 5. (1, 5): m = 3, A[3] = 7 > 5, j = 2. (1, 2): m = 1, A[1] = 2 < 5, i = 2. (2, 2): m = 2, A[2] = 4 < 5, i = 3 > j. Trace 6, 3, 1, 2; the algorithm returns nothing.Solution
| i | Swap | A after |
|---|---|---|
| 1 | A[1] = 4 ↔ A[5] = 1 | [1, 9, 2, 7, 4, 8] |
| 2 | A[2] = 9 ↔ A[3] = 2 | [1, 2, 9, 7, 4, 8] |
| 3 | A[3] = 9 ↔ A[5] = 4 | [1, 2, 4, 7, 9, 8] |
| 4 | none (7 is the minimum of A[4:6]) | [1, 2, 4, 7, 9, 8] |
| 5 | A[5] = 9 ↔ A[6] = 8 | [1, 2, 4, 7, 8, 9] |
| 6 | none | [1, 2, 4, 7, 8, 9] |
Solution
(2, 3), (7, 3), (7, 4), (7, 10), (9, 10), (12, 10), (12, 15): 7 comparisons. After (12, 15) appends 12, AL is exhausted and 15 is appended without a comparison. B = [2, 3, 4, 7, 9, 10, 12, 15].while i < j: instead of while i <= j:. Give an input on which the modified algorithm is wrong, and explain.Solution
A = [5], t = 5. Initially i = j = 1, so the loop condition i < j is false, the loop never runs, and the algorithm returns nothing even though A[1] = 5. In general the bug misses t whenever the range has shrunk to the single element holding t; for example A = [1, 3, 4, 5, 8, 9], t = 3 gives m = 3 (4 > 3, j = 2), then m = 1 (1 < 3, i = 2), and now i = j = 2 ends the loop without testing A[2] = 3.Solution
It proves only one direction. Correctness also requires that if a solution exists, the algorithm returns something (equivalently, if it returns nothing, there is no solution). The missing part is the invariant "A[i:j] always contains a solution", with the reason each move is safe: if A[i] + A[j] > t, then A[i′] + A[j] ≥ A[i] + A[j] > t for every i′ ≥ i because A is sorted, so j is in no solution and can be discarded (symmetrically for i), and a range that always contains a two-element solution cannot shrink to one element before the solution is returned.Solution
Keep (i, j) = (1, n) and the loop, but swap the moves: if A[i] + A[j] < t, set j −= 1 (A[j−1] > A[j], so the sum grows); if A[i] + A[j] > t, set i += 1 (A[i+1] < A[i], so the sum shrinks). The correctness argument is the mirror image: when the sum is too small, A[j] is the smallest value in A[i:j], so pairing it with anything in range gives at most A[i] + A[j] < t and j is in no solution. Running time is unchanged, O(n).Solution
Algorithm. Fix the smallest index i, and look for the other two in A[i+1:n] with Two-Sum and target t − A[i]. Two-Sum returns indices relative to the subarray, so shift them by i.
ALG(A, t):
for i = 1, ..., n-2:
r = Two-Sum(A[i+1:n], t - A[i])
if r is a pair (a, b):
return (i, i+a, i+b) # convert to indices of A
return nothing
On the example: i = 1 searches [2, 4, 7, 11] for 12 (sums 13, 9, 11; nothing); i = 2 searches [4, 7, 11] for 11 and finds 4 + 7 at relative (1, 2), so the algorithm returns (2, 3, 4), and 2 + 4 + 7 = 13.
Correctness. If the algorithm returns (i, i + a, i + b), then i < i + a < i + b and A[i+a] + A[i+b] = t − A[i] by the correctness of Two-Sum, so the triple is a solution. Conversely, if some solution (i*, j*, k*) exists, then in iteration i = i* (if no earlier iteration returned), A[i*+1:n] is sorted with distinct elements and contains the pair j*, k* summing to t − A[i*], so Two-Sum returns some pair, and the algorithm returns a solution. Hence it returns nothing only when no solution exists.
Running time. The loop makes at most n − 2 iterations. Each calls Two-Sum on an array of length at most n, O(n) (passing the subarray by its endpoints costs O(1); copying it would cost O(n), which is also fine). Total n · O(n) = O(n²).
Course Ch. 2 · Aug 27–Sep 33. Essential graph algorithms
The course notes open Chapter 2 with the sentence "The algorithms in this section are the essential building blocks of graph algorithms," and that is exactly their role on the final. Breadth-first search (BFS) and depth-first search (DFS) are the two ways of walking through a graph; everything else in this chapter (finding a cycle, ordering a DAG so that every edge points forward, splitting a graph into strongly connected components) is DFS or BFS with a small modification, and Chapters 4, 7 and 8 of this guide call them again. On the exam they appear twice: as one-point hand traces in Problems 1 and 2 (a BFS "d" array, DFS "post" values with smallest-label tie-breaking, a list of back or cross edges), and as five-point design problems, where the winning move is almost always "run BFS, DFS or Topological-Sort, then scan the result". Midterm 1 and Practice Midterm 1 each had two such problems, and two of those four were copied from Problem Set 2. Every algorithm in this chapter visits each vertex once and scans each adjacency list once, so it runs in O(m + n) time, and almost every design problem on graphs is solved by calling one of them and then doing O(m + n) more work.
3.1 Graphs, adjacency lists, n and m
In plain words. A graph is a set of points, called vertices, joined by lines, called edges; in a directed graph each edge is an arrow. The course always stores a graph as an adjacency list: for every vertex, the list of vertices its arrows point to. With this format, looking at all the arrows out of one vertex costs time proportional to how many arrows there are. Adding these costs over all vertices gives the number of edges, which is why every algorithm in this chapter runs in time proportional to the size of the graph.
- A graph G = (V, E) has vertex set V = {1, …, n} and edge set E; the course writes n = |V| and m = |E| throughout.
- A directed edge from u to v is written with parentheses, (u, v); an undirected edge is written {u, v}. The out-neighbors of u are the v with (u, v) ∈ E, and out-deg(u) is how many there are.
- Adjacency matrix: an n × n array with G[u][v] = 1 if (u, v) ∈ E and 0 otherwise. Adjacency list: an array of n lists, G[u] being the list of out-neighbors of u. The lecture: "In COMP 550: by default, G is an adj list."
- The length of G[u] is out-deg(u), and Σu ∈ V out-deg(u) = m. This one identity is behind every O(m + n) bound in the chapter.
- Testing whether (u, v) ∈ E costs O(1) with a matrix but O(out-deg(u)) with a list; listing the out-neighbors of u costs O(n) with a matrix but O(out-deg(u)) with a list.
- Exam convention: vertices are labelled 1 to n, each list is written in increasing order, and exam questions say "As usual, break ties in favor of the vertex with the smallest label."
The lecture of 08-27 lists "four common representations of a graph": a picture, the pair G = (V, E), an adjacency matrix ("array of length n, each element is an array of length n") and an adjacency list ("array of length n, each element is a list of out-neighbors"). Its running example is G = [[2, 3, 4], [1], [4, 2], []]: vertex 1 points to 2, 3 and 4; vertex 2 points to 1; vertex 3 points to 4 and 2; vertex 4 points nowhere. Here n = 4 and m = 3 + 1 + 2 + 0 = 6. A graph may have up to n(n − 1) directed edges, so m can be as large as about n², and the lecture notes in red that O(m + n) is called "linear time" "even though m could be ≈ n²": linear in the size of the input, which is n + m.
Problem
The two problems on the worksheet for Day 1/3 compare the formats. Problem 1: "The input is (G, u, v) where G is a directed graph as either an adjacency matrix or an adjacency list (and u and v are vertices in G), and our goal is to determine if (u, v) is an edge in E. Describe two algorithms for this problem (one for each format of G) and analyze their running times." Problem 2: the same input without v; the goal is "to print the out-neighbors of u". On the running example, (3, 2) is an edge and (2, 3) is not, and the out-neighbors of 3 are 4 and 2.
Algorithm
For Problem 1 with a matrix, return whether G[u][v] = 1; with a list, walk along G[u] and return True if v is found, False at the end. For Problem 2 with a matrix, loop v = 1, …, n and print v whenever G[u][v] = 1; with a list, print every element of G[u]. The lecture writes the list versions as follows.
Is-Edge(G, u, v): # adjacency list
for w in G[u]:
if w = v: return True
return False
Print-Out-Neighbors(G, u): # adjacency list
for v in G[u]:
print(v)
Correctness
Both are immediate from the definitions: (u, v) ∈ E exactly when v appears in the list G[u], equivalently when G[u][v] = 1, and the out-neighbors of u are exactly the elements of G[u].
Running time
Indexing into an array is a primitive operation, so the matrix test is O(1). The list test walks a list of length out-deg(u), so it is O(out-deg(u)) (the lecture adds, in purple, "more precisely O(out-deg(u) + 1)", which covers an empty list). Printing out-neighbors is O(n) with a matrix, because the whole row of length n is scanned, and O(out-deg(u)) with a list. The lecture marks O(n) for the list version as "correct but not the best".
Check-in 3.1. Write the adjacency list of the directed graph with edges (1, 3), (2, 1), (2, 3), (3, 4), (4, 2), then give n, m and the sum of the list lengths.
Answer
G = [[3], [1, 3], [4], [2]]. n = 4, m = 5, and the list lengths 1 + 2 + 1 + 1 = 5 = m, as they must.3.2 Breadth-first search
In plain words. Breadth-first search finds, for every vertex, how few arrows you must follow to get there from a chosen start vertex. It works outward in layers: first everything one arrow away from the start, then everything one arrow beyond those, and so on, using a queue so that vertices are handled in the order they were discovered. The first time a vertex is discovered, its distance is fixed at one more than the distance of the vertex that discovered it. The notes picture it as "water spreading across the surface of a table in the shape of an expanding circle".
- Input (G, s): a directed graph and a start vertex s ∈ V. Output: an array d with d[v] = the distance from s to v, the number of edges on a shortest s-v path, or ∞ if v cannot be reached.
- The idea: a first-in first-out queue processes vertices in order of distance, so the first vertex that discovers v is at distance d[v] − 1.
- "Processing u" means scanning G[u] in order; every v with d[v] = ∞ gets d[v] = d[u] + 1 and joins the back of the queue.
- Recording p[v] = u at the same moment gives parent pointers; the edges (p[v], v) form the BFS tree, and following p back from v gives a shortest path.
- Running time O(m + n): each vertex enters the queue at most once and its list is scanned once.
- Trap: BFS distances count edges. With edge lengths you need Dijkstra or Bellman-Ford (Chapter 7).
Problem
The notes: "The input is (G, s), where G is a directed graph and s ∈ V. Our goal is to return an array d such that for all v ∈ V, d[v] is the distance from s to v. Describe an O(m + n)-time algorithm for this problem, prove that it's correct, and analyze its running time." Tiny instance: for G = [[2], [3], []] and s = 1, the answer is d = [0, 1, 2]; for s = 3 it is d = [∞, ∞, 0].
Algorithm
Set every d value to ∞ except d[s] = 0, and put s alone in a queue Q. While Q is not empty, remove the vertex u at its front and process it: for each out-neighbor v of u, in the order of the list G[u], check whether v has been seen before (d[v] ≠ ∞). If not, set d[v] = d[u] + 1 and add v to the back of Q. When the queue is empty, return d. A vertex that is never reached keeps d[v] = ∞.
BFS(G, s):
d = [∞]*n; d[s] = 0
Q = queue(s)
while |Q| >= 1:
u = dequeue from Q
for v in G[u]:
if d[v] = ∞:
d[v] = d[u] + 1 # p[v] = u (parent pointer, 09-01 lecture)
add v to Q
return d
The lecture's example (08-27) is the eight-vertex graph below with s = 1, as the adjacency list G = [[2, 4], [3, 5, 6], [6], [5, 7], [7], [8], [], [5]].
| Step | Dequeue u | Scan G[u] | Newly set | Queue after |
|---|---|---|---|---|
| 0 | (start) | d[1] = 0 | [1] | |
| 1 | 1 | 2, 4 | d[2] = 1, d[4] = 1 | [2, 4] |
| 2 | 2 | 3, 5, 6 | d[3] = d[5] = d[6] = 2 | [4, 3, 5, 6] |
| 3 | 4 | 5, 7 | d[7] = 2 (5 already seen) | [3, 5, 6, 7] |
| 4 | 3 | 6 | none | [5, 6, 7] |
| 5 | 5 | 7 | none | [6, 7] |
| 6 | 6 | 8 | d[8] = 3 | [7, 8] |
| 7 | 7 | (empty) | none | [8] |
| 8 | 8 | 5 | none | [ ] |
The result is d = [0, 1, 2, 1, 2, 2, 2, 3], exactly as written in the lecture. Some cells worked out: at step 2, vertex 2 is dequeued before 4 because it entered the queue first, so it discovers 5 before 4 can, and the tree edge into 5 is (2, 5), not (4, 5). At step 3, vertex 7 is discovered by 4 (distance 1) rather than by 5, so d[7] = 2. At step 8, the edge (8, 5) is scanned but 5 already has d[5] = 2 and nothing changes. The BFS tree, highlighted in green in the lecture, consists of the seven edges that set a d value: (1, 2), (1, 4), (2, 3), (2, 5), (2, 6), (4, 7), (6, 8).
Parent pointers and paths. The 09-01 lecture asks "How do we get the actual paths from s?" and answers "Track parent pointers in an array p": add the line p[v] = u next to d[v] = d[u] + 1. On the graph [[2], [3, 4], [4], [1]] with s = 1 this gives d = [0, 1, 2, 2] and parents p[2] = 1, p[3] = 2, p[4] = 2 (vertex 1 has no parent). "To get the s → v path: start at v, keep recursively going to p[v] until you reach s", then reverse: from 4 the walk is 4, 2, 1, reversed to the path 1, 2, 4.
Tie-breaking. The worksheet for Day 1/3, Problem 3, asks for "the edges of the BFS tree, in the order in which they're added" on G = [[2, 4], [3, 4], [1, 4], []]. The lecture adds the convention that exam questions repeat: "In COMP 550: break ties in favor of vertex with smallest label", which in practice means scanning each list in increasing order. Vertex 1 discovers 2 and then 4; vertex 2 then discovers 3 (its other neighbor 4 is already seen); 4 and 3 discover nothing new. The answer is (1, 2), (1, 4), (2, 3), with d = [0, 1, 2, 1].
Correctness
The notes argue by induction on the distance. "Suppose the distance from s to some vertex v is k; we want to show that at the end of BFS, d[v] = k. If k = 0, then s = v and d[v] = 0, as desired. If k > 0, then there exists an in-neighbor u of v such that BFS set d[u] = k − 1 and added u to Q. (We can further formalize this via induction; we omit the details.) When BFS removes u from Q, it sets d[v] = d[u] + 1 = k, as desired." The vertex u is the one just before v on a shortest s-v path; its distance is k − 1, so by the induction hypothesis d[u] = k − 1.
To make the step airtight (this is the part the notes omit), check two inequalities. First, d[v] ≥ k: every value BFS writes is d[v] = d[u] + 1 along an actual edge (u, v), so by induction d[v] is the length of an actual s-v path, which cannot be shorter than the shortest one. Second, d[v] ≤ k: the queue holds vertices in nondecreasing order of d, so when u (with d[u] = k − 1) is dequeued, either v is still unseen and gets d[v] = k, or v was seen earlier from some vertex x dequeued no later than u, with d[x] ≤ k − 1, so d[v] ≤ k. Together, d[v] = k. Vertices that cannot be reached are never added to the queue and keep d[v] = ∞, which is also correct.
Running time
Initializing d and Q takes O(n). "Every vertex gets added to Q at most once, so the while-loop makes at most n iterations." The tempting next step is to bound each iteration by O(n), because u can have up to n − 1 out-neighbors, for O(n²) in total; the notes call this "correct, but the analysis can be improved". Processing u takes only O(out-deg(u)) time, and Σu ∈ V out-deg(u) = m, so the scans cost O(m) in total and the whole algorithm runs in O(m + n). The lecture writes the sum out: O(out-deg(1)) + O(out-deg(2)) + ⋯ + O(out-deg(n)) = O(m), "# edges".
Variants. On an undirected graph BFS works unchanged (each edge appears in both lists) and reaches exactly the connected component of s, which is the whole idea of PS 2.3. Running BFS from every vertex costs n · O(m + n), which is O(mn) when the graph is connected (PS 2.1). Replacing "distance" by a 0/1 color that alternates layer by layer gives the bipartiteness test of PS 2.4.
Check-in 3.2. Run BFS from s = 1 on G = [[2, 5], [3], [6], [1], [4, 6], [3]] (drawn below). Fill in d, then list the BFS tree edges in the order they are added.
| v | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| d[v] |
Answer
d = [0, 1, 2, 2, 1, 2]. Vertices are dequeued in the order 1, 2, 5, 3, 4, 6, and the tree edges are added in the order (1, 2), (1, 5), (2, 3), (5, 4), (5, 6). Vertex 6 is discovered by 5 (step 3), not by 3, because 5 was dequeued before 3 scanned its list.3.3 Depth-first search, Explore, pre and post values
In plain words. Depth-first search walks through a graph by always going deeper: from the current vertex it follows the first arrow to an unvisited vertex, and from there the first arrow again, and only when it is stuck does it back up one step and try the next arrow. The notes compare it to "running in a maze while unraveling a long rope on the ground behind us". A clock records, for each vertex, the time it was first entered (its pre value) and the time it was finally left (its post value). These two numbers per vertex are the whole output, and the next four sections read cycles, orderings and components from them.
- Input: a directed graph G. Output: arrays pre and post; the lecture calls pre[u] the "arrival time" and post[u] the "departure time".
- Explore(G, u) stamps pre[u] = t, then recursively explores every unvisited out-neighbor of u in the order of G[u], then stamps post[u] = t. The clock t starts at 1 and goes up by 1 after every stamp, so the values 1, …, 2n are each used exactly once.
- DFS(G) is "simply a wrapper around Explore": for u = 1, …, n in order, if u is unvisited, call Explore(G, u). Each such call starts a new tree.
- Nesting: if Explore(v) is called while Explore(u) is running, then pre[u] < pre[v] < post[v] < post[u]. Explore(u) does not finish until every vertex reachable from u through unvisited vertices has been explored.
- Running time O(m + n), by the same sum of out-degrees as BFS.
- Trap: after the first tree finishes, DFS restarts at the smallest unvisited label, and the clock keeps running; it does not restart at 1.
Problem
The notes "describe DFS without any particular problem in mind"; its job is to produce pre and post. Tiny instance (worksheet for Day 2/3, Problem 1): "Write the pre- and post-values if we run DFS on the following graph: [[2, 3], [3, 4], [], [1, 3]]." The official answer is pre = [1, 2, 3, 5], post = [8, 7, 4, 6].
Algorithm
Start with every pre and post value equal to ∞ and the clock at t = 1. DFS looks at the vertices 1, 2, …, n in turn and calls Explore on each one that has not been visited (pre value still ∞). Explore(G, u) first writes pre[u] = t and advances the clock; then it goes through the list G[u] in order, and for each out-neighbor v that has not been visited it calls Explore(G, v) and waits for that call to finish completely; when the list is exhausted, it writes post[u] = t and advances the clock. A vertex that has been visited, whether finished or still in progress, is skipped.
Explore(G, u):
pre[u] = t; t += 1
for v in G[u]:
if pre[v] = ∞:
Explore(G, v)
post[u] = t; t += 1
DFS(G):
pre, post, t = [∞]*n, [∞]*n, 1
for u in V: # for u = 1, ..., n
if pre[u] = ∞:
Explore(G, u)
return pre, post
Trace 1: the worksheet graph G = [[2, 3], [3, 4], [], [1, 3]]. The table lists every tick of the clock; the call stack is the chain of Explore calls still running after that tick.
| t | Event | Why | Call stack after |
|---|---|---|---|
| 1 | pre[1] = 1 | DFS starts at vertex 1 | 1 |
| 2 | pre[2] = 2 | first entry of G[1] = [2, 3] is unvisited | 1, 2 |
| 3 | pre[3] = 3 | first entry of G[2] = [3, 4] is unvisited | 1, 2, 3 |
| 4 | post[3] = 4 | G[3] is empty | 1, 2 |
| 5 | pre[4] = 5 | next entry of G[2] is 4, unvisited | 1, 2, 4 |
| 6 | post[4] = 6 | G[4] = [1, 3]: both already visited | 1, 2 |
| 7 | post[2] = 7 | G[2] exhausted | 1 |
| 8 | post[1] = 8 | remaining entry 3 of G[1] already visited | (empty) |
So pre = [1, 2, 3, 5] and post = [8, 7, 4, 6], as in the official solution. Some cells worked out: at t = 6, vertex 4 looks at 1, which is visited but not finished (it is on the stack), and at 3, which is finished; neither is explored again. At t = 8, vertex 1 resumes its list after 2 and reaches 3, already visited, so it finishes. The tree edges, along which Explore was called, are (1, 2), (2, 3), (2, 4).
Trace 2: the lecture's seven-vertex example (09-01): G = [[2, 3, 5], [3, 4], [], [1, 3], [4], [2, 3, 7], []]. This one needs a restart.
| t | Event | Why | Call stack after |
|---|---|---|---|
| 1 | pre[1] = 1 | DFS starts at 1 | 1 |
| 2 | pre[2] = 2 | G[1] = [2, 3, 5]: 2 unvisited | 1, 2 |
| 3 | pre[3] = 3 | G[2] = [3, 4]: 3 unvisited | 1, 2, 3 |
| 4 | post[3] = 4 | G[3] empty | 1, 2 |
| 5 | pre[4] = 5 | next in G[2]: 4 unvisited | 1, 2, 4 |
| 6 | post[4] = 6 | G[4] = [1, 3]: both visited | 1, 2 |
| 7 | post[2] = 7 | G[2] exhausted | 1 |
| 8 | pre[5] = 8 | back in G[1]: 3 visited, 5 unvisited | 1, 5 |
| 9 | post[5] = 9 | G[5] = [4]: visited | 1 |
| 10 | post[1] = 10 | G[1] exhausted | (empty) |
| 11 | pre[6] = 11 | DFS loop: 2, 3, 4, 5 visited; 6 is not | 6 |
| 12 | pre[7] = 12 | G[6] = [2, 3, 7]: 2, 3 visited, 7 unvisited | 6, 7 |
| 13 | post[7] = 13 | G[7] empty | 6 |
| 14 | post[6] = 14 | G[6] exhausted | (empty) |
| v | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| pre | 1 | 2 | 3 | 5 | 8 | 11 | 12 |
| post | 10 | 7 | 4 | 6 | 9 | 14 | 13 |
These are the pairs the lecture writes beside the vertices: 1,10 / 2,7 / 3,4 / 5,6 / 8,9 / 11,14 / 12,13. Some cells worked out: vertex 6 has no incoming edges, so nothing reaches it from 1 and it is explored only when the DFS loop reaches u = 6, at time 11; the clock continues from 10, it does not restart. The DFS "tree" is therefore a forest of two trees, rooted at 1 and 6, with tree edges (1, 2), (2, 3), (2, 4), (1, 5), (6, 7).
Correctness
There is no problem statement to prove, but the later proofs use three facts, all visible in the code. (1) Every vertex is explored exactly once. The wrapper calls Explore on every vertex that is still unvisited, so each vertex is explored at least once, and the test pre[v] = ∞ prevents a second call. (2) Nesting. Calls form a stack: if Explore(v) starts while Explore(u) is running, it must finish before Explore(u) can continue, so pre[u] < pre[v] < post[v] < post[u]. Two intervals [pre, post] are therefore either nested or disjoint, never overlapping. (3) Explore(u) reaches everything it can. When Explore(u) finishes, every out-neighbor of u has been visited (each one was either visited already or explored from u), and so every vertex reachable from u along a path of vertices that were unvisited when Explore(u) began is a descendant of u. The proofs of Find-Cycle and Topological-Sort in Sections 3.5 and 3.6 are applications of facts (2) and (3).
Running time
The notes: "Every vertex gets explored exactly once, and exploring a vertex u (ignoring the cost incurred by subsequent recursive calls) takes O(out-deg(u)). Since Σu ∈ V out-deg(u) = m, the total running time is O(m + n)." The DFS loop itself adds O(n) for the n checks of pre[u].
Check-in 3.3. Run DFS on G = [[2, 4], [3], [1], [3, 5], [2], [5]] (drawn below) and fill in pre and post.
| v | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| pre | ||||||
| post |
Answer
pre = [1, 2, 3, 6, 7, 11], post = [10, 5, 4, 9, 8, 12]. Order of events: pre1, pre2, pre3, post3 (3's only neighbor 1 is on the stack), post2, pre4 (back in G[1]), pre5 (G[4] = [3, 5]: 3 is finished), post5 (2 visited), post4, post1, then a restart at 6: pre6 = 11, post6 = 12.3.4 Classifying edges: tree, forward, back, cross
In plain words. After DFS has run, every edge of the graph can be given one of four labels depending on how it relates to the tree that DFS built. Tree edges are the ones DFS actually walked along; forward edges jump from a vertex down to a descendant by a shortcut; back edges point from a vertex up to one of its ancestors; cross edges are everything else. The label can be read off from the pre and post values of the two endpoints without drawing the tree. Back edges matter most, because they are exactly the edges that close cycles.
- Input: a directed graph after DFS (pre, post and the tree T). Output: the type of every edge (u, v).
- The notes: "Tree edges were directly traversed by DFS, and their union is called the DFS tree." It may be a forest: "Each time DFS calls Explore(G, u), it implicitly creates a new tree, rooted at u."
- "(u, v) is a forward edge if there is a path from u to v in T, (u, v) is a back edge if there is a path from v to u in T, and (u, v) is a cross edge if it is none of the above."
- Timestamp test: tree or forward ⇔ pre[u] < pre[v] < post[v] < post[u]; back ⇔ pre[v] < pre[u] < post[u] < post[v]; cross ⇔ pre[v] < post[v] < pre[u] < post[u].
- O(1) per edge once pre and post are known, so classifying all edges takes O(m + n).
- Trap: an edge (u, v) with pre[u] < post[u] < pre[v] < post[v] cannot exist, because Explore(u) would have visited v. Cross edges always point from the later interval to the earlier one ("right to left").
Problem
Worksheet for Day 2/3, Problem 2: "For the same graph as Problem 1, state the type of every edge (DFS tree, forward, back, cross)." Official answer for G = [[2, 3], [3, 4], [], [1, 3]]: tree (1, 2), (2, 3), (2, 4); forward (1, 3); back (4, 1); cross (4, 3).
Algorithm
Run DFS and keep the tree edges (the (u, v) for which Explore(v) was called from Explore(u)). For every other edge (u, v), compare the two intervals [pre[u], post[u]] and [pre[v], post[v]]. If v's interval lies inside u's, v is a descendant of u and the edge is forward. If u's interval lies inside v's, v is an ancestor of u and the edge is back. If the intervals are disjoint (v's entirely before u's), neither is an ancestor of the other and the edge is cross.
| Edge (u, v) | Timestamp pattern | Meaning in T |
|---|---|---|
| tree or forward | pre[u] < pre[v] < post[v] < post[u] | v is a descendant of u |
| back | pre[v] < pre[u] < post[u] < post[v] | v is an ancestor of u (or v = u) |
| cross | pre[v] < post[v] < pre[u] < post[u] | neither is an ancestor of the other |
Applied to the lecture's seven-vertex example, pre = [1, 2, 3, 5, 8, 11, 12] and post = [10, 7, 4, 6, 9, 14, 13]:
| Edge | Intervals [pre, post] of u and v | Type |
|---|---|---|
| (1, 2), (2, 3), (2, 4), (1, 5), (6, 7) | Explore(v) called from u | tree |
| (1, 3) | [1, 10] contains [3, 4], not a tree edge | forward |
| (4, 1) | [5, 6] inside [1, 10] | back |
| (4, 3) | [3, 4] before [5, 6] | cross |
| (5, 4) | [5, 6] before [8, 9] | cross |
| (6, 2) | [2, 7] before [11, 14] | cross |
| (6, 3) | [3, 4] before [11, 14] | cross |
This matches the lecture's colors: green tree edges, a blue forward edge (1, 3), a red back edge (4, 1) and pink cross edges (5, 4), (4, 3), (6, 2), (6, 3). Some cells worked out: (1, 3) has the tree-or-forward pattern, and since 3 was explored from 2 rather than from 1, it is forward. The edge (5, 4) runs between two different branches below 1, so it is cross, and cross edges between trees, like (6, 2), also count as cross.
Correctness
The test is correct because of the nesting fact from Section 3.3: v is a descendant of u in T exactly when Explore(v) started and finished during Explore(u), that is, when v's interval lies inside u's; and v is an ancestor of u exactly when u's interval lies inside v's. If neither holds the intervals are disjoint, and the order is forced: if u's interval came first, Explore(u) would have found v unvisited while scanning G[u] and explored it, making v a descendant. So for every edge, exactly one row of the table applies.
Running time
DFS takes O(m + n), and each of the m edges is classified with O(1) comparisons, for O(m + n) in total.
Check-in 3.4. For the graph of Check-in 3.3 (pre = [1, 2, 3, 6, 7, 11], post = [10, 5, 4, 9, 8, 12]), classify all eight edges (1, 2), (1, 4), (2, 3), (3, 1), (4, 3), (4, 5), (5, 2), (6, 5).
Answer
Tree: (1, 2), (2, 3), (1, 4), (4, 5). Back: (3, 1), since [3, 4] lies inside [1, 10]. Cross: (4, 3) ([3, 4] before [6, 9]), (5, 2) ([2, 5] before [7, 8]) and (6, 5) ([7, 8] before [11, 12]). No forward edges.3.5 Cycle finding
In plain words. A directed cycle is a route that follows arrows and comes back to where it started, such as a set of courses that are each other's prerequisites. To find one, run DFS and look for a back edge: an arrow from a vertex up to one of its ancestors in the DFS tree. The tree path from that ancestor down to the vertex, followed by the back edge itself, is a cycle. Conversely, every cycle forces DFS to produce a back edge, so if there is none, the graph has no cycle.
- Input: a directed graph G. Output: a directed cycle in G, or nothing if none exists.
- The lecture's idea in one line: "basically check for back edge".
- (u, v) is a back edge if and only if pre[v] < pre[u] < post[u] < post[v].
- Correctness has two directions: (1) if G has a cycle, the algorithm returns one; (2) if the algorithm returns something, it is a cycle (equivalently, no cycle ⇒ returns nothing).
- The key step of (1): the edge of the cycle pointing into the first cycle vertex DFS explores is a back edge.
- Running time O(m + n): DFS, O(1) per edge for the test, O(n) to read off the tree path.
Problem
The notes: "The input is a directed graph G. Our goal is to return a directed cycle in G (or nothing if none exists). Describe an O(m + n)-time algorithm for this problem, prove that it's correct, and analyze its running time." On the worksheet graph [[2, 3], [3, 4], [], [1, 3]], the back edge (4, 1) and the tree path 1, 2, 4 give the cycle 1 → 2 → 4 → 1. On [[2], [3], []] the answer is nothing.
Algorithm
"Run DFS(G) to obtain a DFS tree T. If there is a back edge (u, v), then find the v-u path P in T and return P + (u, v)." To find P, walk up from u through the tree parents until reaching v, then reverse; or run BFS from v inside T.
Find-Cycle(G):
T = DFS Tree from DFS(G)
for (u, v) in E:
if (u, v) is a back edge: # pre[v] < pre[u] < post[u] < post[v]
P = v-u path in T
return P + (u, v)
Trace on the lecture's seven-vertex example: with pre = [1, 2, 3, 5, 8, 11, 12] and post = [10, 7, 4, 6, 9, 14, 13], the scan of the edges finds (4, 1) with 1 < 5 < 6 < 10, so (4, 1) is a back edge. The tree path from 1 to 4 is 1, 2, 4 (tree edges (1, 2) and (2, 4)), and the algorithm returns the cycle 1 → 2 → 4 → 1. No other edge passes the test.
Correctness
The worksheet for Day 2/3, Problem 3, asks "What are the two statements we'd need to prove to show that Find-Cycle is correct?" The answer: for any directed graph G, "(1) if G has a cycle then Find-Cycle(G) returns a cycle, and (2) if G doesn't have a cycle then Find-Cycle(G) returns nothing." The solution adds that (2) "is equivalent to proving that if Find-Cycle(G) returns something, then G must have a cycle" (the contrapositive; the lecture writes p ⇒ q ⇔ ¬q ⇒ ¬p), which is easier to prove.
Statement (2), returned output is a cycle. "If (u, v) is a back edge, then (by definition) there exists a v-u path P in T, so P + (u, v) is a cycle in G." Every tree edge is an edge of G, so the walk from v down to u and back along (u, v) is a cycle.
Statement (1), every cycle produces a back edge. "Suppose G has a cycle C. Let v denote the first vertex in C explored by DFS and u denote the vertex preceding v in C. Then while exploring v we explore u, which results in (u, v) being a back edge." In more detail: when Explore(v) begins, every other vertex of C is unvisited, and they are all reachable from v along C, so by fact (3) of Section 3.3 all of them, u included, become descendants of v before Explore(v) finishes. Then (u, v) points from a descendant to its ancestor, which is a back edge, and the algorithm finds it (or another back edge) and returns a cycle. The lecture's red margin note says the same: "in-cycle edge pointing to first vertex explored in cycle will be a back edge".
Running time
"Running DFS and constructing T take O(m + n) time. Looking for a back edge takes O(1) time per edge. If we find one, we can compute P in O(n) time using BFS (or DFS) in T, since T only has n − 1 edges. Thus, the total running time is O(m + n)."
Variant. To test only whether a cycle exists, return True at the first back edge and False after the loop; the cost is still O(m + n). Undirected graphs need a different test and are not covered in the course's Chapter 2.
Check-in 3.5. Run Find-Cycle on G = [[2], [3, 4], [], [5], [2]]. Give pre and post, the back edge it finds, and the cycle it returns.
Answer
pre = [1, 2, 3, 5, 6], post = [10, 9, 4, 8, 7]. The only back edge is (5, 2), since 2 < 6 < 7 < 9. The tree path from 2 to 5 is 2, 4, 5, so the returned cycle is 2 → 4 → 5 → 2.3.6 Topological sort
In plain words. A directed acyclic graph (DAG) can always be laid out in a line so that every arrow points from left to right; such a line is a topological ordering, like an order in which to take courses so that prerequisites come first. Run DFS and list the vertices in order of decreasing post value: a vertex is finished only after everything it points to is finished, so it lands to the left of all of them. In practice the algorithm puts each vertex at the front of a list at the moment it receives its post value, which avoids sorting. If the graph has a cycle, no topological ordering exists.
- Input: a DAG G. Output: an ordering R of V such that for every (u, v) ∈ E, u appears before v in R.
- The idea (lecture): "DFS, sort V by decreasing post-value."
- The fact to prove: for every edge (u, v), post[u] > post[v]. Two cases: Explore(u) called before Explore(v), or Explore(v) called before Explore(u).
- Implementation: "When we set the post-value of any vertex u, we add u to the left end of a list R."
- Running time O(m + n), the same as DFS.
- Traps: increasing pre value is not a topological ordering, and neither is increasing post value. A DAG may have many topological orderings; the algorithm returns one.
Problem
The notes: "The input is a DAG G. Our goal is to return a topological ordering of G. Describe an O(m + n)-time algorithm for this problem, prove that it's correct, and analyze its running time." The notes first observe that a graph with a cycle has no topological ordering (the cycle's edges cannot all point right), which is why the input is assumed to be a DAG. Tiny instance from the 09-03 lecture: G = [[2, 3], [], []] (1 → 2, 1 → 3) has pre/post 1,6 / 2,3 / 4,5, and decreasing post gives [1, 3, 2]; [1, 2, 3] is also a valid ordering.
Algorithm
"Basically, we sort V in order of decreasing post value. But to avoid the need to describe an O(n)-time sorting algorithm, we run a slight modification of DFS on G: When we set the post-value of any vertex u, we add u to the left end of a list R (initially empty). At the end, we return R." Because post values are handed out in increasing order, the vertex finished last ends up leftmost.
Topological-Sort(G):
R = []
DFS(G)
# after post[u] = t,
# append u to the left end of R
return R
The lecture's example is the DAG with edges (4, 2), (4, 3), (4, 1), (2, 1), (3, 1), that is, G = [[], [1], [1], [1, 2, 3]].
| t | Event | R after |
|---|---|---|
| 1 | pre[1] = 1 (DFS starts at 1) | [ ] |
| 2 | post[1] = 2 (G[1] empty) | [1] |
| 3 | pre[2] = 3 (restart at 2) | [1] |
| 4 | post[2] = 4 (1 is visited) | [2, 1] |
| 5 | pre[3] = 5 (restart at 3) | [2, 1] |
| 6 | post[3] = 6 | [3, 2, 1] |
| 7 | pre[4] = 7 (restart at 4) | [3, 2, 1] |
| 8 | post[4] = 8 (1, 2, 3 all visited) | [4, 3, 2, 1] |
The algorithm returns R = [4, 3, 2, 1]. Some cells worked out: vertex 1 is a sink, so DFS starting at 1 finishes it immediately with post 2, and it ends up at the right end; vertex 4 is the only source and is finished last. The lecture draws the ordering 4, 2, 3, 1, which is equally valid: the DAG has exactly these two topological orderings, since 2 and 3 are not joined by an edge.
Correctness
The lecture states the goal as "WTS (want to show): ∀ edge (u, v): post[u] > post[v]"; once this holds, listing by decreasing post value puts u before v for every edge. The notes prove it in two cases. "Consider any edge (u, v). If the algorithm calls Explore(u) before calling Explore(v), then it in fact calls Explore(v) while exploring u since v is an out-neighbor of u, so post[u] > post[v]." (By the nesting fact, Explore(v) finishes before Explore(u) does.) "Now suppose the algorithm calls Explore(v) before calling Explore(u). Since G is a DAG and (u, v) ∈ E, u is not reachable from v, so the algorithm calls Explore(u) only after Explore(v) has terminated; this also implies post[u] > post[v]." In the lecture's words: "No v → u path in G because G is a DAG, so we'll finish exploring v before we start exploring u." The two cases are exhaustive, since one of the two calls comes first.
Running time
"Appending to a list takes O(1) time, so this algorithm has the same asymptotic running time as DFS, which is O(m + n)."
The consecutive-pair facts. Three of these problems rest on two observations about a topological ordering T. If (T[i], T[i + 1]) is not an edge, then neither of T[i] and T[i + 1] can reach the other: T[i + 1] cannot reach anything to its left, and every edge out of T[i] skips past T[i + 1] to the right, from where no edge comes back. Swapping the two then gives a second topological ordering. If every consecutive pair is an edge, then T is a path through all n vertices, every vertex reaches every later vertex, and T is the only topological ordering.
Check-in 3.6. Run Topological-Sort on G = [[2, 3], [4], [4, 5], [], []]. Fill in post, then write R.
| v | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| post | |||||
| R |
Answer
pre = [1, 2, 6, 3, 7] and post = [10, 5, 9, 4, 8]. Vertices finish in the order 4, 2, 5, 3, 1, each placed at the left end of R, so R = [1, 3, 5, 2, 4]. Check: every edge (1, 2), (1, 3), (2, 4), (3, 4), (3, 5) points left to right.3.7 Strongly connected components
In plain words. In a directed graph, two vertices belong to the same strongly connected component when each can reach the other; the components split the vertex set into groups of mutually reachable vertices. If you start a search inside a component that has no arrows leaving it (a "sink" component), the search reaches exactly that component, so you can label it and remove it. The trick is to find such a starting vertex: run DFS on the reversed graph and take the vertex with the largest post value. Repeating this, in decreasing post order, labels every component in O(m + n) time.
- Input: a directed graph G. Output: an array c with c[u] = c[v] exactly when u and v are in the same SCC.
- G is strongly connected if every u can reach every v. "The strongly connected components of G partition V", and G is a DAG if and only if every SCC is a single vertex.
- The component graph GSCC (one vertex per SCC, an edge A → B when some edge goes from A to B) is always a DAG. A sink SCC has no edges leaving it.
- The notes' observation: after DFS on any graph H, ordering the SCCs by their largest post value gives a topological ordering of HSCC. Applied to the reverse graph GR, the largest post value lies in a sink SCC of G.
- Algorithm: build GR, run DFS on it, then BFS in G from each unlabelled vertex in decreasing post order, labelling everything newly reached with a new number.
- Running time O(m + n). SCC is not in the cover page's list of algorithms you may call by name, so if you use it on the exam, describe it.
Problem
The notes: "The input is a directed graph G. Our goal is to return an array c such that for all u, v ∈ V, u and v are in the same SCC if and only if c[u] = c[v]. Describe an O(m + n)-time algorithm for this problem, prove that it's correct, and analyze its running time." The worksheet for Day 3/3, Problem 3, asks: "What is the output of the SCC algorithm on G = [[2], [3, 4], [1, 5], [5], []]?" Official answer: c = [3, 3, 3, 2, 1].
Algorithm
"Construct the reverse graph GR of G by reversing every edge (i.e., (u, v) in G becomes (v, u) in GR). Run DFS on GR to obtain post[u] for all u ∈ V. Then, from each u ∈ V in order of decreasing post[u], run BFS to find the vertices reachable from u in G and label these as a strongly connected component." Vertices that already have a label are skipped, both as starting points and inside the BFS.
SCC(G):
G^R = reverse of G
pre, post = DFS(G^R)
c, k = [∞]*n, 1
for u in V in order of decreasing post[u]:
if c[u] = ∞:
BFS(G, u); k += 1
# set c[v] = k for every vertex v
# such that c[v] = ∞ and
# v is reachable from u
return c
The lecture's example (09-03) is exactly the worksheet graph: edges (1, 2), (2, 3), (3, 1), (2, 4), (3, 5), (4, 5). Its reverse GR has edges (2, 1), (3, 2), (1, 3), (4, 2), (5, 3), (5, 4), that is, GR = [[3], [1], [2], [2], [3, 4]].
| Phase | Work | Result |
|---|---|---|
| DFS on GR | pre1 = 1, pre3 = 2 (GR[1] = [3]), pre2 = 3 (GR[3] = [2]), post2 = 4 (1 visited), post3 = 5, post1 = 6; restart pre4 = 7, post4 = 8 (2 visited); restart pre5 = 9, post5 = 10 | post = [6, 4, 5, 8, 10] |
| Order | decreasing post | 5, 4, 1, 3, 2 |
| u = 5 | BFS in G from 5 reaches only 5 (G[5] empty) | c[5] = 1 |
| u = 4 | BFS in G from 4: 5 is labelled, so only 4 | c[4] = 2 |
| u = 1 | BFS in G from 1 reaches 2, 3 (4 and 5 labelled) | c[1] = c[2] = c[3] = 3 |
| u = 3, 2 | already labelled, skipped | c = [3, 3, 3, 2, 1] |
The post values (1,6 / 3,4 / 2,5 / 7,8 / 9,10 for vertices 1 to 5) are the ones the lecture writes beside GR, and the official worksheet solution says the same: "The post-values in the reverse of G are [6, 4, 5, 8, 10], so we BFS in G from vertex 5, then 4, then 1." Some cells worked out: {5} is a sink SCC of G (no edge leaves 5), and it is labelled first; once 5 is labelled, {4} becomes a sink among what remains; finally the cycle {1, 2, 3} is labelled.
Correctness
The notes' argument has three steps. (1) Sink SCCs are safe starting points. If u lies in a sink SCC C of G, the vertices reachable from u are exactly C: everything in C is reachable, and no edge leaves C. So "ideally, we could run BFS on (G, u) where u is in a sink SCC and label all vertices reached from u as an SCC. Unfortunately, finding a vertex in a sink SCC is not straightforward." (2) Post values order the components. "Suppose we run DFS on any directed graph H and set post[C] = maxu ∈ C post[u] for every SCC C of H. Then if we order the SCCs by their decreasing post-values, the result is a topological ordering of HSCC. (The proof is similar to, and generalizes, the one in the previous section.)" (3) Reversal turns sources into sinks. GR has the same SCCs as G with every component edge reversed, so a topological order of GRSCC is a reverse topological order of GSCC. "Thus, the SCC algorithm processes GRSCC in topological order, which is equivalent to processing GSCC in reverse topological order. So each time the algorithm calls BFS, it labels the vertices of some sink SCC of G" (sink among the vertices not yet labelled, since edges into labelled components are ignored).
Running time
"Constructing GR and running DFS takes O(m + n) time. We then run BFS from one vertex u per SCC; notice that this run of BFS only processes vertices that are reachable from u and haven't been processed before. By ignoring vertices that have already been labeled (i.e., only adding newly labeled vertices to the queue), we obtain a total running time of O(m + n)." Building GR takes one pass over the lists: for each u and each v in G[u], append u to GR[v].
Check-in 3.7. Run the SCC algorithm on G = [[2], [3], [1, 4], [5], [6], [4]]. Give GR, the post values of DFS on GR, the BFS order, and c.
Answer
GR = [[3], [1], [2], [3, 6], [4], [5]]. DFS on GR: pre1 = 1, pre3 = 2, pre2 = 3, post2 = 4, post3 = 5, post1 = 6, pre4 = 7, pre6 = 8, pre5 = 9, post5 = 10, post6 = 11, post4 = 12, so post = [6, 4, 5, 12, 10, 11]. Decreasing post: 4, 6, 5, 1, 3, 2. BFS in G from 4 reaches 4, 5, 6 (label 1); BFS from 1 reaches 1, 2, 3 (label 2). c = [2, 2, 2, 1, 1, 1].3.8 Worked problems from Problem Set 2
Problem Set 2 supplied two problems to the midterm-1 exams: Midterm 1's Problem 2 is PS 2.1 (apart from the symbol D), Practice Midterm 1's Problem 3 is PS 2.3 word for word, and the final promises that at least two of Problems 3 to 8 are identical to problem-set problems. The statements below are copied verbatim from the course page; the solutions follow the official ones, expanded and laid out as Algorithm, Correctness, Running time.
PS 2.1. Diameter of a connected graph
Solution
Algorithm. The official solution: "Brute force is sufficient: we can run BFS from every vertex and keep track of the maximum distance."
ALG(G):
diam = 0
for each vertex u:
d = BFS(G, u)
diam = max(diam, max(d))
return diam
Example: on the path with edges {1, 2}, {2, 3}, {3, 4}, BFS from 1 gives d = [0, 1, 2, 3], so diam becomes 3, and no other start vertex gives more; the algorithm returns 3.
Correctness. "When we run BFS from u, we can find the farthest distance from u, so running BFS from every vertex suffices." BFS from u returns d(u, v) for every v (Section 3.2), so max(d) = maxv d(u, v), and the maximum of these over all u is maxu,v d(u, v) = D. Because G is connected, no entry of d is ∞.
Running time. "The algorithm makes exactly n iterations (one per vertex), and each iteration takes O(m + n) = O(m) time (since G is connected)." A connected graph has m ≥ n − 1, so n = O(m). Computing max(d) is O(n). "So the total running time is n · O(m) = O(mn)."
Pattern: all-pairs information from n calls of BFS; "connected" is what turns O(m + n) into O(m).
PS 2.2. Two vertices that cannot reach each other
Solution
Algorithm. "Let T be a topological ordering of V. If there exists i such that (T[i], T[i + 1]) ∉ E, then return (T[i], T[i + 1]); otherwise, return nothing." The lecture first dismisses brute force ("for each pair (s, t), check if s cannot reach t and t cannot reach s using 2 BFS's", O(n²(m + n))) and then gives the hint "whenever input is a DAG, topo sort is usually helpful".
ALG(G):
T = topological ordering of V # Topological-Sort(G)
for i = 1, ..., n-1:
if (T[i], T[i+1]) not in E: # T[i+1] not in G[T[i]]
return (T[i], T[i+1])
Example: the lecture's DAG has topological ordering T = [5, 1, 4, 3, 2] in which (1, 4) is not an edge, so the algorithm returns (1, 4).
Correctness. Two directions. What is returned is valid. "Suppose the algorithm returns (T[i], T[i + 1]). Then T[i] cannot reach T[i + 1] because each edge leaving T[i] points to some vertex T[j] where j > i + 1, and no edges point backward. Similarly, T[i + 1] cannot reach T[i]" (every edge out of T[i + 1] points further right). If nothing is returned, no valid pair exists. "If (T[i], T[i + 1]) ∈ E for all i ∈ {1, …, n − 1}, then for any pair of vertices (T[i], T[j]) where i < j, T[i] can reach T[j] by following these edges."
Running time. "Topologically ordering V takes O(m + n) time, and we can find any missing edge (T[i], T[i + 1]) in O(m + n) time. Note that for each vertex u, we scan the list G[u] at most once, so the total running time of scanning the n − 1 lists is O(m + n) (similar to BFS)." The lecture's margin note: "because we scan each list ≤ once".
Pattern: DAG ⇒ topologically sort, then look at consecutive pairs.
PS 2.3. Connected component labels
Solution
Algorithm. "We run a wrapper around BFS (similar to how DFS is a wrapper around Explore) and populate c, and whenever we 'restart' from a new starting vertex, we increment the connected component number."
ALG(G):
c, cc_num = [0]*n, 1
for each vertex u:
if c[u] = 0:
BFS(G, u) # when processing any vertex v (including u), set c[v] = cc_num
cc_num += 1
return c
Example: n = 5 with edges {1, 3}, {2, 4}, {3, 5}. From u = 1, BFS labels 1, 3, 5 with 1; u = 2 is unlabelled, so BFS labels 2, 4 with 2; c = [1, 2, 1, 2, 1].
Correctness. (Not asked for, but short.) In an undirected graph, BFS from u reaches exactly the vertices of u's connected component, so each component gets one number. The next unlabelled vertex lies in a component not yet visited, and cc_num has been incremented, so different components get different numbers.
Running time. The naive bound is "n · O(m + n) = O(mn + n²) since the algorithm makes n iterations and each iteration takes O(m + n) time. However, notice that the algorithm calls BFS only once per component of G. If a component has a vertices and b edges, then running BFS on that component only takes O(a + b) time. So the total running time is the sum of these BFS calls across all components, which is O(m + n)." The loop's own checks of c[u] add O(n).
Pattern: a wrapper that restarts a search from each unvisited vertex; charge each search only to the part of the graph it touches.
PS 2.4. Bipartite test
Solution
Algorithm. "We essentially BFS from vertex 1 (arbitrarily starting with c[1] = 0), and whenever we process a vertex u, we color its uncolored neighbors using 1 − c[u] and check that none of its other neighbors had been colored c[u]."
ALG(G):
c = [∞]*n; c[1] = 0
Q = queue(1)
while |Q| >= 1:
u = dequeue from Q
for v in G[u]:
if c[v] = ∞:
c[v] = 1 - c[u]
add v to Q
else if c[v] = c[u]:
return
return c
Examples: on the 4-cycle with edges {1, 2}, {2, 3}, {3, 4}, {4, 1}, vertex 1 colors 2 and 4 with 1, then 2 colors 3 with 0, and every check passes: c = [0, 1, 0, 1]. On the triangle {1, 2}, {2, 3}, {1, 3}, vertex 1 colors 2 and 3 with 1; processing 2 finds its neighbor 3 already colored 1 = c[2], so the algorithm returns nothing.
Correctness. Two directions. Returning nothing is right. "If ALG returns nothing, then it must have set c[v] = c[u] for some edge {u, v}. But c[v] = 1 − c[u] is the only possible color for v, so if c[v] = c[u] for some edge {u, v}, then the graph cannot be bipartite." (Once c[1] = 0 is fixed, and swapping the two colors of a valid coloring gives another valid coloring, every color BFS writes is forced along the BFS tree.) A returned c is valid. "For any edge {u, v}, if we let u denote the vertex that was processed first, then when ALG processed u, it either set c[v] = 1 − c[u] or checked that c[v] ≠ c[u] (since we're assuming that ALG returns c). Either way, c[v] ≠ c[u], as desired." Since G is connected, every vertex receives a color.
Running time. "The running time analysis is the same as the one for BFS: processing u takes O(out-deg(u)), so the total running time is O(m + n)."
Pattern: a slightly modified BFS that writes something other than a distance; prove "returns nothing ⇒ none exists" and "returns c ⇒ c is valid".
PS 2.5. Is the topological order unique?
Solution
Algorithm. "(This solution is similar to the one to Problem 2.2.) Let T be a topological ordering of V. If there exists i such that (T[i], T[i + 1]) ∉ E, then return True; otherwise, return False."
ALG(G):
T = topological ordering of V
for i = 1, ..., n-1:
if (T[i], T[i+1]) not in E:
return True
return False
Examples: for G = [[2, 3], [], [2]], Topological-Sort gives T = [1, 3, 2]; (1, 3) and (3, 2) are both edges, so the algorithm returns False (1, 3, 2 is the only order). For G = [[2, 3], [], []], T = [1, 3, 2] and (3, 2) is not an edge, so it returns True (1, 2, 3 also works).
Correctness. "If some (T[i], T[i + 1]) is not in E, then we can swap vertices T[i] and T[i + 1] to obtain a different topological order (since every edge would still point from left to right)." No edge joins the two swapped vertices, and every other pair keeps its relative order. "Otherwise, if every (T[i], T[i + 1]) is in E, then T is the only topological order of G because the path (T[1], T[2], …, T[n]) forces every vertex in G to appear in the same order as T."
Running time. Topological-Sort is O(m + n), and checking each consecutive pair scans the list G[T[i]] once; each list is scanned at most once, so the loop is O(m + n) and the total is O(m + n).
Pattern: the same consecutive-pair scan as PS 2.2, with a different conclusion.
3.9 Homework-style one-point questions
Homework 2 was auto-graded and had three question types, each first shown on a small example and then repeated on a large random graph (40 to 60 vertices). The small versions are exactly the Problem 1 traces of the exams; the large versions are meant to be done with code, and the 09-03 lecture's purple note recommends: "write code in Python or Java without AI".
Type 1: the BFS d array. The homework's warm-up: "Suppose we run BFS on the following graph from vertex 1: G = [[2, 4], [], [1, 2], [3], []]. The final values of d are [0, 1, 2, 1, inf], and the final values of d[1:3] are [0, 1, 2]." (In the homework, d[1:3] means d[1] through d[3].) The first question uses G = [[3], [1], [4], [1, 2]]: vertex 1 discovers 3 (d = 1); 3 discovers 4 (d = 2); 4 scans 1 (seen) and discovers 2 (d = 3). So d = [0, 3, 1, 2] and the accepted answer for d[1:3] is [0, 3, 1]. The large versions had accepted answers such as [0, 5, 8, 7, 4, 7, 8, 9, 3, inf] for d[1:10], with "inf" for an unreachable vertex.
Type 2: DFS pre and post. The warm-up on the same five-vertex graph gives pre = [1, 2, 5, 4, 9] and post = [8, 3, 6, 7, 10] (note the restart at vertex 5). On G = [[3], [1], [4], [1, 2]] the trace is pre1 = 1, pre3 = 2, pre4 = 3, then G[4] = [1, 2]: 1 is on the stack, 2 is new, pre2 = 4; G[2] = [1] is visited, so post2 = 5, post4 = 6, post3 = 7, post1 = 8. Accepted answers: pre = [1, 4, 2, 3], post = [8, 5, 7, 6].
| v | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| pre | 1 | 4 | 2 | 3 |
| post | 8 | 5 | 7 | 6 |
Type 3: counting back edges. "How many back edges are there?" on the 40-vertex graph had the accepted answer 84. By hand the method is the test of Section 3.4 applied to every edge: (u, v) is back exactly when pre[v] < pre[u] < post[u] < post[v]. On the small graph [[3], [1], [4], [1, 2]] the back edges are (2, 1) and (4, 1), so the count is 2; the tree edges are (1, 3), (3, 4), (4, 2).
Check-in 3.8. Homework-style: run DFS on G = [[2, 3], [4], [2], [1], [4]]. Fill in pre and post and state how many back edges there are.
| v | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| pre | |||||
| post |
Answer
pre = [1, 2, 6, 3, 9], post = [8, 5, 7, 4, 10]. There is 1 back edge, (4, 1). The tree edges are (1, 2), (2, 4), (1, 3); the cross edges are (3, 2) and (5, 4).3.10 Past exam problems on this chapter
Every graph question from Midterm 1, Practice Midterm 1 and the Practice Final that belongs to this chapter is below, with its official answer. The one-point parts carry "Do not explain your answers … (1p each, no partial credit)"; the five-point problems are graded on the Algorithm, Correctness and Running time paragraphs.
Midterm 1, Problem 1 (b)–(e)
The parts refer to the graph below, G = [[2, 4], [3, 4], [5], [3, 5], []].
Solution
[0, 1, 2, 1, 2]. Vertex 1 discovers 2 and 4 (d = 1); 2 discovers 3 (d = 2); 4 discovers 5 (d = 2).Solution
[10, 9, 6, 8, 5]. Trace: pre1 = 1, pre2 = 2, pre3 = 3, pre5 = 4, post5 = 5, post3 = 6, back in G[2]: pre4 = 7 (G[4] = [3, 5], both visited), post4 = 8, post2 = 9, post1 = 10 (4 visited). pre = [1, 2, 3, 7, 4].Solution
none. No edge points to an ancestor; consistently, the graph is a DAG.Solution
(4, 3), (4, 5). Their heads have intervals [3, 6] and [4, 5], both before 4's interval [7, 8]. The tree edges are (1, 2), (2, 3), (3, 5), (2, 4), and (1, 4) is forward.Midterm 1, Problem 2 (= PS 2.1)
Solution
The official solution: "This is Problem 2.1 from Problem Set 2." Algorithm. For each vertex u, run BFS(G, u) and keep the largest entry of d seen so far; return it.
ALG(G):
diam = 0
for each vertex u:
d = BFS(G, u)
diam = max(diam, max(d))
return diam
Correctness. BFS from u computes d(u, v) for every v, so max(d) is the largest distance from u; taking the maximum over all u gives maxu,v d(u, v) = D. Running time. n iterations, each O(m + n) = O(m) because G is connected (m ≥ n − 1), so O(mn) in total.
Midterm 1, Problem 4. A vertex that reaches everything
Solution
Algorithm. "Let R = [R[1], …, R[n]] be a topological ordering of G. If R[1] can reach every vertex, we return it; otherwise, we return nothing."
ALG(G):
R = topological-ordering(G)
d = BFS(G, R[1])
if infinity not in d: # check if R[1] can reach every vertex
return R[1]
On the examples: for [[2, 3], [], [2]], R = [1, 3, 2] and BFS from 1 reaches everything, so the answer is 1. For [[2], [], [2]], R = [3, 1, 2] and BFS from 3 reaches only 3 and 2, so the answer is nothing.
Correctness. "If the algorithm returns R[1], then R[1] can reach every vertex and the algorithm is correct. Otherwise, we need to show that no vertex can reach every vertex in G. In this case, R[1] cannot reach every vertex in G, and every other vertex is R[i] for some i > 1. Since R is a topological ordering, there are no edges from R[i] to any vertex left of R[i], so no R[i] can reach any vertex before it in R." In particular no R[i] with i > 1 reaches R[1].
Running time. "Topologically ordering G and running BFS both take O(m + n) time, and scanning d takes O(n) time, so the total running time is O(m + n)."
The official solution warns: "One common mistake was checking if (T[i], T[i + 1]) ∈ E for all i ∈ {1, …, n − 1}. This is not correct, because it's possible that none of the (T[i], T[i + 1]) edges exist, yet T[1] can reach every vertex by a single edge." For example, in G = [[2, 3], [], []] vertex 1 reaches everything, but the topological ordering [1, 3, 2] has no edge (3, 2).
Practice Midterm 1, Problem 1 (b)–(e)
The parts refer to the graph below, G = [[4], [1, 3, 4], [5], [5], [2]].
Solution
d = [0, 3, 4, 1, 2]. The graph forces a single chain: 1 → 4 (d = 1), 4 → 5 (d = 2), 5 → 2 (d = 3), 2 → 3 (d = 4).Solution
post = [10, 7, 6, 9, 8]. Trace: pre1 = 1, pre4 = 2, pre5 = 3, pre2 = 4; G[2] = [1, 3, 4]: 1 visited, pre3 = 5; G[3] = [5] visited, post3 = 6; 4 visited, post2 = 7, post5 = 8, post4 = 9, post1 = 10. pre = [1, 4, 5, 2, 3].Solution
(2, 1), (2, 4), (3, 5). The DFS tree is the chain 1 → 4 → 5 → 2 → 3, and each of these edges points from a vertex up to an ancestor on that chain.Solution
none. The tree is a single chain through all five vertices, so every vertex is an ancestor or descendant of every other and no edge can be cross.Practice Midterm 1, Problem 3 (= PS 2.3)
Solution
The official solution: "This is Problem 2.3 from Problem Set 2." Algorithm. Loop over the vertices; from each unlabelled u, run BFS and give every vertex it reaches the current label, then increase the label.
ALG(G):
c, cc_num = [0]*n, 1
for each vertex u:
if c[u] = 0:
BFS(G, u) # when processing any vertex v (including u), set c[v] = cc_num
cc_num += 1
return c
Correctness. BFS from u reaches exactly u's component, so each component gets one label and later components get new ones. Running time. BFS is called once per component, and on a component with a vertices and b edges it costs O(a + b); summing over the components gives O(m + n), plus O(n) for the loop.
Practice Midterm 1, Problem 4. A path through every vertex of a DAG
Solution
Algorithm. "Let R = [R[1], …, R[n]] be a topological ordering of G. If (R[i], R[i + 1]) ∈ E for all i ∈ {1, …, n − 1}, return R; else, return nothing."
ALG(G):
R = topological-ordering(G)
for i = 1, ..., n-1:
if R[i+1] not in G[R[i]]: # check if (R[i], R[i+1]) is an edge
return
return R
Correctness. "If every (R[i], R[i + 1]) ∈ E, then R visits every vertex exactly once. Otherwise, we claim that no such path exists. For contradiction, suppose P is a path in G that visits every vertex exactly once. Since G is a DAG, we can topologically order G. In fact, this ordering must be equal to P, because otherwise, there would be an edge in P pointing in the opposite direction of the ordering. Therefore, the algorithm will find (and return) R = P."
Running time. "We can topologically order a DAG in O(m + n) time using the algorithm from the notes. Checking if (R[i], R[i + 1]) ∈ E requires scanning the list G[R[i]], which takes O(out-deg(R[i])) time. Since we scan every list at most once, the total running time of scanning all of the lists is also O(m + n)."
Practice Final, Problem 1 (b)
The graph is shared with parts (a) and (c), whose edge numbers are capacities and weights; DFS ignores them. As an adjacency list, G = [[2, 3], [3, 4], [4], []].
Solution
[8, 7, 6, 5]. Trace: pre1 = 1, pre2 = 2 (smallest out-neighbor of 1), pre3 = 3 (G[2] = [3, 4]), pre4 = 4 (G[3] = [4]), post4 = 5, post3 = 6, post2 = 7 (4 visited), post1 = 8 (3 visited). The DFS tree is the path 1 → 2 → 3 → 4, and (1, 3), (2, 4) are forward edges. This matches the official answer.Before moving on
- I can run BFS by hand with smallest-label tie-breaking and write the d array, the BFS tree edges in order, and ∞ for unreachable vertices.
- I can run DFS by hand, including restarts, and write pre and post with the clock ticking on both stamps.
- I can classify every edge as tree, forward, back or cross from the pre/post intervals.
- I can state Find-Cycle and prove both directions of its correctness.
- I can state Topological-Sort, prove post[u] > post[v] for every edge in two cases, and use the consecutive-pair facts on a DAG.
- I can run the SCC algorithm (DFS on GR, BFS on G in decreasing post order) and explain why it labels sink components first.
Exercises
Solution
d = [0, 2, 1, 3, 4]. 1 discovers 3 (d = 1); 3 discovers 2 (d = 2); 2 scans 1 (seen) and discovers 4 (d = 3); 4 discovers 5 (d = 4). Dequeue order 1, 3, 2, 4, 5; tree edges (1, 3), (3, 2), (2, 4), (4, 5).Solution
post = [10, 5, 9, 4, 8, 12] (pre = [1, 2, 6, 3, 7, 11]). Trace: pre1 = 1, pre2 = 2, pre4 = 3, G[4] = [1] is on the stack, post4 = 4, post2 = 5; back in G[1]: pre3 = 6, G[3] = [2, 5]: 2 visited, pre5 = 7, post5 = 8, post3 = 9, post1 = 10; restart at 6: pre6 = 11, both out-neighbors visited, post6 = 12.Solution
Back: (4, 1) (its interval [3, 4] lies inside 1's [1, 10]). Cross: (3, 2), (6, 3), (6, 5). The tree edges are (1, 2), (2, 4), (1, 3), (3, 5), and there are no forward edges.Solution
R = [5, 2, 1, 3, 4]. Trace: pre1 = 1, pre3 = 2, pre4 = 3, post4 = 4, post3 = 5, post1 = 6; restart pre2 = 7, post2 = 8 (1 and 4 visited); restart pre5 = 9, post5 = 10. Vertices finish in the order 4, 3, 1, 2, 5, each placed at the left end. Check: (5, 1), (5, 2), (2, 1), (2, 4), (1, 3), (3, 4) all point right.Solution
False. In G = [[2], []] (the single edge (1, 2)), DFS gives pre = [1, 2] and post = [4, 3]. Increasing post order is [2, 1], in which (1, 2) points from right to left. The correct rule is decreasing post order, which gives [1, 2].Solution
The argument proves only that whatever the algorithm returns is a cycle. It never shows that the algorithm returns something whenever G has a cycle, i.e., that every cycle produces a back edge. The missing half: let v be the first vertex of a cycle C explored by DFS and u its predecessor on C; when Explore(v) starts, the rest of C is unvisited and reachable from v, so u becomes a descendant of v, and (u, v) is a back edge. Both directions are needed for full credit.Solution
Algorithm. Run BFS from s in G and BFS from s in the reverse graph GR; return the vertices that both searches reach.
ALG(G, s):
d1 = BFS(G, s)
G^R = reverse of G # for u in V: for v in G[u]: append u to G^R[v]
d2 = BFS(G^R, s)
S = []
for v in V:
if d1[v] < ∞ and d2[v] < ∞: append v to S
return S
Correctness. d1[v] < ∞ exactly when s can reach v in G (BFS correctness). A path from v to s in G, with every edge reversed, is a path from s to v in GR, and conversely, so d2[v] < ∞ exactly when v can reach s in G. Hence v is returned if and only if s reaches v and v reaches s. Example: for G = [[2], [3], [1, 4], [5], [6], [4]] and s = 1, BFS in G reaches all six vertices and BFS in GR reaches {1, 2, 3}, so the answer is [1, 2, 3].
Running time. Each BFS is O(m + n); building GR scans every list once, O(m + n); the final loop is O(n). Total O(m + n).
Solution
Algorithm. Run DFS and let u be the vertex with the largest post value (the root of the last tree DFS starts). Run BFS from u; if no entry of d is ∞, return u, otherwise return nothing.
ALG(G):
pre, post = DFS(G)
u = vertex with the largest post value
d = BFS(G, u)
if infinity not in d:
return u
Example: G = [[2], [3], [1], [3], [4]] gives post = [6, 5, 4, 8, 10]; u = 5, and BFS from 5 reaches 4, 3, 1, 2, so the algorithm returns 5.
Correctness. If u is returned, it reaches every vertex. Otherwise we show that no vertex r reaches every vertex. Suppose some r does. Let w be the root of the DFS tree containing r. If w ≠ u, then w's tree was finished before Explore(u) began, and u was unvisited at that time. Follow a path from r to u: r is visited when w's tree finishes and u is not, so some edge (y, x) on the path has y visited and x unvisited when w's tree finishes; but Explore(y) finished during w's tree, and by then every out-neighbor of y, including x, had been visited. This contradiction shows r is in u's tree, so u reaches r, and r reaches everything, so u reaches every vertex and BFS from u would have found no ∞. Hence returning nothing is correct.
Running time. DFS is O(m + n), finding the largest post value is O(n), BFS is O(m + n), and scanning d is O(n): O(m + n) in total. (On a DAG, u is the first vertex of the Topological-Sort output, and this reduces to Midterm 1's Problem 4.)
Course Ch. 3 · Sep 8–154. Greedy algorithms
This chapter covers course Chapter 3, taught in three lectures on September 8, 10 and 15. The course notes define the subject in one sentence: an algorithm is "greedy" if it "constructs a solution by repeatedly choosing the option that appears to make the 'most progress' toward an optimal solution, without consideration for how this decision affects the set of available future decisions." Greedy algorithms are short to write down, usually a sort followed by one pass, and the hard part is the proof that the short rule is really optimal. The chapter works through the course's examples in order: Max k-Sum (the first exchange argument), the Minimum Spanning Tree problem with the Cut Property and three algorithms (Prim, Kruskal, Reverse-Delete with the Cycle Property), Selecting Compatible Intervals, and Fractional Knapsack. On the final, this material feeds two kinds of points: one-point traces in Problems 1–2 (the Practice Final asked for the order of Prim's edges and for the Fractional Knapsack array x) and five-point design problems in Problems 3–8 (the Practice Final's Problem 6 is an MST problem, and Problem Set 3's problems are candidates for the "identical to a problem set" slots). Every greedy algorithm in this course is proved correct the same way: assume an optimal solution differs from the greedy one, exchange one piece of it for the greedy choice, and show the result is still feasible and no worse.
4.1 Max k-Sum and the exchange argument
In plain words. A greedy algorithm builds its answer one choice at a time, always taking the option that looks best right now and never taking it back. Many such rules are wrong, so in this course a greedy algorithm is only worth as much as its proof, and the proof is almost always an exchange argument. The first example, Max k-Sum, asks for k numbers from an array with the largest possible sum, and the obvious answer (take the k largest) is correct. Its proof is short enough that the three steps of an exchange argument can be seen clearly before they are reused for spanning trees, intervals and knapsacks.
- Input: (A, k), an array A of n distinct integers and a positive integer k ≤ n. Output: k distinct integers of A whose sum is as large as possible.
- Algorithm: sort A in decreasing order and return A[1 : k].
- The exchange argument, in the three steps the lecture numbered: (1) for contradiction, assume OPT ≠ ALG; (2) construct OPT′ by exchanging something in OPT for something in ALG; (3) show that OPT′ is feasible and "better" (or at least as good) than OPT.
- The exchange here: OPT must leave out some A[i] with i ≤ k and include some A[j] with j > k; swap A[j] out and A[i] in.
- The inequality that finishes the proof: A[i] > A[j], because A is sorted in decreasing order and i ≤ k < j.
- Running time O(n log n), all of it for sorting.
- Trap: writing "OPT′ is better" without saying why OPT′ is feasible and which inequality makes it better; those two sentences are the points.
Problem
The course notes state it as follows. Problem (3.1, Max k-Sum). "The input is (A, k), where A is an array of n distinct integers and k is a positive integer at most n, and our goal is to return an array of exactly k distinct integers in A such that the sum of the array is maximized." The lecture's example is A = [4, 5, 1, 7, 2] with k = 3. Sorting gives [7, 5, 4, 2, 1], and the answer is [7, 5, 4], with sum 16.
Algorithm
Sort A from largest to smallest, so that A[1] is the largest element and A[n] the smallest. The first k positions now hold the k largest elements, and the algorithm returns them. In the course's pseudocode:
ALG(A, k):
sort A in decreasing order
return A[1:k]
The trace on the lecture's example has only two steps, but the second table shows the exchange itself on a concrete non-optimal solution, which is the picture the lecture drew with the highlighted A[i] and A[j].
| Step | A | Returned | Sum |
|---|---|---|---|
| input | [4, 5, 1, 7, 2] | ||
| sort decreasing | [7, 5, 4, 2, 1] | [7, 5, 4] | 16 |
| Solution | Elements | Sum | What happened |
|---|---|---|---|
| OPT (a hypothetical rival) | {7, 4, 2} | 13 | excludes A[2] = 5 (i = 2 ≤ k) and includes A[4] = 2 (j = 4 > k) |
| OPT′ = OPT − A[4] + A[2] | {7, 5, 4} | 16 | still 3 elements; sum went up by A[2] − A[4] = 3 |
Some cells worked out: in the sorted array the first three positions hold 7, 5, 4, so any 3-element set other than {7, 5, 4} must miss one of these three and must, to have 3 elements, use one of 2 or 1 instead. The rival {7, 4, 2} misses 5 and uses 2, and swapping them raises the sum by 5 − 2 = 3.
Correctness
The technique is the exchange argument. The notes' proof (repeated in more detail in Problem Set 3) runs as follows. After sorting, we want to show that an optimal solution OPT equals A[1 : k]. Step 1. For contradiction, suppose OPT ≠ A[1 : k]. Step 2. Then OPT excludes some number A[i] in A[1 : k] and, since |OPT| = k, includes some number A[j] with j > k. Let OPT′ be OPT with A[j] removed and A[i] added. Step 3. OPT′ is feasible because it still has exactly k distinct elements of A. Writing v(B) for the sum of an array B, v(OPT′) = v(OPT) − A[j] + A[i] > v(OPT), because A[j] < A[i] (A is sorted in decreasing order and j > k ≥ i). So OPT′ is a feasible solution with a larger sum than OPT, which contradicts the optimality of OPT. Hence OPT = A[1 : k].
Running time
Sorting takes O(n log n) time (Merge-Sort, Chapter 2), and copying the first k elements takes O(k) = O(n) time, so the total is O(n log n).
Variant: the cashier (lecture of September 8). The lecture's second example is the waiting-time problem that became Problem 3.2. Jobs with processing times A = [4, 1, 2] wait for the cashier one after another; in the given order the waiting times are 0 + 4 + 5 = 9, in the order [1, 4, 2] they are 0 + 1 + 5 = 6, and in increasing order [1, 2, 4] they are 0 + 1 + 3 = 4, the minimum. The exchange is a swap of two neighbours: if a job of length 7 sits right before a job of length 4, swapping them leaves everyone else's wait unchanged, makes the 4-job wait 7 less and the 7-job wait 4 more, a net decrease of 3. The lecture also drew the non-adjacent case: with jobs of total length λ between them, the 4-job waits 7 + λ less, the 7-job waits 4 + λ more, and each job in between waits 3 less, so the total drops by at least 3.
Check-in 4.1. Let A = [6, 2, 9, 4, 7] and k = 2. Write what the algorithm returns. Then suppose a rival solution is OPT = {9, 4}: name the A[i] it excludes and the A[j] it includes (indices in the sorted array), write OPT′ and say by how much the sum increases.
Answer
Sorted, A = [9, 7, 6, 4, 2], and the algorithm returns [9, 7] with sum 16. OPT = {9, 4} excludes A[2] = 7 (i = 2 ≤ k) and includes A[4] = 4 (j = 4 > k). OPT′ = {9, 7}, which still has 2 elements, and its sum is larger by 7 − 4 = 3 (13 → 16).4.2 Minimum spanning trees and the Cut Property
In plain words. The lecture's story is connecting houses with cables at minimum cost: every house must be reachable from every other, and each possible cable has a price. A spanning tree is a set of edges that just barely connects all the vertices, and a minimum spanning tree is the cheapest such set. All three MST algorithms of the course rest on one fact, the Cut Property: whenever the vertices are split into two groups, the cheapest edge between the two groups must be in the MST. The fact is proved by the exchange argument of Section 4.1, applied to a cycle.
- Input: a connected, undirected graph G = (V, E) in which every edge e has a distinct integer weight w(e). Output: the minimum spanning tree, usually returned as a list F of its edges.
- A spanning tree of G uses edges of G, reaches every vertex, has n − 1 edges and no cycle; the lecture notes that any two of "n − 1 edges", "connected", "acyclic" imply the third.
- With distinct weights there is exactly one MST, so the course says "the MST".
- A cut is a subset S of V; an edge crosses S if it has exactly one endpoint in S.
- Cut Property: for any cut S in G, the lightest edge crossing S is in the MST of G.
- Proof idea: if the lightest crossing edge e were missing from the MST T, then T + e has a cycle, the cycle crosses S a second time at some f, and T + e − f is a lighter spanning tree.
- Trap: f must be an edge of that cycle. Swapping out an arbitrary crossing edge of T can disconnect the tree (worksheet of September 8).
Problem
Problem (3.2, Minimum Spanning Tree). The notes define: "A spanning tree of an undirected graph G = (V, E) is a graph T = (V, F) such that F ⊆ E and T is connected; T is a minimum spanning tree (MST) if Σe∈F w(e) is as small as possible." The problem: "The input is a connected, undirected graph G = (V, E) where each edge e has a distinct weight w(e) ∈ ℤ. Our goal is to return a minimum spanning tree of G. Describe an O(m²)-time algorithm for this problem, prove that it's correct, and analyze its running time." In the adjacency list, G[u] holds pairs (v, w), one per neighbour v, where w is the weight of {u, v}. The graph below is the one on the worksheet of September 15; its MST, highlighted in the second copy, has weight 1 + 2 + 3 + 4 + 7 = 17.
Statement
For example, in the graph above take S = {3, 6}. The edges with exactly one endpoint in S are {2, 3} of weight 7, {2, 6} of weight 8 and {5, 6} of weight 9, so the Cut Property says {2, 3} is in the MST, even though 7 is the third largest weight in the graph (after 9 and 8). The property says nothing about the other crossing edges; it only certifies the lightest one.
Correctness
The notes prove the property by contradiction with an exchange. Assume there is a cut S whose lightest crossing edge e is not in the MST T. Since T is a spanning tree, adding e to it creates exactly one cycle C, and C contains e. The cycle starts on one side of the cut, crosses it along e, and must come back, so some other edge f ∈ C also crosses S. Because e is the lightest edge crossing S, w(e) < w(f). Now T′ = T + e − f is a spanning tree: removing f breaks the only cycle, and every vertex is still connected because any path that used f can go around the rest of C instead. Its weight is w(T) + w(e) − w(f) < w(T), contradicting the assumption that T is the MST. ∎
Running time
The Cut Property is a fact, not an algorithm, but using it costs very little: with S stored as a 0/1 array (S[u] = 1 if and only if u ∈ S, the notes' way of avoiding hashing), one scan of the m edges finds the lightest edge crossing S in O(m) time. That one scan is the inner step of Prim's algorithm and of Problem 3.4.
Check-in 4.2. In the worksheet graph above, list the edges crossing the cut S = {1, 4} with their weights, and say which one the Cut Property puts in the MST. Do the same for S = {1, 2, 4, 5}.
Answer
S = {1, 4}: {1, 2}:1, {1, 5}:5, {4, 5}:2; the lightest is {1, 2}. S = {1, 2, 4, 5}: {2, 3}:7, {2, 6}:8, {5, 6}:9; the lightest is {2, 3}. Both are in the MST.4.3 Prim's algorithm
In plain words. Prim's algorithm grows one tree outward from vertex 1, much as BFS grows outward from its start vertex (the lecture's comparison). At each step it looks at every edge that leaves the current tree and adds the cheapest one, together with the new vertex it reaches. Every edge it adds is the lightest edge crossing a cut, so the Cut Property guarantees it belongs to the MST. After n − 1 additions the tree touches every vertex and is the MST.
- Input: connected, undirected G with distinct weights. Output: the list F of MST edges, in the order they were added.
- Rule: start with S = {1}; repeat n − 1 times: add the lightest edge crossing S to F and its outside endpoint to S.
- Invariant: F is always a subset of the MST, because each added edge is the lightest edge crossing the cut S (Cut Property).
- S is a 0/1 array of length n, so membership tests take O(1) without hashing.
- Running time: n − 1 iterations, each a scan of all edges in O(m), so O(mn) = O(m²).
- Prim's order is not increasing weight: on the worksheet graph it adds weights 1, 4, 2, 7, 3.
- Trap: forgetting edges from earlier tree vertices; every vertex of S contributes its outgoing edges at every step.
Problem
The MST problem of Section 4.2, with an O(m²) target. The lecture's example (September 10) is the square below: edges {1, 2}:5, {1, 4}:4, {1, 3}:3, {2, 3}:2, {3, 4}:1. Prim from vertex 1 adds {1, 3}, {3, 4}, {2, 3}, and the MST weighs 3 + 1 + 2 = 6.
Algorithm
Keep a set S of vertices already in the tree, starting with S = {1} (the notes assume V = [n], so vertex 1 exists), and an empty list F. In each of n − 1 rounds, scan the edges and find the lightest edge e that crosses S, that is, has one endpoint in S and the other outside. Let v be the endpoint of e that is not in S; add v to S and append e to F. When the loop ends, F has n − 1 edges and S = V. The notes' pseudocode:
Prim(G):
S = {1}; F = [empty list]
for i = 1, ..., n-1:
e = lightest edge crossing S
v = endpoint of e not in S
add v to S; add e to F
return F
The notes add that S is implemented as a binary array: "creating S = {1} is equivalent to creating S = [0] * n and setting S[1] = 1, and adding v to S is equivalent to setting S[v] = 1." The trace on the lecture's square:
| Round | S before | Edges crossing S | Chosen | F after |
|---|---|---|---|---|
| 1 | {1} | {1, 2}:5, {1, 3}:3, {1, 4}:4 | {1, 3} | [{1, 3}] |
| 2 | {1, 3} | {1, 2}:5, {1, 4}:4, {2, 3}:2, {3, 4}:1 | {3, 4} | [{1, 3}, {3, 4}] |
| 3 | {1, 3, 4} | {1, 2}:5, {2, 3}:2 | {2, 3} | [{1, 3}, {3, 4}, {2, 3}] |
A second, longer trace on the worksheet graph of Section 4.2 shows how the candidate list grows and shrinks:
| Round | S before | Edges crossing S (weight) | Chosen |
|---|---|---|---|
| 1 | {1} | {1, 2}:1, {1, 4}:4, {1, 5}:5 | {1, 2} |
| 2 | {1, 2} | {1, 4}:4, {1, 5}:5, {2, 5}:6, {2, 3}:7, {2, 6}:8 | {1, 4} |
| 3 | {1, 2, 4} | {4, 5}:2, {1, 5}:5, {2, 5}:6, {2, 3}:7, {2, 6}:8 | {4, 5} |
| 4 | {1, 2, 4, 5} | {2, 3}:7, {2, 6}:8, {5, 6}:9 | {2, 3} |
| 5 | {1, 2, 3, 4, 5} | {3, 6}:3, {2, 6}:8, {5, 6}:9 | {3, 6} |
Some cells worked out: in round 3, the edge {4, 5} of weight 2 appears for the first time because vertex 4 only just joined S, and it beats everything else. In round 4, both endpoints of {1, 5} and {2, 5} are now in S, so those edges no longer cross S and drop out of the list. In round 5, {3, 6} of weight 3 becomes available only after 3 joins. The answer is {1, 2}, {1, 4}, {4, 5}, {2, 3}, {3, 6}, weight 17.
Correctness
The notes' argument uses the Cut Property directly. In each iteration, Prim's algorithm adds the lightest edge crossing S to F. By the Cut Property this edge is in the MST T, so F is always a subset of T (an invariant that holds after every iteration). The algorithm stops when F has n − 1 edges, and any spanning tree has exactly n − 1 edges, so at that point F is all of T: the algorithm returns the MST.
Running time
There are n − 1 iterations. Each one finds the lightest edge crossing S by scanning all m edges and checking S[u] ≠ S[v] in O(1), which costs O(m). The total is O(mn). Because G is connected, n − 1 ≤ m, so O(mn) = O(m²), the bound the problem asks for. The lecture mentioned as a tangent that a heap-based priority queue brings Prim's algorithm down to O(m log n); that version is not needed for any exam.
Check-in 4.3. Run Prim's algorithm from vertex 1 on the graph below (the second graph from the lecture of September 10). Fill in the edge chosen in each round, then give the MST weight.
| Round | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| Edge | |||||
| Weight |
Answer
Rounds 1–5: {1, 2}:1, {2, 4}:2, {4, 5}:4, {2, 3}:6, {3, 6}:5. In round 4 the candidates are {2, 3}:6, {2, 6}:7, {5, 6}:8 ({2, 5} and {1, 4} no longer cross S); {3, 6}:5 only appears once 3 has joined. MST weight 18.4.4 Kruskal's algorithm
In plain words. While Prim's algorithm grows one tree from a single vertex, Kruskal's algorithm "jumps around" the edges of the graph from the lightest to the heaviest, in the notes' words. It looks at each edge once, in increasing order of weight, and keeps it unless it would close a cycle with the edges already kept. The kept edges form several small trees that gradually merge into one. Every kept edge is the lightest edge leaving the little tree it starts from, so the Cut Property again shows it belongs to the MST.
- Input and output as for Prim; the output list F is in increasing order of weight.
- Rule: sort E by increasing weight; for each edge e in that order, add e to F if F + e is acyclic.
- Cycle test: e = {u, v} closes a cycle exactly when u can already reach v using the edges of F; check with BFS on (V, F).
- Correctness: when e = {u, v} is added, let S be the vertices connected to u via F; e is the lightest edge crossing S, so it is in the MST by the Cut Property.
- Running time: O(m log m) to sort plus m BFS runs on a forest with at most n − 1 edges, each O(n), so O(mn) = O(m²).
- Prim and Kruskal return the same tree (the MST is unique) but generally list its edges in different orders.
- Trap: running the reachability test on G instead of on the forest F, or claiming each test costs O(m + n) and getting O(m²) with a wrong reason.
Problem
The MST problem of Section 4.2. The lecture's example (September 10) is the graph below, with edges {1, 4}:1, {2, 5}:2, {5, 6}:3, {3, 4}:4, {2, 3}:5, {2, 4}:6, {1, 2}:7, {2, 6}:8, {3, 6}:9. Kruskal keeps {1, 4}, {2, 5}, {5, 6}, {3, 4}, {2, 3}, weight 15.
Algorithm
Sort the edges by increasing weight and start with an empty list F. Go through the edges in that order. For the current edge e = {u, v}, ask whether u can already reach v using only the edges kept so far; if it cannot, adding e creates no cycle and e is appended to F, and if it can, e is skipped for good. Return F. The notes' pseudocode (where "F + e" means the graph (V, F ∪ {e})):
Kruskal(G):
sort E by increasing weight
F = [empty list]
for e in E:
if F + e is acyclic: # BFS from u in (V, F): can u reach v?
add e to F
return F
| # | Edge | w | Can u already reach v in F? | Action | Components of (V, F) after |
|---|---|---|---|---|---|
| 1 | {1, 4} | 1 | no | keep | {1, 4}, {2}, {3}, {5}, {6} |
| 2 | {2, 5} | 2 | no | keep | {1, 4}, {2, 5}, {3}, {6} |
| 3 | {5, 6} | 3 | no | keep | {1, 4}, {2, 5, 6}, {3} |
| 4 | {3, 4} | 4 | no | keep | {1, 3, 4}, {2, 5, 6} |
| 5 | {2, 3} | 5 | no | keep | {1, 2, 3, 4, 5, 6} |
| 6 | {2, 4} | 6 | yes (2–3–4) | reject | unchanged |
| 7 | {1, 2} | 7 | yes (1–4–3–2) | reject | unchanged |
| 8 | {2, 6} | 8 | yes (2–5–6) | reject | unchanged |
| 9 | {3, 6} | 9 | yes (3–2–5–6) | reject | unchanged |
Some cells worked out: after edge 5 the forest is already a single tree with n − 1 = 5 edges, so every later edge must be rejected; the algorithm still looks at them, but a hand trace can stop listing once five edges are kept. Edge 6, {2, 4}, is rejected because 2 reaches 4 along 2–3–4 in F. The answer is {1, 4}, {2, 5}, {5, 6}, {3, 4}, {2, 3} with weight 1 + 2 + 3 + 4 + 5 = 15. For comparison, Prim from vertex 1 on the same graph adds {1, 4}, {3, 4}, {2, 3}, {2, 5}, {5, 6}: the same five edges in a different order.
Correctness
The notes give a two-part argument. F is a subset of the MST. Let e = {u, v} be any edge added to F, and let S be the set of vertices connected to u via F immediately before e was added. No edge of F crosses S (S is a whole component of F). Every edge lighter than e has already been considered; each of them either was kept, and so does not cross S, or was rejected because its endpoints were already connected in F, and so also does not cross S. Hence e is the lightest edge that could be added to F without creating a cycle, which makes it the lightest edge crossing S, and by the Cut Property e is in the MST. F is spanning. Suppose some cut S′ had no edge of F crossing it. Since G is connected, some edge e crosses S′, and when the algorithm considered e, F + e was acyclic (no path in F joins the two sides of S′), so the algorithm would have added e. This contradicts the behaviour of the algorithm. A subset of the MST that connects every vertex is the MST.
Running time
Sorting E takes O(m log m) time; the lecture notes that log m ≤ log(n²) = 2 log n, so this is also O(m log n). The loop makes m iterations, and each checks whether F + e is acyclic by running BFS on (V, F) from u and checking whether v is reached. BFS normally costs O(m + n), but (V, F) has at most n − 1 edges, so each run costs only O(n). The total is O(m log m) + m · O(n) = O(mn) = O(m²).
Extra context beyond what is examined: the lecture of September 15 showed the Union-Find data structure, which speeds up Kruskal's cycle test to O(log n) per edge and the whole algorithm to O(m log n), and labelled it "Tangent (don't need to know for any exam)". With parent pointers and union by size, running Kruskal on the worksheet graph of Section 4.2 ends with parent array p = [2, 5, 6, 5, 5, 5] and sizes [1, 2, 1, 1, 6, 2], the answer to the worksheet's Problem 1.
Check-in 4.4. The lecture of September 10 started Kruskal on the graph of Check-in 4.3 and stopped after two edges. Finish it: list every edge in increasing order of weight and write keep or reject.
| Edge | {1, 2} | {2, 4} | {1, 4} | {4, 5} | {3, 6} | {2, 3} | {2, 6} | {5, 6} | {2, 5} |
|---|---|---|---|---|---|---|---|---|---|
| w | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| Action |
Answer
keep, keep, reject ({1, 4}: 1–2–4 already), keep, keep, keep, then reject, reject, reject (the tree is complete after {2, 3}). Kruskal's order is {1, 2}, {2, 4}, {4, 5}, {3, 6}, {2, 3}, weight 18; Prim (Check-in 4.3) added the same edges in the order {1, 2}, {2, 4}, {4, 5}, {2, 3}, {3, 6}.4.5 Reverse-Delete and the Cycle Property
In plain words. Reverse-Delete is Kruskal's algorithm run backwards: instead of adding the lightest edges that do not close a cycle, it deletes the heaviest edges that can be removed without disconnecting the graph. Its justification is the mirror image of the Cut Property, called the Cycle Property: the heaviest edge on any cycle is not in the MST. An edge that can be removed without disconnecting the graph lies on a cycle, and since edges are tried heaviest first, it is the heaviest edge of that cycle. So every deletion is safe, and what remains at the end is the MST.
- Cycle Property: for any cycle C in G, the heaviest edge in C is not in the MST of G.
- Proof: if the heaviest edge f of C were in the MST T, removing f from T creates a cut; C crosses that cut again at some e with w(e) < w(f), and T + e − f is lighter.
- Rule: sort E by decreasing weight; for each e in that order, remove e from G if G − e is still connected.
- Invariant: G always contains the MST; at the end G is acyclic and connected, so it is the MST.
- Running time: O(m log m) to sort plus m BFS runs on the current graph, each O(m + n) = O(m), so O(m²).
- Summary from the lecture of September 15: Cut Property ⇒ Prim and Kruskal; Cycle Property ⇒ Reverse-Delete.
- Trap: in the proof, e must cross the cut made by removing f; any other edge of C may create a cycle instead (worksheet of September 15).
Problem
The MST problem of Section 4.2, O(m²) target. The lecture's example (September 10) is the graph below; Reverse-Delete deletes the edges of weight 10, 9, 6 and 3 and keeps the other five, an MST of weight 4 + 5 + 8 + 1 + 2 = 20. (The weight of {2, 5} is hard to read in the handwritten notes; it is drawn here as 5. Any value below 6 gives the same deletions and the same tree; the total of 20 depends on the value 5.)
Algorithm
First the property, which the notes state and prove before the algorithm.
Then the algorithm: sort the edges by decreasing weight. For each edge e in that order, test whether G − e is still connected (run BFS from one endpoint of e in G − e and check whether the other endpoint is reached). If it is, delete e from G permanently; if not, e is a bridge of the current graph and stays. Return what is left of G. The notes' pseudocode:
Reverse-Delete(G):
sort E by decreasing weight
for e in E:
if G - e is connected: # BFS: do the endpoints of e still reach each other?
remove e from G
return G
| # | Edge | w | Is G − e connected? | Action |
|---|---|---|---|---|
| 1 | {1, 4} | 10 | yes: 1–2–3–4 | delete |
| 2 | {5, 6} | 9 | yes: 5–2–3–6 | delete |
| 3 | {2, 3} | 8 | no: it is now the only link between {1, 2, 5} and {3, 4, 6} | keep |
| 4 | {1, 5} | 6 | yes: 1–2–5 | delete |
| 5 | {2, 5} | 5 | no: 5 has no other edge left | keep |
| 6 | {1, 2} | 4 | no: 1 has no other edge left | keep |
| 7 | {4, 6} | 3 | yes: 4–3–6 | delete |
| 8 | {3, 6} | 2 | no | keep |
| 9 | {3, 4} | 1 | no | keep |
Some cells worked out: in row 3, the two curved edges are already gone, so {2, 3} is the bridge between the left triangle and the right triangle and cannot be removed even though it is the heaviest remaining edge. In row 7, the triangle 3, 4, 6 is still intact, so its heaviest edge {4, 6} goes. The result is {1, 2}, {2, 5}, {2, 3}, {3, 4}, {3, 6}, weight 20; Kruskal on the same graph keeps exactly these edges.
Correctness
Proof of the Cycle Property (exchange argument). For contradiction, assume some cycle C has its heaviest edge f in the MST T. Removing f from T splits T into two pieces, which define a cut S. The cycle C crosses S along f and has to cross back, so some other edge e of C crosses S, and since f is the heaviest edge in C, w(e) < w(f). Then T′ = T + e − f is a spanning tree (e reconnects the two pieces) and is lighter than T, contradicting the assumption that T is the MST. ∎
Correctness of Reverse-Delete (the notes' argument). When the algorithm removes an edge e, G stays connected, so e lies on a cycle: e together with a path between its endpoints in G − e. Every heavier edge has already been considered, and the edges of that path are still in G, so they are all lighter than e; thus e is the heaviest edge in that cycle and, by the Cycle Property, not in the MST. Hence G contains the MST throughout the algorithm, including at the end. At the end G is acyclic: if a cycle C remained, its heaviest edge could have been removed without disconnecting G when it was considered, contradicting the behaviour of the algorithm. A connected, acyclic graph containing the MST is the MST.
Running time
Sorting E takes O(m log m) time. The loop makes m iterations, and each checks whether G − e is connected by running BFS on the current graph, which costs O(m + n). Because G is connected, n − 1 ≤ m, so O(m + n) = O(m), and the total is O(m log m) + m · O(m) = O(m²).
| Algorithm | Order | Rule | Justified by | Running time |
|---|---|---|---|---|
| Prim | grows from vertex 1 | add the lightest edge crossing S | Cut Property | O(mn) = O(m²) |
| Kruskal | increasing weight | add e if F + e is acyclic | Cut Property | O(m log m) + m · O(n) = O(m²) |
| Reverse-Delete | decreasing weight | remove e if G − e is connected | Cycle Property | O(m log m) + m · O(m) = O(m²) |
Check-in 4.5. In the worksheet graph of Section 4.2, apply the Cycle Property to the three triangles 1, 4, 5 and 2, 5, 6 and 2, 3, 6, and name the three edges it rules out of the MST.
Answer
Cycle 1, 4, 5 has edges {1, 4}:4, {4, 5}:2, {1, 5}:5, so {1, 5} is not in the MST. Cycle 2, 5, 6 has {2, 5}:6, {5, 6}:9, {2, 6}:8, so {5, 6} is not. Cycle 2, 3, 6 has {2, 3}:7, {3, 6}:3, {2, 6}:8, so {2, 6} is not. All three are indeed absent from the MST of weight 17.4.6 Selecting compatible intervals
In plain words. Each interval is an event with a start time and an end time, and the goal is to attend as many events as possible without attending two that overlap. Of the natural greedy rules (shortest first, earliest start first, fewest conflicts first, earliest end first), only the last one always works. The algorithm sorts the events by end time and takes each event that starts after the last chosen one ends. The exchange argument shows that the earliest-ending event can always replace the first choice of any optimal solution, which is the whole proof.
- Input: an array A of n intervals [s, t] of positive integers with s < t; an interval includes its endpoints, and two intervals conflict if they share any real number. Output: a largest list of pairwise compatible intervals.
- Rule ("keep picking the event that ends earliest"): sort A by non-decreasing end time; add each interval that does not conflict with the last interval in S.
- Why only the last one: S is built in order of end time, so the last interval in S ends latest; e conflicts with some interval in S if and only if it conflicts with the last one, so each test is O(1).
- Exchange: at the first index i where ALG[i] ≠ OPT[i], OPT[i] cannot end before ALG[i]; replacing OPT[i] by ALG[i] keeps OPT feasible and the same size.
- Running time O(n log n): sort, then n iterations of O(1).
- Counterexamples kill the other three rules (Chapter 0 worksheet); know at least one.
- Trap: endpoints count, so [6, 8] and [8, 10] conflict; the test is s > (end of the last chosen interval), with a strict inequality.
Problem
The notes' definition: "An interval is an array of two positive integers [s, t] where s < t; this interval represents the set of real numbers from s through t (including the endpoints). Two intervals conflict if there exists a real number in both of their corresponding sets." Problem (3.3, Selecting Compatible Intervals). "The input is an array A of n intervals (as defined above). A list of intervals is compatible if no two intervals in the list conflict with each other. Our goal is to return a list of compatible intervals that contains as many intervals as possible. Describe an O(n log n)-time algorithm for this problem, prove that it's correct, and analyze its running time."
The problem opened the course. Chapter 0's example is a day of five events: Event 1 from 9:00 to 10:30, Event 2 from 9:00 to 9:15, Event 3 from 9:30 to 10:05, Event 4 from 10:00 to 12:00 and Event 5 from 10:15 to 11:45. Its only optimal solution is {Event 2, Event 3, Event 5}.
Why the other greedy rules fail
Chapter 0's worksheet listed four greedy rules and asked which are optimal; the official answer is that "the only optimal algorithm is the one that keeps picking the interval that ends the earliest." Its counterexamples, drawn below with an optimal solution in green:
- Shortest interval first fails on {[1, 10], [9, 12], [11, 20]}: the shortest, [9, 12], conflicts with both others, so the rule gets 1 interval while [1, 10] and [11, 20] give 2.
- Earliest start first fails on {[1, 10], [2, 3], [4, 5]}: it takes [1, 10] and nothing else fits, while [2, 3] and [4, 5] give 2.
- Fewest remaining conflicts first fails on {[1, 3], 3 copies of [2, 5], [4, 7], [6, 9], [8, 11], 3 copies of [10, 13], [12, 14]} (the September 10 worksheet's Problem 1): [6, 9] has only 2 conflicts, fewer than anything else, but choosing it rules out [4, 7] and [8, 11], and the rule ends with 3 intervals while [1, 3], [4, 7], [8, 11], [12, 14] give 4.
Algorithm
Sort A by non-decreasing end time and create an empty list S. Go through the intervals in this order; if the current interval e does not conflict with the last interval in S (that is, e starts strictly after the last interval in S ends, or S is empty), append e to S. Return S. The notes point out why checking only the last interval is enough: "e conflicts with any interval in S if and only if e conflicts with the last interval in S." The lecture first wrote "any interval in S", crossed out "any" and wrote "the last", turning an O(n²) loop into O(n). The notes' pseudocode:
Select-Intervals(A):
sort A by non-decreasing end time
S = [empty list]
for e in A:
if e does not conflict with the last interval in S:
add e to the end of S
return S
A trace on A = [[2, 5], [1, 3], [4, 7], [6, 8], [3, 9], [8, 10], [9, 12]], shown below already sorted by end time:
| Step | Interval e | Last chosen ends at | Starts after it? | Action | S after |
|---|---|---|---|---|---|
| 1 | [1, 3] | (S empty) | yes | add | [1, 3] |
| 2 | [2, 5] | 3 | no (2 ≤ 3) | skip | [1, 3] |
| 3 | [4, 7] | 3 | yes (4 > 3) | add | [1, 3], [4, 7] |
| 4 | [6, 8] | 7 | no | skip | same |
| 5 | [3, 9] | 7 | no | skip | same |
| 6 | [8, 10] | 7 | yes (8 > 7) | add | [1, 3], [4, 7], [8, 10] |
| 7 | [9, 12] | 10 | no (9 ≤ 10) | skip | [1, 3], [4, 7], [8, 10] |
Some cells worked out: [3, 9] comes after [6, 8] in the sorted order because it ends later, even though it starts earlier; the order is by end time only. At step 6, [8, 10] is compatible with [4, 7] but would have conflicted with [6, 8] (they share the point 8), which is why the strict test matters. The answer has 3 intervals, and a brute-force check over all subsets confirms that no 4 are compatible.
Correctness
The notes use an exchange argument that walks along the solution. Let ALG and OPT be the algorithm's solution and an optimal solution, each sorted by non-decreasing end time, and let m = |ALG|. If ALG[i] = OPT[i] for every i ∈ [m], the algorithm is optimal. Otherwise let i be the smallest index with ALG[i] ≠ OPT[i]. The goal is to build another optimal solution OPT′ that agrees with ALG on positions 1 through i; repeating the step then reaches an optimal solution equal to ALG. "The key is that OPT[i] cannot end before ALG[i] because the algorithm greedily chooses the interval with the smallest end time": both are compatible with the shared first i − 1 intervals, and ALG[i] is the earliest-ending such interval. So let OPT′ be OPT with OPT[i] removed and ALG[i] added. OPT′ is feasible: ALG[i] does not conflict with the first i − 1 intervals (the algorithm checked this), and it ends no later than OPT[i], which already ended before OPT[i + 1] began, so it does not conflict with any later interval of OPT. Also |OPT′| = |OPT| and OPT′ agrees with ALG on positions 1 through i. Repeating the exchange gives an optimal solution identical to ALG. (The argument also rules out OPT being longer than ALG: once they agree on positions 1 through m, any OPT[m + 1] would start after ALG[m] ends and the algorithm would have added it.)
Running time
Sorting A takes O(n log n) time, and each of the n iterations takes O(1) time (one comparison with the last interval of S), so the total is O(n log n). The lecture first wrote the loop as checking every interval in S, which "looks like O(n log n) + n · O(n) = O(n²)"; comparing with the last interval only is what gives O(n log n).
Check-in 4.6. Run Select-Intervals on A = [[5, 9], [1, 4], [3, 6], [7, 8], [10, 11], [2, 12]] (drawn below in the given order). Write the intervals in sorted order and mark each as added or skipped.
| Sorted by end | ||||||
|---|---|---|---|---|---|---|
| Add / skip |
Answer
Sorted: [1, 4], [3, 6], [7, 8], [5, 9], [10, 11], [2, 12]. Actions: add, skip (3 ≤ 4), add (7 > 4), skip (5 ≤ 8), add (10 > 8), skip. Result [1, 4], [7, 8], [10, 11], 3 intervals.Check-in 4.7. Give a counterexample to the greedy rule "keep picking the shortest interval", and state what the rule returns and what the optimum is.
Answer
{[1, 10], [9, 12], [11, 20]} (Chapter 0). The shortest interval is [9, 12] (length 3), which conflicts with both others, so the rule returns 1 interval; the optimum {[1, 10], [11, 20]} has 2.4.7 Fractional knapsack
In plain words. Items have a value and a weight, the knapsack holds a total weight of at most B, and the goal is to pack as much value as possible. In the fractional version an item may be split, so taking 20% of an item gives 20% of its value for 20% of its weight. The greedy rule is to take items in order of value per unit of weight, as much of each as fits, which fills the knapsack completely and splits at most one item. The exchange argument shifts a tiny amount of weight from a worse-ratio item to a better-ratio item and shows the value cannot go down.
- Input: (v, w, B), arrays v and w of n positive integers and a positive integer capacity B. Output: an array x of n real numbers with 0 ≤ x[i] ≤ 1, Σ x[i] · w[i] ≤ B, and Σ x[i] · v[i] as large as possible.
- Rule: sort items by non-increasing v[i]/w[i]; in that order, increase each x[i] as much as possible without exceeding B.
- At most one x[i] is strictly between 0 and 1: the item that fills the knapsack.
- Exchange: at the first item i where OPT[i] < ALG[i], some later item j has OPT[j] > 0; raise x[i] by ε and lower x[j] by ε · w[i]/w[j]. Weight is unchanged and value changes by ε · (v[i] − (w[i]/w[j]) · v[j]) ≥ 0.
- Running time O(n log n): sort, then n iterations of O(1).
- The same rule fails for 0/1 Knapsack, where items cannot be split (that problem needs dynamic programming, Chapter 6).
- Trap: x must be listed in the original item order, x[1] through x[n], not in the sorted order.
Problem
Problem (3.4, Fractional Knapsack). "The input is (v, w, B), where v and w are arrays of n positive integers each and B ∈ ℤ+. Our goal is to return an array x of n real numbers such that 0 ≤ x[i] ≤ 1 for all i ∈ [n], Σi=1n x[i] · w[i] ≤ B, and Σi=1n x[i] · v[i] is maximized." The lecture's story is shopping with a budget: B dollars, and each item has a value and a cost (its weight). The lecture's instance, also Problem 2 of the September 10 worksheet, is v = [4, 1, 2], w = [5, 1, 4], B = 7, with answer x = [1, 1, 1/4] and value 4 + 1 + 2/4 = 5.5.
Algorithm
Compute each item's ratio v[i]/w[i] (value per unit of weight) and sort the items from the highest ratio to the lowest. Start with x = [0, …, 0] and remaining capacity B. In sorted order, take as much of each item as fits: x[i] = min(1, remaining / w[i]), then subtract x[i] · w[i] from the remaining capacity. Once the capacity reaches 0, every later item gets x[i] = 0. The notes' pseudocode:
Fractional-Knapsack(v, w, B):
sort items by non-increasing v[i]/w[i]
x = [0]*n
for each item i:
increase x[i] by as much as possible
return x
The lecture sorted pairs (v[i]/w[i], i) so that each ratio remembers its item. The trace on the lecture's instance, where the ratios are v/w = [0.8, 1, 0.5]:
| Order | Item i | v[i] | w[i] | v[i]/w[i] | Capacity before | x[i] | Value added | Capacity after |
|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 1 | 1 | 1 | 7 | 1 | 1 | 6 |
| 2 | 1 | 4 | 5 | 0.8 | 6 | 1 | 4 | 1 |
| 3 | 3 | 2 | 4 | 0.5 | 1 | 1/4 | 0.5 | 0 |
Some cells worked out: item 2 comes first because its ratio 1/1 = 1 beats item 1's 4/5 = 0.8, even though item 1 is the most valuable. After items 2 and 1 the knapsack holds weight 1 + 5 = 6, so 1 unit of room is left; item 3 weighs 4, so x[3] = 1/4, worth 2 · 1/4 = 0.5. Listed in item order, the answer is x = [1, 1, 1/4], value 5.5.
Correctness
The notes' exchange argument. Number the items in sorted order, so v[1]/w[1] ≥ v[2]/w[2] ≥ ⋯, and write v(y) for the value of a solution y. For contradiction assume v(OPT) > v(ALG), and let i be the smallest index with OPT[i] ≠ ALG[i]. By design of the algorithm, ALG took as much of item i as would fit given the items before it, on which OPT agrees, so OPT[i] < ALG[i]. Since v(OPT) > v(ALG), OPT must use some later item: there is a j > i with OPT[j] > 0. Build OPT′ from OPT by increasing OPT[i] by some ε > 0 and decreasing OPT[j] by ε · w[i]/w[j]. If ε is small enough, both amounts stay between 0 and 1, and OPT′ is feasible, because its weight is w(OPT) + ε · w[i] − (ε · w[i]/w[j]) · w[j] = w(OPT) ≤ B (this is the September 15 worksheet's Problem 2). Its value is
v(OPT′) = v(OPT) + ε · v[i] − ε · w[i]w[j] · v[j] = v(OPT) + ε · (v[i] − w[i]w[j] · v[j]) ≥ v(OPT),
where the inequality holds because ε > 0 and v[i]/w[i] ≥ v[j]/w[j] (multiply both sides by w[i]). So OPT′ is also optimal and takes more of item i than OPT does. Repeating the process gives an optimal solution identical to ALG.
Running time
Computing the n ratios takes O(n) time, sorting the items takes O(n log n), and each of the n iterations takes O(1), so the total is O(n log n).
Check-in 4.8. Run the greedy algorithm on v = [6, 10, 12], w = [1, 2, 3], B = 5. Fill in the ratios and x, and give the value.
| i | 1 | 2 | 3 |
|---|---|---|---|
| v[i]/w[i] | |||
| x[i] |
Answer
Ratios [6, 5, 4], so the order is 1, 2, 3. Item 1 (weight 1, 4 left), item 2 (weight 2, 2 left), then 2/3 of item 3. x = [1, 1, 2/3], value 6 + 10 + 12 · 2/3 = 24.4.8 Worked problems from Problem Set 3
Problem Set 3 was released on September 8 and due September 15, together with Homework 3. Every problem below is stated word for word from the course page, and the solution follows the official one, expanded and laid out in the course's answer recipe (Algorithm with pseudocode, Correctness, Running time). Midterm 1's Problem 3 was Problem 3.4 verbatim, and the final promises at least two problems identical to problem-set problems, so all five are worth being able to reproduce from memory. Attempt each one on paper before opening its solution.
PS 3.1. Max k-Sum
Solution
The problem set notes that this problem was also solved in Chapter 3 (Section 4.1 here) and that its solution is a bit more detailed.
Algorithm. Sort A in decreasing order and return the first k elements.
ALG(A, k):
sort A in decreasing order
return A[1:k]
Correctness. We want to show that an optimal solution OPT equals A[1 : k] (after sorting A). For contradiction, suppose OPT ≠ A[1 : k]. Then OPT excludes some number A[i] in A[1 : k] and, since |OPT| = k, includes some number A[j] for some j > k. Consider the solution OPT′ constructed by starting with OPT, removing A[j] and adding A[i]; in other words, OPT′ equals OPT except that A[j] is exchanged for A[i]. OPT′ is feasible because |OPT′| = |OPT| = k. Furthermore, letting v(B) denote the sum of any array B, v(OPT′) = v(OPT) − A[j] + A[i] > v(OPT), where the inequality holds because A[j] < A[i] (A is sorted in decreasing order and j > k ≥ i). So OPT′ is a feasible solution whose sum is greater than v(OPT), contradicting the optimality of OPT.
Running time. Sorting takes O(n log n) time, and adding the first k elements to an array takes O(k) = O(n) time, so the total running time is O(n log n).
Pattern: choose-the-best-k by sorting; exchange one excluded top element for one included lower element.
PS 3.2. Minimizing total waiting time
Solution
Algorithm. Return A sorted in non-decreasing order (shortest job first).
ALG(A):
sort A in non-decreasing order
return A
Correctness. Intuitively, longer jobs should appear at the end, because that way they contribute to the waiting time of fewer jobs. Formally, suppose that the optimal solution is not sorted in non-decreasing order, that is, it processes some job i immediately before another job j but A[i] > A[j]. Swap i and j and leave all other jobs untouched. Then i waits A[j] more time (j now runs before it) and j waits A[i] less time (i no longer runs before it). Jobs before the pair wait exactly as before, and jobs after the pair still wait for both, so no other waiting time changes. The net effect on the sum of waiting times is a decrease by A[i] − A[j] > 0, contradicting optimality. Hence the optimal order has no adjacent pair out of order, which means it is sorted.
Running time. Sorting an array takes O(n log n) time.
Pattern: an ordering problem solved by sorting on a key, proved by swapping one adjacent out-of-order pair (the September 8 worksheet's Problem 1 asks for exactly this exchange).
PS 3.3. Minimizing maximum lateness
Solution
Algorithm. Sort A in non-decreasing order of the deadline d[i] (earliest deadline first). On the example this gives (5, 1), (1, 3), (3, 4) with C = [5, 6, 9], H = [4, 3, 5] and H* = 5, the optimum.
ALG(A):
sort A in non-decreasing order of d[i]
return A
Correctness. For contradiction, suppose OPT orders some A[i] immediately before some A[j] but d[i] > d[j]. If we swap jobs i and j in OPT, leaving everything else unchanged, we obtain a solution OPT′ whose maximum lateness is at most that of OPT. Specifically, all completion times stay the same except that C[i] and C[j] are swapped: if c is the time at which the second of the two jobs finishes, then in OPT job j finished at c, and in OPT′ job i finishes at c. Since C[j] decreases, j's lateness decreases. Since C[i] increases, i's lateness increases, but its new lateness is c − d[i] < c − d[j], which is j's lateness in OPT, because d[i] > d[j]. So every lateness in OPT′ is at most some lateness in OPT, and the swap cannot increase the maximum lateness. Repeating such swaps sorts OPT by deadline without making it worse, so the sorted order is optimal.
Running time. Sorting takes O(n log n) time.
Pattern: adjacent swap again, but the objective is a maximum, so the swap only has to "not get worse"; processing times play no role in the key.
PS 3.4. Updating the MST after an edge gets heavier
Solution
Algorithm. Remove e from T to create a cut in the graph, and add the lightest edge crossing the cut to T.
ALG(G, T, e):
u, v = endpoints of e
remove e from T
S = vertices reachable from u # run BFS(T, u)
e' = lightest edge crossing S # scan all m edges of G, using a 0/1 array for S
return T + e'
Example: in the worksheet graph of Section 4.2, raise w({1, 4}) from 4 to 10. Removing {1, 4} from T leaves the pieces S = {1, 2, 3, 6} and {4, 5}; the edges crossing S are {1, 4}:10, {1, 5}:5, {2, 5}:6 and {5, 6}:9, so the new MST is T − {1, 4} + {1, 5}, of weight 18 (the edge e′ may also be e itself, if e is still the lightest crossing edge).
Correctness. First, every edge f ∈ T other than e is still in the MST. If we remove f from T, we obtain a cut Sf, and f is the only edge of T crossing Sf. By the Cut Property applied to the old graph, f is the lightest edge crossing Sf (otherwise the lightest crossing edge would be in the MST T, and T would have two edges crossing Sf). This still holds after w(e) increases, since e is the only edge whose weight changed and raising it cannot make it lighter than f. So by the Cut Property again, f is in the new MST, and the n − 2 edges of T other than e are all in the new MST. Second, the algorithm removes e from T to create a cut S, and no edge of T − e crosses S. By the Cut Property, the lightest edge crossing S in the new graph is in the new MST, so the algorithm correctly adds it. The result has n − 1 edges of the new MST, so it is the new MST.
Running time. Removing e from T takes O(n) time. Running BFS from u takes O(n) time, because T − e has n vertices and n − 2 edges. Scanning the m edges of G while keeping track of the lightest one crossing S takes O(m) time. The total is O(m + n) = O(m), since G is connected and n − 1 ≤ m.
Pattern: "remove an edge of a tree to get a cut, then use the Cut Property"; both halves of the argument are graded (see Section 4.10).
PS 3.5. Coin change with dimes, nickels and pennies
Solution
Algorithm. Take as many dimes as possible, then as many nickels as possible, then pennies. Following Python, a // b denotes a/b rounded down. For t = 28 this returns [2, 1, 3].
ALG(t):
a = t // 10; t -= 10*a
b = t // 5; t -= 5*b
c = t
return [a, b, c]
Correctness. Let OPT = [a*, b*, c*] be an optimal solution; we want a + b + c = a* + b* + c*. First we claim a = a*. If a* > a, then ALG could have picked at least one more dime, which is impossible because it starts by picking as many dimes as possible. If a > a*, then OPT has at least 10 cents' worth of nickels and pennies, and some of them can be replaced by a dime: if OPT has at least 2 nickels, those 2 coins can be replaced with a dime; if it has exactly 1 nickel, it must have at least 5 pennies, and these 6 coins can be replaced with a dime; if it has no nickels, it has at least 10 pennies, and these 10 coins can be replaced with a dime. In every case the replacement decreases the number of coins in OPT, which is impossible since OPT already uses the fewest coins. So a = a*. By the same reasoning, since 5 pennies can replace 1 nickel, b = b*. Finally, ALG and OPT have the same total value, so c = c*.
Running time. The algorithm consists of a constant number of primitive operations, so it runs in O(1) time.
Pattern: exchange several small pieces of OPT for one big piece that ALG chose; the case analysis is what makes the exchange explicit.
4.9 Homework-style one-point questions
Homework 3 was auto-graded, with exact answers typed into a box: the same kind of one-point, no-explanation question as Problems 1 and 2 of the final. It contained three question types, each asked once on a small instance and then on a large one. Each type is worked below on the homework's own instance with the accepted answer.
Type 1: the k-th edge Prim adds
The graph comes as an adjacency list of pairs: "For each u ∈ {1, …, n}, G[u] is a list of arrays [v, w], where v is a neighbor of u and w is the weight of the edge {u, v}." Q1 gave G = [[[2, 1], [3, 3]], [[1, 1], [3, 4], [4, 2]], [[1, 3], [2, 4], [4, 5]], [[2, 2], [3, 5]]], said that the first edge added from vertex 1 is {1, 2}, and asked for the second and third. Decode the edges first: {1, 2}:1, {1, 3}:3, {2, 3}:4, {2, 4}:2, {3, 4}:5. Then run Prim:
| Round | S before | Edges crossing S | Chosen |
|---|---|---|---|
| 1 | {1} | {1, 2}:1, {1, 3}:3 | {1, 2} |
| 2 | {1, 2} | {1, 3}:3, {2, 3}:4, {2, 4}:2 | {2, 4} |
| 3 | {1, 2, 4} | {1, 3}:3, {2, 3}:4, {3, 4}:5 | {1, 3} |
The accepted answers were {2, 4} and {1, 3}, written as "{i, j}" with i < j. Q2 asked the same about a 30-vertex graph with 149 edges; the accepted answers were first edge {1, 4}, tenth edge {5, 22} and last edge {15, 27}. By hand, the first edge is simply the lightest pair in G[1] (here [4, 46]); for later rounds keep a written list of candidate edges leaving S, add the new vertex's edges after each round, and cross out edges whose both endpoints are now in S.
Type 2: the k-th interval Select-Intervals chooses
Q3 gave A = [[3, 5], [1, 2], [2, 4]], said the first interval chosen is [1, 2], and asked for the second. Sorted by end time: [1, 2], [2, 4], [3, 5]. The interval [2, 4] starts at 2, which is not after 2, so it conflicts with [1, 2]; [3, 5] starts at 3 > 2 and is chosen. Accepted answer: [3, 5]. Q4 asked for the first, fifth and last interval chosen from 60 intervals. The full sequence chosen is:
| Choice | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|
| Interval | [1, 2] | [3, 7] | [20, 26] | [47, 58] | [60, 61] | [65, 66] | [89, 101] | [129, 144] | [158, 166] |
The accepted answers were the three bold entries. By hand there is no need to sort all 60 intervals: repeatedly scan for the interval with the smallest end among those that start strictly after the last chosen end. For example, after [3, 7] the candidates must start at 8 or later, and among them [20, 26] ends first (the interval [7, 8] starts at 7, which is not after 7).
Type 3: the optimal Fractional Knapsack value
Q5 gave v = [1, 4, 4], w = [2, 3, 4], B = 8 and the greedy result x = [0.5, 1, 1], and asked for the optimal value in the form "a.bc". The value is 1 · 0.5 + 4 + 4 = 8.5, entered as 8.50. Q6 had 18 items and B = 33. Only the top few ratios matter:
| Order | Item | v | w | v/w | Capacity before | x | Value added |
|---|---|---|---|---|---|---|---|
| 1 | 15 | 242 | 3 | 80.67 | 33 | 1 | 242 |
| 2 | 18 | 124 | 5 | 24.8 | 30 | 1 | 124 |
| 3 | 16 | 193 | 10 | 19.3 | 25 | 1 | 193 |
| 4 | 10 | 240 | 13 | 18.46 | 15 | 1 | 240 |
| 5 | 14 | 217 | 12 | 18.08 | 2 | 1/6 | 36.17 |
The total is 799 + 217/6 = 835.1666…, and since digits after c are ignored the accepted answer was 835.16 (truncated, not rounded to 835.17). Q7 (27 items, B = 31) works the same way: items 1, 2, 23, 3, 9 and 22 are taken whole (weight 27), then 4/14 = 2/7 of item 25, for a value of 5983/7 = 854.714…, accepted as 854.71.
4.10 Past exam problems on this chapter
Midterm 1 (September 22) and Practice Midterm 1 (September 17) covered course Chapters 1–3. Their one-point Problem 1 parts were all on Two Sum, BFS and DFS, so the course Chapter 3 material appears in their design problems: Midterm 1's Problem 3 (Problem 3.4 verbatim) and Problem 5 (a new interval problem), and Practice Midterm 1's Problem 5 (an ordering problem). The Practice Final (December 1) has two one-point parts and one design problem on this chapter. The lecture of September 15 described the midterm format in words that also describe the final's design problems: "≈ to psets 1–3", with "≥ 2 identical to something from Psets". Statements below are verbatim; solutions follow the official ones in the answer recipe.
Midterm 1, Problem 3. Updating the MST (PS 3.4)
Solution
The official solution reads: "This is Problem 3.4 from Problem Set 3 ... One common mistake is not explaining why every non-e edge is still in the MST." The model answer, condensed from Section 4.8:
Algorithm. Remove e = {u, v} from T; run BFS(T − e, u) to get the side S containing u; scan all edges of G and return T − e + e′, where e′ is the lightest edge crossing S.
Correctness. (1) Each edge f ≠ e of T is still in the new MST: removing f from T gives a cut Sf that only f crosses in T, f was the lightest edge crossing Sf (Cut Property in the old graph), and increasing w(e) cannot change that, so f is in the new MST by the Cut Property. (2) No edge of T − e crosses S, and the lightest edge crossing S in the new graph is in the new MST by the Cut Property. These n − 1 edges are the new MST.
Running time. O(n) to remove e, O(n) for BFS on a tree with n − 2 edges, O(m) to scan the edges: O(m + n).
Midterm 1, Problem 5. Fewest points hitting every interval
Solution
Algorithm. Sort A by non-decreasing end time t and walk through it; whenever the current interval [s, t] does not contain the rightmost point placed so far, add t to P. On the example the sorted order is [2, 3], [4, 5], [1, 10]: place 3, then place 5 (4 > 3), and [1, 10] already contains 5, so P = [3, 5]. On A = [[1, 4], [2, 6], [5, 8], [7, 9], [3, 10]] it returns [4, 8].
ALG(A):
sort A by non-decreasing t
P = [empty list]; last = -infinity
for [s, t] in A:
if last < s: # [s, t] does not contain the last point
append t to P
last = t
return P
Correctness. Every interval is hit: when [s, t] is reached, either s ≤ last ≤ t already holds (last ≤ t because earlier intervals end no later), or t is added. For optimality, use the exchange argument of Selecting Compatible Intervals. Suppose OPT ≠ ALG, both sorted, and the earliest difference occurs when ALG handles [s, t] by picking t while OPT's next point is some t* ≠ t; since OPT must hit [s, t] and its earlier points agree with ALG's (which miss [s, t]), t* ≤ t, so t* < t. Let OPT′ be OPT with t* replaced by t. OPT′ is feasible: any interval [a, b] that relied on t* is not hit by the earlier common points, so it comes at or after [s, t] in sorted order and satisfies t ≤ b; it contains t* < t, so a ≤ t* < t ≤ b, and it also contains t. OPT′ has the same size as OPT and agrees with ALG on one more point, so repeating the exchange shows ALG is optimal.
Running time. Sorting takes O(n log n) time and the loop takes O(n), so the total is O(n log n).
The official solution names the common mistake: "adding (s + t)/2, instead of just t, to P." The midpoint wastes the part of the interval to the right of it, which is exactly where later intervals start.
Pattern: interval problem ⇒ sort by end time, act at the end time, exchange at the first difference.
Practice Midterm 1, Problem 5. Weighted completion time
Solution
Algorithm. Sort A in non-decreasing order of p[i]/w[i]. On the example the ratios are 4/3, 1/5 and 2/3, so the order is (5, 1), (3, 2), (3, 4), with value 5 · 1 + 3 · 3 + 3 · 7 = 35, the optimum (better than both orders in the statement).
ALG(A):
sort A in non-decreasing order of p[i]/w[i]
return A
Correctness. For contradiction, suppose OPT orders some A[i] immediately before A[j] but p[i]/w[i] > p[j]/w[j], that is, w[j] · p[i] > w[i] · p[j]. Swap i and j in OPT and leave everything else unchanged to get OPT′. Every other job keeps its completion time. Ci increases by p[j] (job j now runs first), adding w[i] · p[j] to the value, and Cj decreases by p[i], subtracting w[j] · p[i]. The net change is a decrease by w[j] · p[i] − w[i] · p[j] > 0, so OPT′ is better than OPT, a contradiction. Hence the optimal order is sorted by p[i]/w[i].
Running time. Computing the ratios takes O(n) time and sorting takes O(n log n), so the total is O(n log n).
Pattern: PS 3.2 with weights; the key is a ratio, found by writing out what one adjacent swap changes.
Practice Final, Problem 1(c). Prim's order
Solution
{1, 3}, {3, 4}, {2, 3}. From S = {1} the candidates are {1, 2}:6 and {1, 3}:2; from {1, 3} they are {1, 2}:6, {2, 3}:3, {3, 4}:1; from {1, 3, 4} they are {1, 2}:6, {2, 3}:3, {2, 4}:8.Practice Final, Problem 2(a). Fractional Knapsack
Solution
[0.5, 1, 1]. Ratios are 1.5, 2, 5, so the order is item 3 (weight 1, 3 left), item 2 (weight 2, 1 left), then half of item 1 (1 of its 2 units). Value 5 + 4 + 1.5 = 10.5. Listed from x[1], the half comes first even though item 1 was considered last.Practice Final, Problem 6. Spanning tree with the smallest maximum edge
Solution
Algorithm. Return a standard MST of G, for example by running Prim's algorithm.
ALG(G):
return Prim(G)
Correctness. Let T be the MST of G, let e be the heaviest edge in T, let T* be an optimal solution for this new problem, and let e* be the heaviest edge in T*. We claim w(e) ≤ w(e*), which shows that T is optimal too. For contradiction, suppose w(e) > w(e*). Then every edge of T* is lighter than e, so e ∉ T*. Inserting e into the spanning tree T* creates a cycle C made of e and a path of T* edges, all lighter than e. So e is the heaviest edge in C, and by the Cycle Property e is not in the MST T, contradicting our choice of e as an edge of T. Hence w(e) ≤ w(e*), and the MST minimizes the maximum edge weight.
Running time. All three MST algorithms covered in the course notes (Prim's, Kruskal's, Reverse-Delete) run in O(m²) time, and returning the tree adds nothing more.
A check on the worksheet graph of Section 4.2: its MST has maximum edge {2, 3} of weight 7, and no spanning tree can do better, because vertices 3 and 6 can only be joined to the rest through {2, 3}:7, {2, 6}:8 or {5, 6}:9.
Pattern: "the MST is also optimal for a different objective", proved by assuming a better tree and using the Cycle Property on the edge it avoids.
Before moving on
- I can write the three steps of an exchange argument and use them on Max k-Sum and on an adjacent-swap ordering problem.
- I can state and prove the Cut Property and the Cycle Property, choosing the exchanged edge correctly in each proof.
- I can run Prim's algorithm and Kruskal's algorithm by hand and list the edges in the order each one chooses them.
- I can run Reverse-Delete and say which edges it deletes, and give the running time of each MST algorithm with its reason.
- I can run Select-Intervals (strict test, closed intervals) and give a counterexample to another greedy rule.
- I can compute the Fractional Knapsack array x in item order and explain the ε-exchange.
Exercises
Solution
(1) For contradiction, assume OPT ≠ ALG. (2) Construct OPT′ by exchanging something in OPT for the corresponding choice of ALG. (3) Show that OPT′ is feasible and better than OPT (a contradiction) or at least as good and closer to ALG (then repeat). Cut Property: for any cut S in G, the lightest edge crossing S is in the MST; it justifies Prim and Kruskal. Cycle Property: for any cycle C in G, the heaviest edge in C is not in the MST; it justifies Reverse-Delete.Solution
{1, 3}, {3, 4}, {2, 4}, {4, 5}, weight 2 + 3 + 1 + 6 = 12. Round by round: from {1} the candidates are {1, 2}:4, {1, 3}:2; from {1, 3}: {1, 2}:4, {2, 3}:5, {3, 4}:3, {3, 5}:8; from {1, 3, 4}: {1, 2}:4, {2, 3}:5, {2, 4}:1, {3, 5}:8, {4, 5}:6; from {1, 2, 3, 4}: {3, 5}:8, {4, 5}:6.Solution
{2, 4}, {1, 3}, {3, 4}, {4, 5}. In increasing order: {2, 4}:1 keep, {1, 3}:2 keep, {3, 4}:3 keep, {1, 2}:4 reject (1–3–4–2), {2, 3}:5 reject (2–4–3), {4, 5}:6 keep, {3, 5}:8 reject. Same tree as Prim, different order.Solution
{5, 6}, {2, 6}, {2, 5}, {1, 5}. In decreasing order: {5, 6}:9 delete, {2, 6}:8 delete, {2, 3}:7 keep (now the only link to {3, 6}), {2, 5}:6 delete, {1, 5}:5 delete, then {1, 4}:4, {3, 6}:3, {4, 5}:2, {1, 2}:1 are all bridges and stay. The remaining tree is the MST of weight 17.Solution
[1, 4], [5, 7], [8, 11], [12, 16]. Choose [1, 4]; skip [3, 5] and [1, 6] (they start at or before 4); choose [5, 7]; skip [3, 9], [5, 9], [6, 10]; choose [8, 11]; skip [8, 12] and [2, 14]; choose [12, 16]. Four intervals.Solution
[1, 1, 1/6]. Ratios 2.5, 2, 1.5: take item 1 (weight 4, 4 left), item 2 (weight 3, 1 left), then 1/6 of item 3. Value 10 + 6 + 9/6 = 17.5.Solution
(a) True. If e = {u, v} is the lightest edge, it is the lightest edge crossing the cut S = {u}, so the Cut Property puts it in the MST. (b) False. The heaviest edge is excluded only if it lies on a cycle; if it is a bridge (for example, the only edge at a vertex of degree 1), every spanning tree must contain it. (c) False. Kruskal lists edges by increasing weight, Prim in the order the tree grows from vertex 1; in Section 4.4's lecture example Kruskal gives {1, 4}, {2, 5}, {5, 6}, {3, 4}, {2, 3} and Prim gives {1, 4}, {3, 4}, {2, 3}, {2, 5}, {5, 6}.Solution
The answer proves only half of the claim. It shows the added edge belongs to the new MST but never explains why the other n − 2 edges of T are still in the new MST, which is exactly the "common mistake" named in the official solution. The missing paragraph: for each f ≠ e in T, removing f from T gives a cut that only f crosses in T; f was the lightest edge crossing it, increasing w(e) does not change that, so f stays by the Cut Property. The running-time line should also say where O(m + n) comes from: BFS on a tree costs O(n), and scanning the edges costs O(m).Solution
Algorithm. Keep only the edges lighter than e and check whether u can reach v using them. If it can, e is not in the MST; otherwise it is.
ALG(G, e):
u, v = endpoints of e
H = graph on V with only the edges f such that w(f) < w(e)
d = BFS(H, u)
if d[v] is infinity: return "e is in the MST"
else: return "e is not in the MST"
Correctness. If v is reachable from u in H, there is a path P from u to v whose edges are all lighter than e, so P + e is a cycle on which e is the heaviest edge, and by the Cycle Property e is not in the MST. If v is not reachable, let S be the set of vertices reached from u in H; then u ∈ S and v ∉ S, so e crosses S. Every edge lighter than e that crosses S would have let BFS leave S, so there is none: every other edge crossing S is heavier than e. Thus e is the lightest edge crossing S, and by the Cut Property e is in the MST.
Running time. Building H takes one pass over the adjacency list, O(m + n); BFS on H takes O(m + n); checking d[v] takes O(1). The total is O(m + n).
Course Ch. 4 · Sep 24–Oct 85. Dynamic programming I: method, LIS, LPS, edit distance
Course Chapter 4 opens with a sentence worth memorizing: dynamic programming (DP) "can be summarized as 'recursion with a table.'" Instead of solving a problem in one sweep, you solve every smaller version of it, smallest first, writing each answer into a table, and you build every new answer out of answers already written down. This chapter covers the four sections of course Chapter 4 that work on sequences: the method itself on Max in Array (section 4.1), the Longest Increasing Subsequence (4.2), the Longest Palindromic Subsequence (4.3) and Edit Distance (4.5). The other two sections, 0/1 Knapsack (4.4) and Independent Set in Trees (4.6), together with the catalog of DP patterns and Problem Set 4, are in Chapter 6. On the final, this chapter feeds Problem 1 and Problem 2 directly: the Practice Final asked for the LIS array d (Problem 1d) and for an edit distance (Problem 2b), and both Midterm 2 and its practice exam asked for an LIS array, the last row of an edit-distance table and the first row of an LPS table. A DP answer is four things in a fixed order, subproblems, recurrence, algorithm, running time, and the whole difficulty lies in choosing subproblems whose answers can be built from smaller ones.
5.1 The dynamic-programming method, on Max in Array
In plain words. A dynamic program answers a big question by first answering many smaller versions of the same question, starting from the smallest. Each smaller answer is written into a table, and each new entry is computed from entries already in the table by a fixed rule. When the table is full, the answer to the original question is read off one of its entries. The course always writes such an algorithm in the same four steps, and the exam grades those four steps.
- The course format replaces "algorithm, correctness, running time" with four steps: Subproblems (which subproblems, and which one is returned), Recurrence (how each is solved from smaller ones, with base cases, and why that holds), Algorithm (pseudocode filling an array d), Running time.
- In the notes' words, the answer to "why does the recurrence hold?" "suffices as a proof that the algorithm is correct." There is no separate correctness proof for a DP.
- OPT is the reasoning (a mathematical quantity); d is the code (an array). The notes use "d" instead of "OPT" in pseudocode "to distinguish between the algorithm itself … and the reasoning behind the algorithm."
- The running time "is typically the number of problems multiplied by the time per subproblem."
- The fill order must guarantee that every entry a cell reads has already been filled.
- The classic trap is a vague subproblem ("OPT[i] is the best so far"): the sentence must name the exact smaller input and the exact quantity.
- Subproblems: "Which subproblems will we solve? What will we return?"
- Recurrence: "How can we solve each subproblem using solutions to smaller subproblems? What are the base cases? Why does the recurrence hold? (The answer to the last question suffices as a proof that the algorithm is correct.)"
- Algorithm: "How do we use the recurrence to populate a DP table (typically an array d of integers)?" The lecture's summary: "basically recurrence, but OPT → d."
- Running time: "almost always = # subproblems × time per subproblem."
Notation used throughout: array indices start at 1, A[1:i] means A[1], A[2], …, A[i] (both ends included), and "for all i ∈ [n]" means for every i from 1 to n. The lecture writes "∀i: 1→n" for the same thing.
Problem
The lecture of September 24 introduced the method on a problem everyone already knows how to solve, so that the format is the only new thing. In the notes' phrasing: "The input is an array A of n distinct, positive integers. Our goal is to return the largest integer in A. Describe an O(n)-time algorithm for this problem, prove that it's correct, and analyze its running time." For A = [3, 1, 4, 1, 5] the answer is 5.
Subproblems
"For all i ∈ [n], let OPT[i] = max(A[1:i]). In other words, OPT[i] will be the largest element in the subarray A[1:i] (which includes A[1] and A[i]). After solving all n subproblems, we will return OPT[n]." The original problem is the largest subproblem, i = n.
Recurrence
The lecture drew the table as a row of boxes under A with an arrow from each box to the next: each entry looks only one step back. In the notes' words, OPT[i] either "stays the same" (as OPT[i−1]) or it "picks" A[i].
Algorithm
Create an array d of length n with every entry equal to A[1], so that the base case d[1] = A[1] is already in place. Then, for i = 2, 3, …, n in that order, set d[i] = max(d[i−1], A[i]); going left to right guarantees that d[i−1] is ready when d[i] needs it. Finally return d[n].
Max-in-Array-DP(A):
d = [A[1]]*n
for i = 2, ..., n:
d[i] = max(d[i-1], A[i])
return d[n]
| i | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| A[i] | 3 | 1 | 4 | 1 | 5 |
| d[i] | 3 | 3 | 4 | 4 | 5 |
Some cells worked out: d[2] = max(d[1], A[2]) = max(3, 1) = 3; d[3] = max(3, 4) = 4; d[5] = max(4, 5) = 5, which is returned. The array d = [3, 3, 4, 4, 5] is the running maximum, so d[i] really equals max(A[1:i]) for every i, which is exactly what the subproblem sentence promised.
Correctness
The technique is exhaustive cases, and it is the form every DP correctness argument takes in this course. The notes: "This recurrence holds because max(A[1:i]) is either the largest integer in A[1:i−1] (i.e., OPT[i−1]), or it is A[i]; whichever is larger is the value of OPT[i]." Spelled out: the largest element of A[1:i] sits at some position. Either that position is i, or it is one of 1, …, i−1, in which case the element is the largest of A[1:i−1], which is OPT[i−1] by definition. These two cases cover every possibility, so the larger of the two candidates is the answer. The base case is right because the maximum of a one-element array is that element, and returning OPT[n] is right because OPT[n] = max(A[1:n]) is the original question.
Running time
"The algorithm makes n − 1 iterations, and each iteration takes O(1) time, so the total running time is O(n)." In the slogan: n subproblems × O(1) per subproblem.
Variants from the same lectures
Sum of an array. The September 24 lecture asked for "a DP for Sum of Array" right away, and it was Problem 1 of the Day 1 worksheet (worked in Section 5.5): OPT[i] = sum of A[1:i], OPT[1] = A[1], OPT[i] = OPT[i−1] + A[i], return OPT[n], O(n). The lecture then named the shared shape Pattern 1: "Input: array A. Subproblems: ∀i: 1→n, OPT[i] = answer given A[1:i]."
Fibonacci, bottom-up versus top-down. On October 1 the lecture took a "tangent" on Fibonacci numbers F(1) = F(2) = 1, F(n) = F(n−1) + F(n−2). The bottom-up DP sets OPT[i] = F(i), fills d = [1]*n from i = 3 up to n with d[i] = d[i−1] + d[i−2], and runs in O(n). Pure recursion (return ALG(n−1) + ALG(n−2)) is correct but "slow: ≈ O(2ⁿ)", more precisely O(φⁿ) with φ ≈ 1.618, because the same calls are repeated: in the tree of calls for ALG(6), ALG(4) is computed twice and ALG(3) three times. Memoization, "store intermediate results in a global array," turns the recursion into top-down DP, which is also O(n). The lecture marked bottom-up as "recommended", and every pseudocode in this guide is bottom-up.
Saving space. On October 13 the lecture observed that Max in Array only ever reads d[i−1], so a single integer can replace the array (d = A[1]; for i = 2, …, n: d = max(d, A[i]); return d), which is the "usual Max(A)". The trick "applies whenever d[i] doesn't depend on all of d[1:i−1]"; it does not apply to LIS, whose recurrence reads every earlier entry. The drawbacks named in lecture: table values are harder to interpret, and the solution itself is harder to reconstruct ("no parent pointers"). The knapsack version of the trick is in Chapter 6.
Check-in 5.1. Cover the boxes above and write the four steps of a DP answer from memory, one line each, including what the Recurrence step must justify.
Answer
(1) Subproblems: define OPT for every index in words and say which entry is returned. (2) Recurrence: OPT in terms of smaller subproblems, the base cases, and why the recurrence holds (this is the correctness proof). (3) Algorithm: pseudocode filling an array d in an order that respects the recurrence. (4) Running time: number of subproblems × time per subproblem.Check-in 5.2. Run Max-in-Array-DP on A = [2, 9, 4, 9, 1]: fill in d, then write what is returned.
| i | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| A[i] | 2 | 9 | 4 | 9 | 1 |
| d[i] |
Answer
d = [2, 9, 9, 9, 9]; the algorithm returns d[5] = 9.5.2 Longest increasing subsequence
In plain words. A subsequence keeps some elements of an array, in their original order, possibly skipping others, and it is increasing if each kept element is larger than the one before. The goal is the length of the longest such subsequence. The obvious subproblem, "the best answer for the first i elements," does not work, because it forgets which value the best subsequence ends on. The fix, which the lecture called the LIS trick, is to insist that the subsequence for subproblem i ends exactly on A[i], and then to return the largest entry of the table rather than the last one.
- Input: an array A of n integers. Output: the length of a longest increasing (strictly increasing) subsequence.
- Subproblems: OPT[i] = length of the LIS of A that must end on A[i], for every i ∈ [n]; return max(OPT).
- Recurrence: OPT[1] = 1; OPT[i] = 1 + max OPT[j] over the candidates j < i with A[j] < A[i], and OPT[i] = 1 if there is no candidate.
- Algorithm: two nested loops filling d = [1]*n from left to right; return max(d).
- Running time O(n²): computing d[i] scans i − 1 earlier entries.
- Parent pointers p[i] = j recover the subsequence itself in O(n) extra time.
- The trap: returning d[n] instead of max(d).
- Subsequence
- In the notes: "a subarray of A, but with some elements possibly skipped." For A = [3, 5, 5, 1, 3, 2], the sequences [3, 5, 3], [5], [5, 5] and [5, 2] are subsequences; [1, 5] and [1, 1] are not.
- Increasing
- Each element is strictly larger than the one before it, which is why the recurrence tests A[j] < A[i] and not ≤.
Problem
"The input is an array A of n integers. Our goal is to return the length of the longest increasing subsequence (LIS) of A. Describe an O(n²)-time algorithm for this problem, prove that it's correct, and analyze its running time." The lecture's example is A = [5, 1, 2, 7, 4, 6, 3]: [5], [4], [1, 2] and [1, 2, 4] are increasing subsequences, [3, 6] is not a subsequence (3 comes after 6), and [7, 4] is a subsequence but not increasing. The LIS is [1, 2, 4, 6], so the algorithm should return 4.
Why the obvious subproblem fails
The lecture first tried Pattern 1: OPT[i] = length of the LIS in A[1:i]. For the example this starts OPT = [1, 1, 2, 3, …] and then gets stuck at i = 5, where the new element is 4. A[1:4] has an increasing subsequence of length 3, namely [1, 2, 7], but 4 cannot extend it; 4 does extend the shorter [1, 2]. The number 3 does not say what the subsequence ends on, so OPT[5] cannot be computed from it. The notes put it this way: "It might seem more natural to let OPT[i] denote the length of the LIS of A[1:i]. This is a reasonable idea, but it's not clear how we can use a recurrence to solve this set of subproblems."
Subproblems
The lecture's general form of the trick, which it later listed as one of the three starred patterns: "OPT[i] = answer given A[1:i], but we must 'use' A[i]." For the lecture's example, OPT = [1, 1, 2, 3, 3, 4, 3]: the best subsequence ending on 7 is [1, 2, 7], the best ending on 4 is [1, 2, 4], the best ending on 6 is [1, 2, 4, 6], and the best ending on the final 3 is [1, 2, 3]. The answer is the maximum entry, 4; the last entry is only 3.
Recurrence
OPT[i] = 1 + maxj ∈ C OPT[j], where C = {j : j < i and A[j] < A[i]},
and OPT[i] = 1 if C = ∅. The lecture's margin note on the max: it "might be 0".In the notes' words, we find "the 'best' entry A[j] to 'come from' before 'jumping' to A[i]," and "A[j] is an option if and only if j < i and A[j] < A[i]."
Algorithm
Start with d = [1]*n, which already holds every base value (a subsequence consisting of A[i] alone has length 1). For i = 2, …, n, look at every earlier index j = 1, …, i − 1; whenever A[j] < A[i] (so A[i] may follow A[j]) and 1 + d[j] beats the current d[i], raise d[i] to 1 + d[j]. Because i increases, every d[j] with j < i is final when it is read. Return the maximum entry of d.
LIS(A):
d = [1]*n
for i = 2, ..., n:
for j = 1, ..., i-1:
if A[j] < A[i] and d[i] < 1 + d[j]:
d[i] = 1 + d[j]
return max(d)
The lecture's second example, A = [5, 2, 5, 6, 3, 7, 4, 6], which was also Problem 2 of the Day 1 worksheet ("What does the LIS DP return?"), traced in full:
| i | A[i] | candidates j (A[j] < A[i]) with d[j] | d[i] | a subsequence achieving d[i] |
|---|---|---|---|---|
| 1 | 5 | none | 1 | [5] |
| 2 | 2 | none | 1 | [2] |
| 3 | 5 | j = 2 (1) | 2 | [2, 5] |
| 4 | 6 | j = 1, 2, 3 (1, 1, 2) | 3 | [2, 5, 6] |
| 5 | 3 | j = 2 (1) | 2 | [2, 3] |
| 6 | 7 | j = 1, …, 5 (1, 1, 2, 3, 2) | 4 | [2, 5, 6, 7] |
| 7 | 4 | j = 2, 5 (1, 2) | 3 | [2, 3, 4] |
| 8 | 6 | j = 1, 2, 3, 5, 7 (1, 1, 2, 2, 3) | 4 | [2, 3, 4, 6] |
Some cells worked out: at i = 3, A[1] = 5 is not smaller than 5 (strictly increasing), so only j = 2 qualifies and d[3] = 1 + 1 = 2. At i = 6, every earlier element is below 7, and the best of them is d[4] = 3, so d[6] = 4. At i = 8, A[4] = 6 and A[6] = 7 are excluded because they are not smaller than 6, and the best remaining candidate is d[7] = 3. So d = [1, 1, 2, 3, 2, 4, 3, 4] and the algorithm returns max(d) = 4, matching the worksheet's official answer. The lecture annotated d[4] = 3 as "represents [–, –, 6]" and d[6] = 4 as that subsequence "+ 7".
Correctness
The technique is again exhaustive cases on the element just before A[i]. The notes: "the LIS S that ends on A[i] must be of the form S = T + A[i], where T is an LIS that ends on A[j] for some j ∈ C. By finding the maximum OPT[j] over all j ∈ C, we correctly calculate OPT[i]." In full: take a longest increasing subsequence ending on A[i]. Either it is just [A[i]] (length 1), or it has an element immediately before A[i], say A[j]. Then j < i (order is kept) and A[j] < A[i] (increasing), so j ∈ C, and the part up to A[j] is an increasing subsequence ending on A[j], of length at most OPT[j]. Conversely, any increasing subsequence ending on A[j] with j ∈ C can be extended by A[i]. So the best length is 1 plus the largest OPT[j] over C. Returning max(OPT) is right because the overall LIS ends on some A[i], and its length is then OPT[i].
Running time
"Calculating d[i] takes O(i) time, so the total running time is O(n²)." Exactly, the inner loop runs 1 + 2 + ⋯ + (n − 1) = n(n − 1)/2 times, plus O(n) for max(d).
Recovering the subsequence: parent pointers
On September 29 the lecture asked "How to find the LIS itself?" and answered "Parent pointers (≈ BFS)". The notes: "whenever we update d[i] = 1 + d[j], we also set p[i] = j … Given d and p, we can trace p to recover the LIS itself in O(n) time. Unless specified otherwise, this technique of maintaining 'parent pointers' to find the 'solution itself' applies to every DP in this course." Start from an index where max(d) occurs, follow p back to an index with no parent, and reverse the list. Because the code only updates when 1 + d[j] is strictly larger, the parent is the smallest j achieving the maximum, which is the tie rule Homework 4 used.
For the lecture's example A = [3, 1, 5, 2, 4, 6, 3]: d = [1, 1, 2, 2, 3, 4, 3], with p[3] = 1, p[4] = 2, p[5] = 4, p[6] = 5, p[7] = 4. The maximum 4 is at index 6, and 6 → 5 → 4 → 2 gives indices 2, 4, 5, 6, that is, the subsequence [1, 2, 4, 6].
Variant: longest increasing contiguous subsequence. If the subsequence must be a subarray (Day 1 worksheet Problem 3, also Problem Set 4.2 and Practice Midterm 2 Problem 2), the same trick works but the only candidate is j = i − 1: OPT[i] = OPT[i−1] + 1 if A[i] > A[i−1] and 1 otherwise, return max(OPT), O(n). For A = [3, 1, 2, 4, 2, 5], OPT = [1, 1, 2, 3, 1, 2] and the answer is 3. The full write-up is in Section 5.5.
Variant: longest decreasing subsequence. Replace A[j] < A[i] by A[j] > A[i]; nothing else changes.
Check-in 5.3. Run LIS on A = [3, 8, 4, 9, 2, 5, 7, 6]: fill in d, then write what is returned.
| i | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| A[i] | 3 | 8 | 4 | 9 | 2 | 5 | 7 | 6 |
| d[i] |
Answer
d = [1, 2, 2, 3, 1, 3, 4, 4]; the algorithm returns max(d) = 4.Check-in 5.4. For the same A, write the parent pointer p[i] of every i with d[i] > 1 (ties go to the smallest j, as in the code), then start at the first index where max(d) occurs and write out the LIS the algorithm finds.
Answer
p[2] = 1, p[3] = 1, p[4] = 2, p[6] = 3, p[7] = 6, p[8] = 6. Starting at index 7: 7 → 6 → 3 → 1, so the indices are 1, 3, 6, 7 and the LIS is [3, 4, 5, 7].5.3 Longest palindromic subsequence
In plain words. A palindrome reads the same forwards and backwards, and the goal is the length of the longest subsequence of a string that is a palindrome. A palindrome is built from both ends inward, so the subproblems are indexed by a stretch A[i:j] of the string with a first and a last character. If the two end characters match, they can be the two ends of the palindrome around the best answer for the inside; if not, one of them must be left out. The table is a triangle that is filled from the bottom row up.
- Input: a string A of length n. Output: the length of a longest palindromic subsequence (LPS).
- Subproblems: OPT[i][j] = length of an LPS of A[i:j], for i ≤ j; return OPT[1][n]. Only the upper-right triangle of the n × n table is used.
- Recurrence: OPT[i][i] = 1; for i < j, OPT[i][j] = OPT[i+1][j−1] + 2 if A[i] = A[j], and max(OPT[i+1][j], OPT[i][j−1]) otherwise.
- Each cell reads cells below and to the left, so fill rows from i = n up to 1, each row left to right.
- Running time O(n²): O(n²) cells, O(1) each.
- The course's d starts as all zeros, so the lower triangle reads 0 and a requested row k begins with k − 1 zeros.
- Trap: filling from the top row down, which reads cells that are not computed yet.
Problem
"The input is a string A of length n. Our goal is to return the length of a longest palindromic subsequence (LPS) of A. Describe an O(n²)-time algorithm for this problem, prove that it's correct, and analyze its running time." The notes' example: for A = abracadabra, aca and abba are palindromic subsequences. The lecture's examples of palindromes were a, aa, aba and racecar (ab is not one), and its example string is A = acbcbda, whose LPS has length 5: acbca (positions 1, 2, 3, 4, 7) or abcba (positions 1, 3, 4, 5, 7).
Subproblems
The lecture later listed this as Pattern 4: "OPT[i][j] = OPT given A[i:j]", used by LPS.
Recurrence
OPT[i][j] = OPT[i+1][j−1] + 2 if A[i] = A[j]; OPT[i][j] = max(OPT[i+1][j], OPT[i][j−1]) otherwise.
When j = i + 1 and A[i] = A[j], the formula reads OPT[i+1][i], a cell below the diagonal; in the course's table it holds 0, which is the right value for the empty string between two adjacent characters, so the result is 0 + 2 = 2.
Algorithm
The lecture drew the dependency picture: cell (i, j) reads the cell diagonally below-left (i+1, j−1), the cell below (i+1, j) and the cell to the left (i, j−1). In the notes: "Each OPT[i][j] depends on entries below and to the left of it, so one way to fill the DP table is row by row, starting with the last row." So the outer loop runs i from n down to 1, sets the diagonal cell d[i][i] = 1, and then fills the rest of row i from left to right by the recurrence; the answer is the top-right cell.
LPS(A):
d = [0]*(n * n)
for i = n, ..., 1:
d[i][i] = 1 # base case
for j = i+1, ..., n:
if A[i] = A[j]:
d[i][j] = d[i+1][j-1] + 2
else:
d[i][j] = max(d[i+1][j], d[i][j-1])
return d[1][n]
The table for the lecture's A = acbcbda, exactly as drawn on September 29 (zeros in the unused lower triangle):
| i \ j | 1: a | 2: c | 3: b | 4: c | 5: b | 6: d | 7: a |
|---|---|---|---|---|---|---|---|
| 1: a | 1 | 1 | 1 | 3 | 3 | 3 | 5 |
| 2: c | 0 | 1 | 1 | 3 | 3 | 3 | 3 |
| 3: b | 0 | 0 | 1 | 1 | 3 | 3 | 3 |
| 4: c | 0 | 0 | 0 | 1 | 1 | 1 | 1 |
| 5: b | 0 | 0 | 0 | 0 | 1 | 1 | 1 |
| 6: d | 0 | 0 | 0 | 0 | 0 | 1 | 1 |
| 7: a | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
Some cells worked out: (3, 5) is bcb; b = b, so d[4][4] + 2 = 3. (2, 4) is cbc; c = c, so d[3][3] + 2 = 3. (1, 4) is acbc; a ≠ c, so max(d[2][4], d[1][3]) = max(3, 1) = 3. (2, 6) is cbcbd; c ≠ d, so max(d[3][6], d[2][5]) = max(3, 3) = 3. (1, 7), the answer: a = a, so d[2][6] + 2 = 3 + 2 = 5. The lecture's arrows showed exactly this: the 5 comes from the 3 at (2, 6), which comes from the 3 at (3, 5).
Correctness
Exhaustive cases on the two end characters, as in the notes: "If i = j, then A[i:j] is just a single character, so OPT[i][i] = 1. If i < j and A[i] = A[j], then the LPS of A[i:j] starts with A[i], ends with A[j], and contains an LPS of A[i+1:j−1] in between. Otherwise, if A[i] ≠ A[j], then the LPS of A[i:j] must exclude A[i] or A[j]." The unequal case is clear: a palindrome that used both ends would begin and end with different characters, which is impossible, so the LPS lies inside A[i+1:j] or inside A[i:j−1], and the max takes the better. For the equal case, any palindromic subsequence of A[i:j] that does not use both ends can be changed into one that does without getting shorter: remove whichever end character it uses (if any) and wrap what remains in A[i] … A[j]. So some LPS uses both ends, and its middle is a palindromic subsequence of A[i+1:j−1], of length at most OPT[i+1][j−1].
Running time
"The DP table has O(n²) entries, and each entry takes O(1) time to compute, so the total running time is O(n²)." (About n²/2 cells of the triangle are actually filled.)
Variant: longest palindromic substring. The lecture left this as "On your own" on September 29. With contiguity required, let OPT[i][j] be True if A[i:j] is a palindrome: OPT[i][i] = True, OPT[i][i+1] = (A[i] = A[i+1]), and OPT[i][j] = (A[i] = A[j]) and OPT[i+1][j−1] for j ≥ i + 2. Fill in the same order and return the largest j − i + 1 with OPT[i][j] True; O(n²).
Check-in 5.5. Fill in the LPS table for A = bbab (upper triangle; start from the bottom row), then write the answer.
| i \ j | 1: b | 2: b | 3: a | 4: b |
|---|---|---|---|---|
| 1: b | ||||
| 2: b | ||||
| 3: a | ||||
| 4: b |
Answer
Row 1: [1, 2, 2, 3]; row 2: [0, 1, 1, 3]; row 3: [0, 0, 1, 1]; row 4: [0, 0, 0, 1]. The answer is d[1][4] = 3 (bab or bbb).5.4 Edit distance
In plain words. The edit distance from one string to another is the smallest number of single-character changes that turn the first into the second, where a change is an insertion, a deletion or a replacement. Since there are two strings, a subproblem has two indices: how much of the first string and how much of the second have been dealt with. Every way of finishing the job ends in one of three ways (insert the last target character, delete the last source character, or turn the last source character into the last target character), and the recurrence takes the cheapest. The table is a rectangle filled row by row, and its bottom-right cell is the answer.
- Input: strings A (length m) and B (length n). Output: the edit distance from A to B, the minimum number of insertions, deletions and replacements turning A into B.
- Subproblems: OPT[i][j] = edit distance from A[1:i] to B[1:j], for 0 ≤ i ≤ m and 0 ≤ j ≤ n (index 0 is the empty prefix); return OPT[m][n].
- Base cases: OPT[0][j] = j (j insertions) and OPT[i][0] = i (i deletions).
- Recurrence: OPT[i][j] = min(OPT[i][j−1] + 1, OPT[i−1][j] + 1, OPT[i−1][j−1] + δij), with δij = 0 if A[i] = B[j] and 1 otherwise.
- In the table: left neighbor + 1 (insert), upper neighbor + 1 (delete), diagonal + 0 or 1 (replace or keep). Shortcut: if A[i] = B[j], copy the diagonal.
- Running time O(mn): (m + 1)(n + 1) cells, O(1) each.
- Traps: forgetting row 0 and column 0, and reporting a "last row" without its first entry m.
Problem
The notes define the edit distance from A to B as "the minimum number of 'moves' we need to make to turn A into B. There are three valid types of moves: insert a character anywhere in A, delete a character anywhere from A, and replace any character in A with any character. (A replacement is equivalent to a deletion followed by an insertion, but it counts as one move rather than two.)" The problem statement: "The input is (A, B), where A and B are strings of length m and n, respectively. Our goal is to return the edit distance from A to B. Describe an O(mn)-time algorithm for this problem, prove that it's correct, and analyze its running time." The lecture's story was "typos, genetics", with the examples ED(cat, bat) = 1 (replace c), ED(cat, cats) = 1 (insert s), ED(cat, bar) = 2 (replace c and t) and ED(cat, dog) = 3. The running example is A = star, B = water, whose edit distance is 3.
Subproblems
This is the lecture's starred Pattern 6, "OPT[i][j] = OPT given (A[1:i], B[1:j])", used for any problem whose input is two sequences. Index 0 is allowed so that the empty prefix A[1:0] is a legal subproblem; the table has m + 1 rows and n + 1 columns.
Recurrence
"The base cases are OPT[0][j] = j and OPT[i][0] = i. (Editing the empty string to a string of length j takes j insertions, and editing a string of length i into the empty string takes i deletions.)" For i, j ≥ 1, the lecture asked how to turn star into wate, that is, "How to end on 'e'?", and listed three ways:
- star → wat, then insert e at the end: OPT[i][j−1] + 1.
- sta → wate, then delete r: OPT[i−1][j] + 1.
- sta → wat, then replace r with e: OPT[i−1][j−1] + 1. If the last characters already agree, as in star → water where both end in r, this step costs 0: "star → water = sta → wate."
OPT[i][j] = min( OPT[i][j−1] + 1, OPT[i−1][j] + 1, OPT[i−1][j−1] + δij ),
where δij = 0 if A[i] = B[j] and 1 otherwise. Shortcut (lecture and notes): if A[i] = B[j], then OPT[i][j] = OPT[i−1][j−1].The lecture's picture of a cell: an arrow left labelled +1, an arrow up labelled +1, and an arrow diagonally up-left labelled "+0/1". Its October 8 recap: "min + 1, except if A[i] = B[j], ↖ + 0."
Algorithm
Write the base cases first: row 0 is 0, 1, 2, …, n and column 0 is 0, 1, 2, …, m. Then fill the remaining cells "one row at a time, and within each row, … from left to right," which guarantees that the left, upper and diagonal neighbors of every cell are ready. Each cell takes the minimum of left + 1 and up + 1, and then compares with the diagonal, adding 0 when the characters match and 1 when they do not.
Edit-Distance(A, B)
d = [0]*((m+1) * (n+1))
for j = 1, ..., n:
d[0][j] = j # base case (row 0)
for i = 1, ..., m:
d[i][0] = i # base case (column 0)
for i = 1, ..., m:
for j = 1, ..., n:
d[i][j] = min(d[i][j-1] + 1, d[i-1][j] + 1)
if A[i] = B[j]:
d[i][j] = min(d[i][j], d[i-1][j-1])
else:
d[i][j] = min(d[i][j], d[i-1][j-1] + 1)
return d[m][n]
The table for star → water, as drawn in lecture on October 1 and again on October 8 (rows are prefixes of A, columns prefixes of B, "" is the empty prefix):
| A \ B | "" | w | a | t | e | r |
|---|---|---|---|---|---|---|
| "" | 0 | 1 | 2 | 3 | 4 | 5 |
| s | 1 | 1 | 2 | 3 | 4 | 5 |
| t | 2 | 2 | 2 | 2 | 3 | 4 |
| a | 3 | 3 | 2 | 3 | 3 | 4 |
| r | 4 | 4 | 3 | 3 | 4 | 3 |
Some cells worked out. (s, w): left 1 + 1, up 1 + 1, diagonal 0 + 1 (s ≠ w); the minimum is 1 (replace s with w). (t, t): the characters match, so copy the diagonal (s, a) = 2; indeed st → wat costs 2 (replace s with w, insert a). (t, e): left (t, t) = 2 plus 1 = 3 is the minimum; the lecture drew this arrow from the 3 to the 2 on its left. (a, a): match, copy the diagonal (t, w) = 2. (r, a): left 4 + 1, up 2 + 1, diagonal 3 + 1 (r ≠ a); the minimum is 3, and the lecture's arrow points up to the 2. (r, r), the answer: match, copy the diagonal (a, e) = 3. So ED(star, water) = 3; one optimal sequence is star → wtar → watar → water (replace s with w, insert a, replace the second a with e). This table, row by row, is also the official answer to Day 3 worksheet Problem 3: "Row 0 is [0, 1, 2, 3, 4, 5], Row 1 is [1, 1, 2, 3, 4, 5], Row 2 is [2, 2, 2, 2, 3, 4], Row 3 is [3, 3, 2, 3, 3, 4], and Row 4 is [4, 4, 3, 3, 4, 3]."
Correctness
Exhaustive cases on the last character of the target, as in the notes: "Since OPT[i][j] edits A[1:i] such that its last character is B[j], it must make one of the following three moves: Edit A[1:i] into B[1:j−1] and insert B[j]. Edit A[1:i−1] into B[1:j] and delete A[i]. Edit A[1:i−1] into B[1:j−1] and replace A[i] with B[j]. (This 'replacement' costs 0 if A[i] = B[j] and 1 otherwise.)" Put differently: in an optimal edit, the final character B[j] was either inserted (case 1), or it came from A[i], unchanged or replaced (case 3), or else A[i] did not survive, so it was deleted and B[j] came from earlier (case 2). The three cases cover every possibility, each costs exactly the smaller subproblem's optimum plus the stated amount, so the minimum of the three is OPT[i][j]. The base cases are forced: from or to an empty string, only insertions or only deletions help.
Running time
"The DP table has (m+1)(n+1) = O(mn) entries, and each entry takes O(1) time to compute, so the total running time is O(mn)." The notes add that the shortcut for A[i] = B[j] "doesn't enable us to improve the asymptotic running time of the algorithm, but it does speed up the process of running the algorithm by hand."
Recovering the moves. With parent pointers (or by walking back from (m, n) to whichever neighbor achieved the minimum), the actual moves are recovered in O(m + n) extra time: a step left is an insertion of B[j], a step up is a deletion of A[i], and a diagonal step is a replacement (or a free keep when the letters match).
Variant: different costs. If insertions, deletions and replacements cost cins, cdel and crep, the three terms become OPT[i][j−1] + cins, OPT[i−1][j] + cdel and OPT[i−1][j−1] + crep·δij, with base cases j·cins and i·cdel; the table and the O(mn) bound are unchanged.
Check-in 5.6. Fill in the edit-distance table for A = ab and B = ba, then write the edit distance.
| A \ B | "" | b | a |
|---|---|---|---|
| "" | |||
| a | |||
| b |
Answer
Rows "", a, b: [0, 1, 2], [1, 1, 1], [2, 1, 2]. The edit distance is 2 (one move cannot work: ab and ba have the same length and differ in both positions).Check-in 5.7. Fill in the table for A = ape and B = pea, then write the last row of d and the edit distance.
| A \ B | "" | p | e | a |
|---|---|---|---|---|
| "" | ||||
| a | ||||
| p | ||||
| e |
Answer
Rows "", a, p, e: [0, 1, 2, 3], [1, 1, 2, 2], [2, 1, 2, 3], [3, 2, 1, 2]. The last row is [3, 2, 1, 2] and the edit distance is 2 (delete the leading a, insert a at the end).5.5 Worked problems from the Day 1 to Day 4 worksheets
The in-class worksheets for these days are the closest thing to practice problems for sections 4.1 to 4.5 (Problem Set 4, worked in Chapter 6, reuses two of them). Each statement below is copied from the course page, and each solution follows the official one, expanded. Attempt each on paper before opening it.
Day 1, Problem 1. Sum of an array
Solution
Subproblems. For all i ∈ {1, …, n}, let OPT[i] denote the sum of A[1:i]; we will return OPT[n].
Recurrence. The base case is OPT[1] = A[1], and for i ≥ 2, OPT[i] = OPT[i−1] + A[i]. The recurrence holds because the sum of A[1:i] is equal to the sum of A[1:i−1] plus A[i].
Algorithm.
ALG(A):
d = [A[1]]*n
for i = 2, ..., n:
d[i] = d[i-1] + A[i]
return d[n]
Running time. The algorithm makes n − 1 iterations and each takes O(1) time, so the total running time is O(n).
Pattern: Pattern 1, a prefix subproblem returning OPT[n].
Day 1, Problem 3. Longest increasing contiguous subsequence
Solution
Subproblems. For all i ∈ {1, …, n}, let OPT[i] denote the length of the longest contiguous increasing subsequence in A[1:i] that must end on A[i]; we will return max(OPT).
Recurrence. The base case is OPT[1] = 1. For i ≥ 2, OPT[i] = 1 + OPT[i−1] if A[i] > A[i−1], and OPT[i] = 1 + 0 otherwise. The recurrence holds because the longest increasing subarray that ends on A[i] must include A[i] (hence the "1") as well as possibly, if A[i] > A[i−1], a portion that ends on A[i−1]; OPT[i−1] is the maximum length of that portion. If A[i] ≤ A[i−1], the run cannot continue through A[i−1], so the run is A[i] alone. The answer is max(OPT) because the best subarray can end anywhere.
Algorithm.
ALG(A):
d = [1] * n
for i = 2, ..., n:
if A[i] > A[i-1]:
d[i] += d[i-1]
return max(d)
Running time. The algorithm makes n − 1 iterations and each takes O(1) time, so the total running time is O(n). On the example, d = [1, 1, 2, 3, 1, 2] and the algorithm returns 3.
Pattern: the LIS trick with a single candidate j = i − 1. This problem is also Problem Set 4.2 and was Practice Midterm 2 Problem 2, word for word.
Day 2, Problem 1. The LPS table for abaca
Solution
| i \ j | 1: a | 2: b | 3: a | 4: c | 5: a |
|---|---|---|---|---|---|
| 1: a | 1 | 1 | 3 | 3 | 3 |
| 2: b | 0 | 1 | 1 | 1 | 3 |
| 3: a | 0 | 0 | 1 | 1 | 3 |
| 4: c | 0 | 0 | 0 | 1 | 1 |
| 5: a | 0 | 0 | 0 | 0 | 1 |
Official answer: "Row 1 is [1, 1, 3, 3, 3], Row 2 is [0, 1, 1, 1, 3], Row 3 is [0, 0, 1, 1, 3], Row 4 is [0, 0, 0, 1, 1], and Row 5 is [0, 0, 0, 0, 1]." Some cells: (3, 5) is aca, a = a, so d[4][4] + 2 = 3; (2, 5) is baca, b ≠ a, so max(d[3][5], d[2][4]) = max(3, 1) = 3; (1, 5) is abaca, a = a, so d[2][4] + 2 = 1 + 2 = 3. The LPS is aba or aca, length 3.
Pattern: interval table filled bottom row up; the zeros below the diagonal are part of the course's answer.
Day 3, Problem 2. Fibonacci numbers
Solution
Subproblems. For all i ∈ {1, …, n}, let OPT[i] = F(i); we will return OPT[n].
Recurrence. The recurrence is the definition of Fibonacci numbers: OPT[1] = OPT[2] = 1, and for all i ∈ {3, …, n}, OPT[i] = OPT[i−1] + OPT[i−2].
Algorithm.
ALG(n):
d = [1] * n
for i = 3, ..., n:
d[i] = d[i-1] + d[i-2]
return d[n]
Running time. The algorithm makes O(n) iterations and each takes O(1) time, so the total running time is O(n). For n = 7, d = [1, 1, 2, 3, 5, 8, 13].
Pattern: bottom-up evaluation of a given recurrence; plain recursion would be exponential.
Day 3, Problem 3. The edit-distance table for star and water
Solution
"Row 0 is [0, 1, 2, 3, 4, 5], Row 1 is [1, 1, 2, 3, 4, 5], Row 2 is [2, 2, 2, 2, 3, 4], Row 3 is [3, 3, 2, 3, 3, 4], and Row 4 is [4, 4, 3, 3, 4, 3]." The table and the cells worked out are in Section 5.4; the edit distance is d[4][5] = 3.
Pattern: Pattern 6; base row and column first, then row by row.
Day 4, Problem 1. Naming a problem for each pattern
Solution
Official answer: (A) Max in Array, (B) Longest Increasing Subsequence (LIS), (C) Edit Distance. (Sum of an array also fits (A), and the longest increasing contiguous subsequence also fits (B).) The full list of six patterns from the October 8 lecture is in Chapter 6.
Pattern: these are the three starred patterns of the lecture.
5.6 Homework-style one-point questions
Homework 4 was auto-graded, one point per answer, and its LIS and LPS questions are exactly the kind of hand trace that Problem 1 of the final asks for. The homework said "You are not expected to solve every homework problem using pencil and paper"; for the 100-element instances it was fine to run a program. On the exam the instances are small. Homework 4 had no edit-distance question; that question type appears in Section 5.7.
Type 1: what LIS returns, and the last entries of d
Homework 4, Question 1: "Consider the following input to LIS: A = [6, 7, 8, 1, 2, 3]. Suppose we run the O(n²)-time DP algorithm on A, breaking all ties in favor of the smaller index." Q1.1 "What does the algorithm return?" Q1.2 "What are the last 3 elements in d?" By hand: d[1] = 1; 7 > 6 gives d[2] = 2; 8 gives d[3] = 3; 1 is smaller than everything before it, so d[4] = 1; 2 can follow only the 1, so d[5] = 2; 3 can follow 1 and 2, so d[6] = 3. So d = [1, 2, 3, 1, 2, 3], the algorithm returns 3, and the last three elements of d are [1, 2, 3].
Type 2: the LIS found by the parent pointers
Q1.3: "What are the last three elements in the LIS implicitly found (i.e., if we maintained parent pointers) by the algorithm? (If max(d) appears multiple times in d, start at the appearance with the smallest index.)" Here max(d) = 3 appears at indices 3 and 6, so start at index 3; p[3] = 2 and p[2] = 1, giving the LIS [6, 7, 8], not [1, 2, 3]. The two tie rules matter: start at the first index holding max(d), and each p[i] is the smallest j that achieved d[i] (the code's strict "<" keeps the first one found).
Question 2 asked the same three things, plus the first three elements of the LIS, for a 100-element array; the accepted answers were: the algorithm returns 15, the last three elements of d are [12, 13, 9], and the LIS found by the parent pointers begins [3, 4, 22] and ends [78, 82, 88]. These are only checkable with a program, which is why the exam never uses instances of that size.
Type 3: what LPS returns
Homework 4, Question 3: "Consider the following input to LPS: A = "abcdb". Suppose we run the O(n²)-time DP algorithm on A. What does the algorithm return?" The accepted answer is 3. By hand, the only repeated letter is b (positions 2 and 5), so the best palindrome is b?b with one letter between, for example bcb or bdb; in the table, d[2][5] = d[3][4] + 2 = 1 + 2 = 3, and the first row is [1, 1, 1, 1, 3]. Question 4 asked the same for a 50-character string; the accepted answer was 36.
5.7 Past exam problems on this chapter
Every one-point part below is quoted from the exam; the answers are the official solutions, recomputed for this guide. They come from Midterm 2 (November 3), Practice Midterm 2 and the Practice Final. Note that Practice Final 1d uses the same instance as Practice Midterm 2 1c (the wording differs only by the words "in the array d"): one-point parts get reused. The last problem is the one five-point design problem from these exams that is built on edit distance.
Midterm 2, Problem 1c. The LIS array
Solution
[1, 2, 1, 3, 4, 4]. The second 2 cannot follow the first (not strictly larger), so d[3] = 1; 4 follows 2, 3 (d[4] = 3); 6 follows 2, 3, 4 (d[5] = 4); 5 also follows 2, 3, 4 (d[6] = 4).Midterm 2, Problem 1d. The last row of an edit-distance table
Solution
[4, 3, 2, 2]. Rows "", a, b, c, a are [0, 1, 2, 3], [1, 1, 1, 2], [2, 1, 2, 2], [3, 2, 2, 3], [4, 3, 2, 2]. Check: abca → baa in 2 moves (delete the first a, replace c with a).Midterm 2, Problem 1e. The first row of an LPS table
Solution
[1, 1, 3, 3]. Row 1 holds the LPS lengths of the prefixes a, ab, aba, abab. In the table, d[1][3] = d[2][2] + 2 = 3 (a = a) and d[1][4] = max(d[2][4], d[1][3]) = max(3, 3) = 3 (a ≠ b).Practice Midterm 2, Problem 1c (and Practice Final, Problem 1d). The LIS array
Solution
[1, 1, 2, 3, 2, 3]. 7 follows 5 or 1 (d = 2); 8 follows 7 (d = 3); 2 follows only 1 (d = 2); 3 follows 1 and 2 (d = 3). The Practice Final asked exactly this question as Problem 1d, with the same answer.Practice Midterm 2, Problem 1d. The last row of an edit-distance table
Solution
[4, 3, 3, 3]. Rows "", a, b, b, c are [0, 1, 2, 3], [1, 1, 1, 2], [2, 1, 2, 1], [3, 2, 2, 2], [4, 3, 3, 3]. Check: abbc → bab in 3 moves, for example insert b at the front (babbc), delete the last b (babc), delete c (bab).Practice Midterm 2, Problem 1e. The first row of an LPS table
Solution
[1, 1, 1, 3]. The prefixes a, ab, abc have no repeated letter (LPS 1); abcb contains bcb (LPS 3). In the table, d[2][4] = d[3][3] + 2 = 3 and d[1][4] = max(d[2][4], d[1][3]) = 3.Practice Final, Problem 2b. An edit distance
Solution
2. Rows "", a, b, b, c over columns "", b, a, b, c: [0, 1, 2, 3, 4], [1, 1, 1, 2, 3], [2, 1, 2, 1, 2], [3, 2, 2, 2, 2], [4, 3, 3, 3, 2]. Two moves suffice: insert b at the front (babbc), then delete the third letter b (babc). One move is impossible: the strings have the same length, so it would have to be a single replacement, but they differ in two positions (the first two letters), and one replacement fixes only one.Practice Midterm 2, Problem 4. Shuffling two strings
Solution
The official solution begins "Our approach is similar to the Edit Distance DP": two input sequences, so Pattern 6.
Subproblems. For all i ∈ {0, 1, …, m} and j ∈ {0, 1, …, n}, let OPT[i][j] be True if A[1:i] and B[1:j] can be merged to create C[1:i+j] and False otherwise. We will return OPT[m][n].
Recurrence. Base cases: OPT[0][0] = True; if i = 0, A[1:i] is empty, so OPT[0][j] is True if and only if B[1:j] = C[1:j]; similarly OPT[i][0] is True if and only if A[1:i] = C[1:i]. For i ≥ 1 and j ≥ 1,
OPT[i][j] = ((A[i] = C[i+j]) and OPT[i−1][j]) or ((B[j] = C[i+j]) and OPT[i][j−1]).
Why it holds. In any merge that creates C[1:i+j], the last character C[i+j] is the last character of A[1:i] or of B[1:j]. If it is A[i], then A[i] = C[i+j] and the rest is a merge of A[1:i−1] and B[1:j] creating C[1:i+j−1], which is OPT[i−1][j]; conversely, such a merge followed by A[i] creates C[1:i+j]. The B[j] case is analogous. If neither A[i] nor B[j] equals C[i+j], no merge exists and both terms are False.
Algorithm. Fill row 0, then column 0, then the rest row by row, left to right, as in Edit Distance.
ALG(A, B, C):
d = [False] * ((m+1) x (n+1)) # rows 0..m, columns 0..n
d[0][0] = True
for j = 1, ..., n: # row 0
d[0][j] = d[0][j-1] and (B[j] = C[j])
for i = 1, ..., m: # column 0
d[i][0] = d[i-1][0] and (A[i] = C[i])
for i = 1, ..., m:
for j = 1, ..., n:
if A[i] = C[i+j]: d[i][j] = (d[i][j] or d[i-1][j])
if B[j] = C[i+j]: d[i][j] = (d[i][j] or d[i][j-1])
return d[m][n]
Running time. There are (m + 1)(n + 1) = O(mn) subproblems, and each takes O(1) time, so the total running time is O(mn).
Trace on the example C = arbtat (rows "", a, ar, art; columns "", b, ba, bat; T = True, F = False): row 0 [T, F, F, F]; row 1 [T, F, F, F]; row 2 [T, T, F, F]; row 3 [F, T, T, T]. The answer d[3][3] is True. For C = rtabat, already d[1][0] and d[0][1] are False (C begins with r), and every entry except d[0][0] is False.
Pattern: Pattern 6 like Edit Distance, with "or" in place of "min" and Booleans in place of numbers. (The official pseudocode's column-0 loop says "i = 1, …, n"; it should run to m.)
Before moving on
- I can write the four steps of a DP answer from memory, with the subproblem sentence in the course's form.
- I can run the LIS DP by hand, return max(d), and recover the LIS with parent pointers and the smallest-index tie rule.
- I can fill an LPS table from the bottom row up and report any row, zeros included.
- I can fill an edit-distance table with row 0 and column 0, report its last row, and check the value with an explicit sequence of moves.
- I can explain each of the three recurrences by exhaustive cases.
Exercises
Solution
(1) Subproblems: "For all i ∈ …, let OPT[i] denote …; we will return …". (2) Recurrence: base cases plus OPT in terms of smaller subproblems, and why it holds. (3) Algorithm: pseudocode that fills d in an order respecting the recurrence and returns the right entry. (4) Running time: number of subproblems × time per subproblem. The correctness argument is the "why the recurrence holds" part of step 2: list the cases the optimal solution could fall into, say why they are exhaustive, and say why each is scored correctly.Solution
d = [1, 2, 2, 3, 3, 4]; the algorithm returns 4. d[3] = 2 (2 follows 1), d[4] = 3 (6 follows 1 and 5, or 1 and 2), d[5] = 3 (3 follows 1 and 2), d[6] = 4 (7 follows any length-3 subsequence).Solution
| i \ j | 1: b | 2: a | 3: n | 4: a | 5: n | 6: a |
|---|---|---|---|---|---|---|
| 1: b | 1 | 1 | 1 | 3 | 3 | 5 |
| 2: a | 0 | 1 | 1 | 3 | 3 | 5 |
| 3: n | 0 | 0 | 1 | 1 | 3 | 3 |
| 4: a | 0 | 0 | 0 | 1 | 1 | 3 |
| 5: n | 0 | 0 | 0 | 0 | 1 | 1 |
| 6: a | 0 | 0 | 0 | 0 | 0 | 1 |
Solution
| A \ B | "" | d | i | e | t |
|---|---|---|---|---|---|
| "" | 0 | 1 | 2 | 3 | 4 |
| t | 1 | 1 | 2 | 3 | 3 |
| i | 2 | 2 | 1 | 2 | 3 |
| d | 3 | 2 | 2 | 2 | 3 |
| e | 4 | 3 | 3 | 2 | 3 |
Solution
3. The table's rows "", h, o, r, s, e over columns "", r, o, s end with the row [5, 4, 4, 3]. Moves: horse → rorse (replace h with r) → rose (delete the second r) → ros (delete e).Solution
The LIS need not end on the last element, so d[n] is only the best subsequence ending on A[n]. On the lecture's A = [5, 1, 2, 7, 4, 6, 3], d = [1, 1, 2, 3, 3, 4, 3], so the student returns 3 while the answer is max(d) = 4. The fix is "we will return max(OPT)" in the subproblem sentence and "return max(d)" in the code.Solution
(a) False. Cell (i, j) reads row i + 1, so the rows are filled from row n up to row 1. (b) True; the notes state this shortcut, which speeds up hand computation but does not change the O(mn) bound. (c) False. Computing d[i] scans all i − 1 earlier entries, so the total is O(n²).Solution
Subproblems. For all i ∈ {1, …, n}, let OPT[i] denote the largest sum of an increasing subsequence of A that must end on A[i]. We will return max(OPT).
Recurrence. Base case OPT[1] = A[1]. For i ≥ 2, OPT[i] = A[i] + max OPT[j] over all j < i with A[j] < A[i], and OPT[i] = A[i] if there is no such j. It holds because the best increasing subsequence ending on A[i] is either A[i] alone or T + A[i] where T is an increasing subsequence ending on some A[j] with j < i and A[j] < A[i]; the best such T has sum OPT[j], and every such T can be extended by A[i]. Since all values are positive, extending never hurts, and the max over the candidates is correct. The overall best subsequence ends somewhere, so the answer is max(OPT).
Algorithm.
ALG(A):
d = [0]*n
for i = 1, ..., n:
d[i] = A[i] # A[i] alone
for j = 1, ..., i-1:
if A[j] < A[i] and d[i] < A[i] + d[j]:
d[i] = A[i] + d[j]
return max(d)
Running time. Computing d[i] takes O(i) time, so the total is O(n²). On the example, d = [4, 10, 1, 4, 18, 8, 14] and the algorithm returns 18.
Pattern: LIS with "sum of values" in place of "count of elements".
Solution
Algorithm. Return n − LPS(A), calling the course's LPS algorithm by name.
ALG(A):
return n - LPS(A)
Correctness. Deleting k characters leaves a subsequence of length n − k, and it must be a palindrome, so n − k ≤ LPS(A), that is, k ≥ n − LPS(A). Conversely, deleting every character not in a longest palindromic subsequence leaves a palindrome after exactly n − LPS(A) deletions. So the minimum is n − LPS(A). For abcda, LPS = 3 (aba, aca or ada), so the answer is 5 − 3 = 2.
Running time. LPS takes O(n²) time and the subtraction O(1), so the total is O(n²).
Solution
Extra context beyond the notes: this problem is not in the course material, but it is the standard companion of Edit Distance and uses the same Pattern 6 table.
Subproblems. For all i ∈ {0, …, m} and j ∈ {0, …, n}, let OPT[i][j] denote the length of a longest common subsequence of A[1:i] and B[1:j]. We will return OPT[m][n].
Recurrence. Base cases OPT[0][j] = OPT[i][0] = 0 (nothing is common with an empty string). For i, j ≥ 1: OPT[i][j] = OPT[i−1][j−1] + 1 if A[i] = B[j], and max(OPT[i−1][j], OPT[i][j−1]) otherwise. It holds by the same exchange as in LPS: if A[i] = B[j], some longest common subsequence can be assumed to end with this matched pair (replace its last character's match by A[i] and B[j]), and the rest is common to A[1:i−1] and B[1:j−1]; if A[i] ≠ B[j], a common subsequence cannot use both A[i] and B[j] as its last character, so one of them is unused and the answer is a subproblem with that character removed.
Algorithm.
LCS(A, B):
d = [0]*((m+1) * (n+1)) # row 0 and column 0 stay 0
for i = 1, ..., m:
for j = 1, ..., n:
if A[i] = B[j]:
d[i][j] = d[i-1][j-1] + 1
else:
d[i][j] = max(d[i-1][j], d[i][j-1])
return d[m][n]
Running time. (m + 1)(n + 1) = O(mn) entries, O(1) each, so O(mn). On the example the rows a, b, c, b over columns b, a, c, b are [0, 1, 1, 1], [1, 1, 1, 2], [1, 1, 2, 2], [1, 1, 2, 3], so the answer is 3.
Course Ch. 4 · Sep 29–Oct 136. Dynamic programming II: knapsack, trees, patterns
This chapter finishes course Chapter 4. Chapter 5 built dynamic programs whose input is one array or one or two strings; here the input grows a second part. In section 4.4 of the course notes the input is a list of items and a capacity, and the subproblem shrinks both at once (0/1 Knapsack, taught on September 29). In section 4.6 the input is a rooted tree, and every vertex gets two subproblems tied together by their recurrences (Independent Set in Trees, October 8, with the matching variant on October 13). The notes then close the chapter with a list of "common DP patterns", which the lecture of October 8 wrote on the board with stars on the most important ones. That list is the most useful tool you have for Problems 3–8 of the final, where you must invent a dynamic program for a problem you have never seen, so this chapter treats it as a topic of its own and then works every problem of Problem Set 4 and every dynamic-programming design problem of Midterm 2, Practice Midterm 2 and the Practice Final with it. A dynamic program is designed by choosing the subproblem shape first, from a short list of patterns, and then splitting on what happens to the last element: it is in the solution or it is not.
A one-sentence reminder of the recipe from Chapter 5, which every solution below follows: the course notes present a dynamic program as Subproblems (which values OPT we compute and which one we return), Recurrence (the base cases and how each OPT is computed from smaller ones, with the reason it holds, which "suffices as a proof that the algorithm is correct"), Algorithm (pseudocode that fills a table d in the right order) and Running time ("typically the number of subproblems multiplied by the time per subproblem"). Chapter 1 explains how these labels earn the five points.
6.1 0/1 Knapsack: a table indexed by items and capacity
In plain words. You have a set of items, each with a value and a weight, and a bag that can carry a limited total weight; you want the most valuable load that fits, taking each item whole or not at all. Trying every set of items would take exponential time, and the greedy rule "best value per unit of weight first" that worked for Fractional Knapsack in course Chapter 3 fails once items cannot be split. The dynamic program fixes this by remembering, for every prefix of the items and every possible remaining capacity, the best value achievable. Each new item is then either skipped or packed, and both options can be read off the row above.
- Input (v, w, B): values v[1..n] and weights w[1..n], all positive integers, and a capacity B. Output: the maximum total value of a set of items whose total weight is at most B (the value, not the set).
- Subproblem (two indices): OPT[i][j] = the optimal value using only items 1, …, i with capacity j, for i ∈ [n] and j ∈ {0, 1, …, B}. Return OPT[n][B].
- The one idea: the optimal solution for (i, j) either excludes item i or includes it; if it includes it, the rest is an optimal solution for items 1, …, i − 1 with capacity j − w[i].
- Recurrence: OPT[i][j] = OPT[i−1][j] if w[i] > j; otherwise OPT[i][j] = max(OPT[i−1][j], v[i] + OPT[i−1][j − w[i]]). Base row: OPT[1][j] = v[1] if w[1] ≤ j, else 0.
- Running time: n(B + 1) entries, O(1) each, so O(nB). The bound depends on the number B, not only on n.
- Rows are items, columns are capacities 0 to B; column 0 is all zeros. "The last row of d" means row n, which has B + 1 numbers.
- Classic trap: in the "include" option, read the previous row, OPT[i−1][j − w[i]]. Reading the current row OPT[i][j − w[i]] would let item i be packed twice (that is the unbounded version, Section 6.2).
Problem
The course notes state it as follows. "The input is (v, w, B), where v and w are arrays of n positive integers each and B ∈ ℤ+. For any S ⊆ [n], S is feasible if Σi ∈ S w[i] ≤ B, and the value of S is Σi ∈ S v[i]. Our goal is to return the maximum value over all feasible solutions. Describe an O(nB)-time algorithm for this problem, prove that it's correct, and analyze its running time." The lecture's example is v = [4, 2, 3, 5], w = [3, 1, 2, 2], B = 5, and "ALG should return 10": items 2, 3 and 4 weigh 1 + 2 + 2 = 5 and are worth 2 + 3 + 5 = 10.
The notes introduce the problem as one "with multiple parts", and explain the new idea: so far every subproblem was a prefix of one array, and now "we can create a subproblem by shrinking them simultaneously", the list of items and the capacity.
Subproblems
In the notes' words: "For all i ∈ [n] and j ∈ {0, 1, …, B}, let OPT[i][j] denote the optimal value if we could only select items from [i] and the knapsack only had capacity j. We will return OPT[n][B]." The lecture wrote the same thing as "OPT[i][j] = max value w/ items 1 → i available and we have capacity j". Two indices are needed because a single prefix index is not enough information: whether item i fits depends on how much room the earlier choices left, so the room left must be part of the subproblem.
Recurrence
OPT[i][j] = OPT[i−1][j] if w[i] > j,
OPT[i][j] = max( OPT[i−1][j], v[i] + OPT[i−1][j − w[i]] ) otherwise.
The notes' reasoning: "let Sij ⊆ [i] denote the optimal solution corresponding to OPT[i][j]. Notice that Sij either contains item i or it doesn't. If w[i] > j, then Sij cannot contain i, so OPT[i][j] = OPT[i−1][j]. Otherwise, Sij either excludes i, or includes it to obtain value v[i] and fills the rest of its knapsack with value OPT[i−1][j − w[i]]."
Algorithm
The table d has n rows (items 1 to n) and B + 1 columns (capacities 0 to B), and starts filled with zeros, which already takes care of column 0. First fill row 1: item 1 alone is worth v[1] in every column where it fits. Then fill rows 2 to n, each from left to right. A cell (i, j) looks at two cells of the row above: the cell directly above it, (i − 1, j), which is the value of skipping item i, and the cell w[i] columns to the left of that, (i − 1, j − w[i]), to which v[i] is added for packing item i. If item i does not fit (j < w[i]) only the first option exists. Finally return the bottom-right cell. The course's pseudocode:
Knapsack-DP(v, w, B):
d = [0]*(n * (B+1))
for j = 1, ..., B: # base cases
if j >= w[1]:
d[1][j] = v[1]
for i = 2, ..., n:
for j = 1, ..., B:
if j < w[i]: # we must exclude item i
d[i][j] = d[i-1][j]
else: # we can exclude or include item i
d[i][j] = max(d[i-1][j], v[i] + d[i-1][j-w[i]])
return d[n][B]
Here is the full table for the lecture's example v = [4, 2, 3, 5], w = [3, 1, 2, 2], B = 5, exactly as it was drawn on September 29. The row labels show each item's value and weight.
| i (v, w) \ j | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| 1 (4, 3) | 0 | 0 | 0 | 4 | 4 | 4 |
| 2 (2, 1) | 0 | 2 | 2 | 4 | 6 | 6 |
| 3 (3, 2) | 0 | 2 | 3 | 5 | 6 | 7 |
| 4 (5, 2) | 0 | 2 | 5 | 7 | 8 | 10 |
Some cells worked out. Row 1: item 1 weighs 3, so it fits from column 3 on and the row is [0, 0, 0, 4, 4, 4]. OPT[2][1]: item 2 weighs 1 and fits, max(OPT[1][1], 2 + OPT[1][0]) = max(0, 2) = 2. OPT[2][4] = max(OPT[1][4], 2 + OPT[1][3]) = max(4, 6) = 6: items 1 and 2 together weigh exactly 4. OPT[3][2] = max(OPT[2][2], 3 + OPT[2][0]) = max(2, 3) = 3. OPT[3][5] = max(OPT[2][5], 3 + OPT[2][3]) = max(6, 7) = 7. OPT[4][2] = max(OPT[3][2], 5 + OPT[3][0]) = max(3, 5) = 5. OPT[4][5] = max(OPT[3][5], 5 + OPT[3][3]) = max(7, 5 + 5) = 10, which is the answer.
Recovering the items
The table stores values, not sets, but the set can be read back from it by walking up from the answer cell. At cell (i, j), if OPT[i][j] = OPT[i−1][j] then skipping item i is optimal: move up to (i − 1, j). Otherwise item i was packed: record it and move to (i − 1, j − w[i]). In row 1, item 1 is packed exactly when the cell is nonzero. For the lecture's table: (4, 5) holds 10 ≠ 7, so item 4 is packed and we move to (3, 3); 5 ≠ 4, so item 3 is packed, move to (2, 1); 2 ≠ 0, so item 2 is packed, move to (1, 0), which is 0. The set is {2, 3, 4}. This is the knapsack version of the parent pointers that the lecture used to recover the LIS itself (Chapter 5).
Correctness
The argument is an exhaustive case analysis on the last item, and it is the same sentence pattern you will reuse in every DP proof. Fix i ≥ 2 and j, and let Sij be an optimal solution for items [i] and capacity j. There are exactly two cases, and they cover every possibility because an item is either in a set or not.
- Item i ∉ Sij. Then Sij is a feasible set of items from [i − 1] with weight at most j, and the best such set has value OPT[i−1][j]. So in this case OPT[i][j] = OPT[i−1][j].
- Item i ∈ Sij. This is only possible if w[i] ≤ j. Removing item i leaves a set of items from [i − 1] of weight at most j − w[i], and it must be the best such set (otherwise swapping in a better one would improve Sij), so its value is OPT[i−1][j − w[i]] and the total is v[i] + OPT[i−1][j − w[i]].
- Since we do not know which case holds, take the larger of the two values when both are allowed, and the first when item i does not fit. Each option is the value of an actual feasible set, so the maximum is never too large, and the optimum falls into one of the cases, so it is never too small.
The base row is correct because with only item 1 available the best is to take it exactly when it fits. Filling row by row guarantees that row i − 1 is complete before row i reads it.
Running time
"The DP table has n(B+1) entries, and each entry takes O(1) time to compute, so the total running time is O(nB)." Note what the bound depends on: the number of items n and the numerical value of the capacity B. Extra context beyond the notes: if B is enormous, say 250, the table is enormous too, so O(nB) is not "polynomial in the length of the input"; this is called pseudo-polynomial and connects to course Chapter 7, which is not on the final. On the exam simply write O(nB).
Check-in 6.1. Run Knapsack-DP on v = [3, 5, 4, 2], w = [2, 3, 2, 1], B = 5. Fill in the table row by row, then write the returned value.
| i (v, w) \ j | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| 1 (3, 2) | ||||||
| 2 (5, 3) | ||||||
| 3 (4, 2) | ||||||
| 4 (2, 1) |
Answer
Row 1: [0, 0, 3, 3, 3, 3]. Row 2: [0, 0, 3, 5, 5, 8]. Row 3: [0, 0, 4, 5, 7, 9]. Row 4: [0, 2, 4, 6, 7, 9]. The algorithm returns 9. For instance OPT[3][5] = max(OPT[2][5], 4 + OPT[2][3]) = max(8, 9) = 9 and OPT[4][5] = max(9, 2 + OPT[3][4]) = max(9, 9) = 9.Check-in 6.2. Using your table from Check-in 6.1, walk back from cell (4, 5) and write which items an optimal solution packs, with its total weight.
Answer
(4, 5): 9 = OPT[3][5], so item 4 is skipped; (3, 5): 9 ≠ OPT[2][5] = 8, so item 3 is packed, move to (2, 3); 5 ≠ OPT[1][3] = 3, so item 2 is packed, move to (1, 0) = 0. The items are {2, 3}, weight 3 + 2 = 5, value 5 + 4 = 9.6.2 Variants: unbounded knapsack and saving space
In plain words. Two small changes to Knapsack-DP were discussed in class. In the first, the Day 2 worksheet, there is an unlimited supply of every item, and the only change is that after packing item i you may still pack item i again. In the second, from the lecture of October 13, the table is replaced by one array of length B + 1, because each row only looks at the row above it. The two changes turn out to be the same thing seen from two sides: sweeping the single array in the wrong direction solves the unbounded problem by accident.
- Unbounded Knapsack: same input, "except there is an infinite supply of every item".
- Base row becomes OPT[1][j] = k · v[1], where k = ⌊j / w[1]⌋ is the number of copies of item 1 that fit.
- Recurrence: OPT[i−1][j − w[i]] becomes OPT[i][j − w[i]]: OPT[i][j] = max(OPT[i−1][j], v[i] + OPT[i][j − w[i]]) when w[i] ≤ j. Still O(nB).
- Greedy by ratio v[i]/w[i] is wrong for the unbounded version too: v = [5, 7], w = [5, 6], B = 10.
- Space saving: row i depends only on row i − 1, so space drops from O(nB) to O(B) with two arrays of length B + 1, or one.
- With one array, sweep j from B down to 0 for 0/1 Knapsack; sweeping left to right "solves Unbounded Knapsack".
- Drawbacks of saving space, in the lecture's list: table values are harder to interpret, and the solution itself is harder to reconstruct (no parent pointers).
Problem
Day 2 worksheet, Problem 2: "Consider the 'Unbounded Knapsack' problem: it's the same as 0/1 Knapsack, except there is an infinite supply of every item. How should the recurrence change?" Instance from the official solution: v = [5, 7], w = [5, 6], B = 10. The answer is 10, two copies of item 1.
Subproblems
Unchanged: OPT[i][j] is the optimal value using items from [i] with capacity j, now with unlimited copies of each item; we return OPT[n][B].
Recurrence
Base row OPT[1][j] = ⌊j / w[1]⌋ · v[1]; for i ≥ 2, OPT[i][j] = OPT[i−1][j] if w[i] > j, and max(OPT[i−1][j], v[i] + OPT[i][j − w[i]]) otherwise.
Algorithm
The official solution changes two lines. "The base case for row 1 becomes OPT[1][j] = k · v[1], where k is the maximum number of copies of item 1 we can take, i.e., k = ⌊j / w[1]⌋." And "in the main recurrence, OPT[i−1][j − w[i]] becomes OPT[i][j − w[i]] because we are no longer forced to pick the remaining solution from items {1, …, i−1}; if we want, we can continue picking additional copies of item i." Since OPT[i][j − w[i]] lies to the left in the same row, filling each row from left to right still computes everything before it is needed.
Unbounded-Knapsack(v, w, B):
d = [0]*(n * (B+1))
for j = 1, ..., B:
d[1][j] = floor(j / w[1]) * v[1] # as many copies of item 1 as fit
for i = 2, ..., n:
for j = 1, ..., B:
d[i][j] = d[i-1][j]
if j >= w[i]:
d[i][j] = max(d[i][j], v[i] + d[i][j-w[i]]) # same row: item i again
return d[n][B]
| i (v, w) \ j | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 (5, 5) | 0 | 0 | 0 | 0 | 0 | 5 | 5 | 5 | 5 | 5 | 10 |
| 2 (7, 6) | 0 | 0 | 0 | 0 | 0 | 5 | 7 | 7 | 7 | 7 | 10 |
Some cells worked out. OPT[1][10] = ⌊10/5⌋ · 5 = 10. OPT[2][6] = max(OPT[1][6], 7 + OPT[2][0]) = max(5, 7) = 7. OPT[2][10] = max(OPT[1][10], 7 + OPT[2][4]) = max(10, 7) = 10. The greedy rule takes item 2 first (ratio 7/6 > 5/5 = 1), after which only 4 units of room remain and nothing else fits, so greedy gets 7. That is the official counterexample.
Correctness
The case split is the same as in Section 6.1: the optimal solution for (i, j) either uses no copy of item i, value OPT[i−1][j], or uses at least one copy. In the second case remove one copy: what remains is a feasible solution with capacity j − w[i] that may still contain item i, so its best value is OPT[i][j − w[i]], not OPT[i−1][j − w[i]]. The base row is correct because with only item 1, taking as many copies as fit is optimal.
Running time
Unchanged: n(B + 1) entries at O(1) each, O(nB).
Saving space (October 13)
The lecture's observation is that in Knapsack-DP "d[i][j] depends on d[i−1][j] and d[i−1][j − w[i]]", that is, "each row only depends on [the] previous row". So "we can reduce space from O(nB) to O(B)": keep two arrays of length B + 1 (the previous row and the current row), or even a single array d[0..B] that is overwritten in place. With one array, the update for item i is d[j] = max(d[j], v[i] + d[j − w[i]]), and the order matters. The right-hand side must use the old d[j − w[i]], the value from row i − 1. Sweeping j from B down to w[i], the cell d[j − w[i]] lies to the left and has not been overwritten yet, so this is correct for 0/1 Knapsack. Sweeping left to right, d[j − w[i]] has already been updated in this pass and may already include item i, so item i can be counted again: the lecture drew a red cross on this direction and wrote that it "solves Unbounded Knapsack". The same trick saves space in any DP whose entries depend only on a fixed number of earlier entries (Max-in-Array keeps one number), but not in LIS, where d[i] depends on all of d[1 : i−1].
Check-in 6.3. Run Unbounded-Knapsack on v = [3, 4, 5], w = [2, 3, 4], B = 7. Fill in all three rows and write the answer.
| i (v, w) \ j | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| 1 (3, 2) | ||||||||
| 2 (4, 3) | ||||||||
| 3 (5, 4) |
Answer
Row 1 (⌊j/2⌋ · 3): [0, 0, 3, 3, 6, 6, 9, 9]. Row 2: [0, 0, 3, 4, 6, 7, 9, 10]. Row 3: [0, 0, 3, 4, 6, 7, 9, 10]. The answer is 10: two copies of item 1 and one of item 2 (weight 2 + 2 + 3 = 7, value 3 + 3 + 4). For example OPT[2][7] = max(OPT[1][7], 4 + OPT[2][4]) = max(9, 10) = 10.6.3 Independent set in trees: two subproblems per vertex
In plain words. A tree is a connected graph without cycles; here it hangs down from a root, and every vertex carries a weight. An independent set is a choice of vertices no two of which are joined by an edge, and the goal is the heaviest such choice. The dynamic program works from the leaves up: for every vertex it computes the best choice inside the part of the tree below it, once with the vertex taken and once with it left out. Those two numbers are exactly what the parent needs, because a parent that is taken forbids its children and a parent that is left out does not care.
- Input (T, w): a tree rooted at vertex 1 given as lists of children T[u], and weights w[u] > 0. Output: the weight of a maximum independent set (MIS), a set S with no edge inside it maximizing Σu ∈ S w(u).
- Subproblems: for every vertex u, OPTin[u] = weight of the MIS in Tu (the subtree rooted at u) that includes u, and OPTout[u] = the same but excluding u. Return max(OPTin[1], OPTout[1]).
- Recurrences: OPTin[u] = w(u) + Σv ∈ T[u] OPTout[v] and OPTout[u] = Σv ∈ T[u] max(OPTin[v], OPTout[v]). Leaf: (w(u), 0).
- Why it works: the subtrees of different children share no edge, so their choices are independent and their weights add.
- Order: children before parents, "sort V in reverse topological order".
- Running time O(n): the work at u is O(|T[u]|), and Σu |T[u]| = n − 1.
- Classic trap: the single subproblem "weight of the MIS in Tu" does not say whether u is used, so the parent cannot be combined with it (unless you look two levels down, Section 6.4).
Problem
The notes define the terms first: "For any undirected graph G, a subset S of vertices is an independent set if no edge in G has both endpoints in S. If each vertex u has weight w(u), the weight of S is Σu ∈ S w(u). (If weights are not given, we assume every vertex has weight 1.) A maximum independent set (MIS) is an independent set whose weight is as large as possible." Then the problem: "The input is (T, w), where T = (V, E) is a tree rooted at vertex 1. For all u ∈ V, T[u] is a list of u's children, and w[u] is the weight of u. Our goal is to return the weight of a maximum independent set in T. Describe an O(n)-time algorithm for this problem, prove that it's correct, and analyze its running time."
The lecture of October 8 opened with the small tree below (vertex numbers inside the circles, weights beside them). Taking the root, worth 3, forbids its three children and allows only the two leaves, 3 + 4 + 1 = 8. Leaving the root out allows vertex 4 (weight 5), vertex 5 (weight 4, which forbids its parent 2) and vertex 3 (weight 2, which forbids the leaf 6): 5 + 4 + 2 = 11, the maximum.
Subproblems
The lecture first wrote "OPT[u] = weight of MIS in subtree rooted at u" and crossed it out with a red X. The reason: to decide whether u can join the set, we must know whether each child is in the set below it, and a single number does not record that. So the notes define two subproblems per subtree: "For all u ∈ V, let Tu denote the subtree of T rooted at u. We define two subproblems per Tu: let OPTin[u] denote the weight of the MIS in Tu that includes u, and let OPTout[u] denote the weight of the MIS in Tu that excludes u. Since the original tree is T1 and the MIS in T1 either includes or excludes vertex 1, we will return max(OPTin[1], OPTout[1])."
The notes add a remark worth remembering for Problems 3–8: OPTin[u] is like OPT[i] for LIS, because both require the subproblem's own index to be in the solution, whereas the knapsack's OPT[i][j] does not require item i; "however, the logic below is similar to the logic behind 0/1 Knapsack", namely the split into "in" and "out".
Recurrence
OPTin[u] = w(u) + Σv ∈ T[u] OPTout[v],
OPTout[u] = Σv ∈ T[u] max(OPTin[v], OPTout[v]).
Return max(OPTin[1], OPTout[1]).Algorithm
Two arrays din and dout are filled according to the recurrences. When vertex u is processed, the values of all its children must already be known, so "if we visualize the root as the top of the tree, we need to work our way up the tree". The notes' way to get such an order: pretend each edge (u, v) with v ∈ T[u] is directed from parent to child, and process V in reverse topological order (course Chapter 2; Chapter 3 of this guide). A topological order lists every parent before its children, so its reverse lists every child before its parent. Then at u, start din[u] at w[u] and dout[u] at 0, and for each child v add dout[v] to the first and max(din[v], dout[v]) to the second. For a leaf the loop over children is empty, which produces the base case automatically. The course's pseudocode:
MIS-Tree(T, w):
d_in, d_out = [0]*n, [0]*n
sort V in reverse topological order
for u in V:
d_in[u] = w[u]
for v in T[u]:
d_in[u] += d_out[v]
d_out[u] += max(d_in[v], d_out[v])
return max(d_in[1], d_out[1])
The lecture's larger example is the 13-vertex tree below (weights beside the vertices); the board showed the pair "in, out" next to every vertex.
| Vertex u | w(u) | Children T[u] | OPTin[u] | OPTout[u] |
|---|---|---|---|---|
| 5, 7, 8, 9, 11, 12, 13 (leaves) | 1, 3, 2, 3, 2, 1, 2 | none | w(u) | 0 |
| 6 | 2 | 7, 8 | 2 + 0 + 0 = 2 | max(3, 0) + max(2, 0) = 5 |
| 10 | 5 | 11 | 5 + 0 = 5 | max(2, 0) = 2 |
| 2 | 5 | 5, 6 | 5 + 0 + 5 = 10 | max(1, 0) + max(2, 5) = 6 |
| 3 | 3 | 9, 10 | 3 + 0 + 2 = 5 | max(3, 0) + max(5, 2) = 8 |
| 4 | 3 | 12, 13 | 3 + 0 + 0 = 3 | max(1, 0) + max(2, 0) = 3 |
| 1 (root) | 2 | 2, 3, 4 | 2 + 6 + 8 + 3 = 19 | max(10, 6) + max(5, 8) + max(3, 3) = 21 |
Some cells worked out. Vertex 6 has two leaf children worth 3 and 2; taking 6 (weight 2) forbids both, so OPTin[6] = 2, while leaving it out lets both leaves in, OPTout[6] = 5. Vertex 2: taking it (5) forces 5 and 6 out, and OPTout[6] = 5 is the best below 6 without 6, so OPTin[2] = 5 + 0 + 5 = 10. At the root, OPTout[1] picks the better of in and out at each child: 10 at vertex 2, 8 at vertex 3, 3 at vertex 4, total 21. The answer is max(19, 21) = 21, matching the green 21 on the board.
To find the set, walk down from the root making the choices that achieved the maximum: 1 is out; at 2, in (10) beats out (6), so 2 is in, which forces 5 and 6 out and frees 7 and 8, which are taken; at 3, out (8) beats in (5), so 3 is out, 9 is in, and at 10 in (5) beats out (2), so 10 is in and 11 is out; at 4 there is a tie (3, 3). Choosing "out" takes 12 and 13, giving the set {2, 7, 8, 9, 10, 12, 13}, which weighs 5 + 3 + 2 + 3 + 5 + 1 + 2 = 21 and is drawn below. Choosing "in" takes vertex 4 instead (weight 3), which the lecture's drawing highlighted; it is equally optimal.
Correctness
The proof is the exhaustive two-case argument of the notes, applied once to each recurrence, plus one structural fact about trees. The fact: if v1 and v2 are different children of u, no edge joins a vertex of Tv1 to a vertex of Tv2 (such an edge would close a cycle through u). So an independent set of Tu is exactly a choice of an independent set inside each child's subtree, plus possibly u, subject only to the edges from u to its children.
- OPTin[u]. "The solution S corresponding to OPTin[u] includes u, so for each v ∈ T[u], S contains an MIS in Tv that excludes v." Each child must be out because of the edge (u, v), and within Tv the best set without v weighs OPTout[v]; the subtrees are independent, so the weights add, plus w(u).
- OPTout[u]. "The solution S′ corresponding to OPTout[u] excludes u, which means for each v ∈ T[u], S′ could include or exclude v." Nothing constrains the children, so each subtree contributes its best with or without v, max(OPTin[v], OPTout[v]).
- Leaves and the answer. If u is a leaf, Tu is just u, so the values are w(u) and 0. The MIS of the whole tree T1 either contains vertex 1 or not, so the answer is the larger of the two values at the root.
Running time
From the notes: "Computing a topological order takes O(m + n) time. For each vertex u, computing din[u] and dout[u] takes O(|T[u]|) time. Since Σu |T[u]| = m = n − 1 (where the second equality holds because T is a tree), the total running time is O(m + n) + O(m + n) = O(n)." The lecture summarized it as "RT: O(n) (≈ BFS)". The important step is the sum: a loop over children inside a loop over vertices looks like O(n²), but every vertex except the root is somebody's child exactly once, so the inner loops run n − 1 times in total.
Check-in 6.4. For the tree below, fill in OPTin and OPTout for every vertex, leaves first, then write the weight of a maximum independent set and one set that achieves it.
| u | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 |
|---|---|---|---|---|---|---|---|---|
| OPTin[u] | ||||||||
| OPTout[u] |
Answer
Leaves 8, 7, 6, 4: (3, 0), (1, 0), (4, 0), (2, 0). Vertex 5: (5 + 0, 3) = (5, 3). Vertex 3: (3 + 0 + 0, 4 + 1) = (3, 5). Vertex 2: (4 + 0 + 3, 2 + 5) = (7, 7). Root: OPTin[1] = 6 + 7 + 5 = 18, OPTout[1] = max(7, 7) + max(3, 5) = 12. The answer is 18, for example {1, 4, 5, 6, 7} (6 + 2 + 5 + 4 + 1).6.4 One array instead of two: looking at grandchildren
In plain words. The crossed-out subproblem from Section 6.3, a single number per vertex, can be rescued. If the vertex is taken, its children are forbidden, but its grandchildren are free, so the recurrence can skip a level and read the grandchildren's values. This was the last page of the lecture of October 8 and Problem 3 of the Day 4 worksheet. It gives the same answers with one array.
- Subproblem: OPT[u] = weight of the MIS in Tu (no requirement about u). Return OPT[1].
- Recurrence: OPT[u] = max( Σv ∈ T[u] OPT[v], w[u] + Σv ∈ T[u] Σx ∈ T[v] OPT[x] ). Leaf: OPT[u] = w[u].
- First option: u is out, every child's subtree is free. Second option: u is in, every child is out, every grandchild's subtree is free.
- Running time O(n), "≈ 2 · O(n)": every vertex is read once as a child and once as a grandchild.
- Same children-before-parents order as MIS-Tree.
Problem
Day 4 worksheet, Problem 3: "What is a DP recurrence for MIS in trees where OPT[u] is the weight of the MIS in the subtree rooted at vertex u?" The official answer: "OPT[u] is the maximum of Σv ∈ T[u] OPT[v] and w[u] + Σv ∈ T[u] Σw ∈ T[v] OPT[w]." (The notes reuse the letter w for a grandchild; this guide writes x to avoid a clash with the weights.)
Subproblems
For all u ∈ V, let OPT[u] denote the weight of the MIS in Tu, with no requirement about u itself. We return OPT[1].
Recurrence
If u is a leaf, OPT[u] = w[u]. Otherwise OPT[u] = max( Σv ∈ T[u] OPT[v], w[u] + Σv ∈ T[u] Σx ∈ T[v] OPT[x] ), where the first term leaves u out and the second takes u and skips its children.
Algorithm
Process the vertices children first. At u, compute A = the sum of OPT over the children and C = w[u] plus the sum of OPT over the grandchildren, by a double loop "for v in T[u]: for x in T[v]", and set OPT[u] = max(A, C). On the lecture's 13-vertex tree this gives OPT = 1, 3, 2, 3, 2, 1, 2 at the leaves, OPT[6] = max(5, 2) = 5, OPT[10] = max(2, 5) = 5, OPT[2] = max(1 + 5, 5 + 3 + 2) = 10, OPT[3] = max(3 + 5, 3 + 2) = 8, OPT[4] = max(3, 3) = 3 and OPT[1] = max(10 + 8 + 3, 2 + (1 + 5) + (3 + 5) + (1 + 2)) = max(21, 19) = 21, the same answer as before. Notice that OPT[u] = max(OPTin[u], OPTout[u]) at every vertex, as it must.
MIS-Tree-1(T, w):
d = [0]*n
sort V in reverse topological order
for u in V:
skip_u, take_u = 0, w[u]
for v in T[u]:
skip_u += d[v] # u out: children free
for x in T[v]:
take_u += d[x] # u in: grandchildren free
d[u] = max(skip_u, take_u)
return d[1]
Correctness
Exhaustive cases on u. If the MIS of Tu excludes u, it is the union of an MIS of each child's subtree (they share no edges), worth Σ OPT[v]. If it includes u, every child is excluded, and what remains is the union of an MIS of each grandchild's subtree, worth w[u] + Σ Σ OPT[x]; the grandchildren are not adjacent to u, so nothing else is forbidden.
Running time
The lecture's count: "for u in V: for v in T[u]: for w in T[v]" is "O(n) (≈ 2 · O(n))", because each vertex appears once as a child (of its parent) and once as a grandchild (of its grandparent). Plus O(n) for the order.
Check-in 6.5. Using the single-array recurrence on the tree of Check-in 6.4, compute OPT[5], OPT[3], OPT[2] and OPT[1], and write one valid processing order for its eight vertices.
Answer
Leaves: OPT = w. OPT[5] = max(3, 5) = 5. OPT[3] = max(4 + 1, 3) = 5. OPT[2] = max(2 + 5, 4 + 3) = 7 (the grandchild of 2 is 8). OPT[1] = max(7 + 5, 6 + (2 + 5) + (4 + 1)) = max(12, 18) = 18. A valid order: 8, 7, 6, 5, 4, 3, 2, 1, the reverse of the BFS order 1, 2, 3, 4, 5, 6, 7, 8; any order with every child before its parent works.6.5 Maximum matching in a tree
In plain words. Now the weights sit on the edges, and we want the heaviest set of edges no two of which touch the same vertex (a matching). At every vertex the only question is whether it is matched to one of its children, and if so to which one. The dynamic program keeps two numbers per vertex: the best matching below it, and the best matching below it that leaves the vertex itself free. This was taught on October 13 with the instruction "on your own" for part of it and finished on the Day 5 worksheet.
- Input: a tree rooted at 1, each edge e with weight w(e) > 0. Output: the weight of a maximum matching, a set F ⊆ E with no two edges sharing an endpoint maximizing Σe ∈ F w(e).
- Subproblems: OPT[u] = weight of the max matching in T(u); OPTout[u] = the same "but we cannot match u". Both are 0 at a leaf. Return OPT[1].
- Recurrences: OPTout[u] = Σv ∈ T[u] OPT[v]; OPT[u] = max( OPTout[u], maxv ∈ T[u] [ w(u, v) + OPTout[v] + Σx ∈ T[u], x ≠ v OPT[x] ] ).
- Speed-up: Σx ≠ v OPT[x] = OPTout[u] − OPT[v], which turns O(n²) into O(n).
- Children before parents, as in MIS-Tree.
Problem
The lecture's statement: "Input: tree T rooted at 1, each edge e has weight w(e) > 0. Goal: return weight of a max matching", where a matching is a "subset F of E s.t. no 2 edges in F share an endpoint". The lecture's example tree is below (edge weights on the edges). The red edges on the board were the root's right edge (weight 3), the edge from 2 to 5 (weight 4) and the edge from 8 to 9 (weight 2): total 9.
Subproblems
From the Day 5 worksheet, Problem 3: "Let OPT[u] denote the weight of the maximum matching in T(u) (the subtree rooted at u), and let OPTout[u] be the same but we cannot match u." Here "cannot match u" means no chosen edge touches u. Inside T(u) the only edges at u go to its children, so this means u is not matched to any child. We return OPT[1].
Recurrence
From the official solution: "If u is a leaf, both weights are 0. If we cannot match u, then the optimal solution is simply the union of OPT[v] over every child v ∈ T[u], so OPTout[u] is the sum of OPT[v] over every child." If u may be matched, either it is not (value OPTout[u]) or it is matched to exactly one child v, and then the total is "the weight w(u, v) of that edge, the rest of the weight from T(v), and the rest of the weight from the other children of u. Since v cannot be matched but the others can", the total is W(u, v) = w(u, v) + OPTout[v] + Σx ∈ T[u], x ≠ v OPT[x]. "So the overall value of OPT[u] is the maximum of (1) OPTout[u], and (2) the maximum value of W(u, v) over all v ∈ T[u]."
OPTout[u] = Σv ∈ T[u] OPT[v],
OPT[u] = max( OPTout[u], maxv ∈ T[u] [ w(u, v) + OPTout[v] + OPTout[u] − OPT[v] ] ).
Algorithm
Process the vertices children first. At u, first compute OPTout[u] by summing OPT over the children. Then, for each child v, evaluate the candidate "match u to v": the edge weight, plus the best inside T(v) with v free, plus the best in all other children's subtrees, which is OPTout[u] − OPT[v]. Keep the maximum of OPTout[u] and all candidates. The full trace on the lecture's tree:
Tree-Matching(T, w):
d, d_out = [0]*n, [0]*n
sort V in reverse topological order
for u in V:
for v in T[u]:
d_out[u] += d[v]
d[u] = d_out[u]
for v in T[u]: # try matching u to child v
d[u] = max(d[u], w(u,v) + d_out[v] + d_out[u] - d[v])
return d[1]
| Vertex u | Children (edge weight) | OPTout[u] | OPT[u] |
|---|---|---|---|
| 4, 6, 7, 9 | none | 0 | 0 |
| 5 | 6 (2), 7 (2) | 0 + 0 = 0 | max(0, 2 + 0 + 0 − 0, 2 + 0 + 0 − 0) = 2 |
| 8 | 9 (2) | 0 | max(0, 2 + 0 + 0 − 0) = 2 |
| 2 | 4 (1), 5 (4) | 0 + 2 = 2 | max(2, 1 + 0 + 2 − 0, 4 + 0 + 2 − 2) = 4 |
| 3 | 8 (1) | 2 | max(2, 1 + 0 + 2 − 2) = 2 |
| 1 | 2 (1), 3 (3) | 4 + 2 = 6 | max(6, 1 + 2 + 6 − 4, 3 + 2 + 6 − 2) = 9 |
Some cells worked out. At vertex 2, matching 2 to 5 is worth 4 (the edge) + OPTout[5] = 0 (5 is now used, so its own edges are lost) + OPTout[2] − OPT[5] = 2 − 2 = 0 (the other child, the leaf 4, contributes nothing) = 4, which beats leaving 2 free (2) and matching 2 to 4 (3). At the root, matching 1 to 3 gives 3 + OPTout[3] (= 2, the edge 8–9) + (6 − 2) (= OPT[2] = 4, the edge 2–5) = 9.
Correctness
Exhaustive cases on how u is matched inside T(u): to no child, or to exactly one child v (two chosen edges at u would share u). If to none, each child's subtree is free and the subtrees are disjoint, so the total is Σ OPT[v] = OPTout[u]. If to v, the edge (u, v) is chosen, so no other chosen edge may touch v (OPTout[v] inside T(v)) or u (so the edges from u to the other children are not chosen, but everything inside their subtrees is free, OPT[x]). Trying every v and taking the best, together with the "no child" case, covers all possibilities. The identity Σx ≠ v OPT[x] = OPTout[u] − OPT[v] holds because OPTout[u] is the sum over all children.
Running time
Evaluated literally, each candidate v costs O(|T[u]|) for the sum over the other children, so a vertex with k children costs O(k²); the lecture wrote "⇒ O(n²)" next to it (think of a star). The official note: "implementing this naively would result in a running time of O(n²), but we can reduce this to O(n) by replacing Σx ≠ v OPT[x] with OPTout[u] − OPT[v]." With the subtraction, vertex u costs O(|T[u]|), and Σu |T[u]| = n − 1, so the total is O(n).
Check-in 6.6. For the edge-weighted tree below, fill in OPTout and OPT for every vertex, children first, and write the weight of a maximum matching and its edges.
| u | 4 | 5 | 6 | 2 | 3 | 1 |
|---|---|---|---|---|---|---|
| OPTout[u] | ||||||
| OPT[u] |
Answer
Leaves 4, 5, 6: (0, 0). Vertex 2: OPTout = 0, OPT = max(0, 5, 2) = 5. Vertex 3: OPTout = 0, OPT = 6. Root: OPTout[1] = 5 + 6 = 11; matching 1 to 2 gives 3 + 0 + 11 − 5 = 9; matching 1 to 3 gives 4 + 0 + 11 − 6 = 9; so OPT[1] = 11, the edges 2–4 and 3–6, with the root unmatched.6.6 Which DP pattern is this?
In plain words. Most of the work in designing a dynamic program is choosing the subproblem, and the course offers a short menu for that choice. The menu is organized by the shape of the input: one array, an array with a number, two arrays, or a tree. For each shape there are one or two standard subproblems, each attached to an algorithm from the course that you already know. On the exam you look at the input, pick the matching entry, and then write the recurrence by asking what happens to the last element.
- The notes end course Chapter 4 with "a list of common DP patterns", organized by the input; the lecture of October 8 wrote the array ones on the board as patterns 1–6 and starred 1, 3 and 6.
- Default for one array: prefixes A[1 : i] (Pattern 1). If the prefix answer cannot be extended without knowing how the solution ends, require A[i] to be involved (Pattern 3, the "LIS trick") and return the max or min over all i.
- Games and "skip ahead" rules that look to the right use suffixes A[i : n] (Pattern 2), filled from i = n down to 1, returning OPT[1].
- Solutions built from both ends use intervals A[i : j] (Pattern 4); a budget or capacity adds a second index (Pattern 5); two sequences use a pair of prefixes (Pattern 6).
- Trees: OPT[u] for the subtree Tu (Pattern 7), or a version that involves u, such as OPTin/OPTout (Pattern 8), children before parents.
- Running time = number of subproblems × time per subproblem; pick the pattern whose table size matches the target bound (O(n): one index; O(n²), O(mn), O(nB): two).
Problem
The Day 4 worksheet, Problem 1, asked: "For each of the following DP patterns, name a problem that can be solved using that pattern: (a) OPT[i] = OPT given A[1 : i]; (b) OPT[i] = OPT given A[1 : i] that somehow involves A[i]; (c) OPT[i][j] = OPT given (A[1 : i], B[1 : j])." The official answer: "(A) Max in array, (B) Longest Increasing Subsequence (LIS), (C) Edit Distance." On the final the question is the reverse: here is a new problem, which pattern does it follow?
Here is the complete list from the notes, with the lecture's numbering for the array patterns, and with every course example this guide works.
| # | Input | Subproblem (notes' wording) | Course examples | Fill order, return |
|---|---|---|---|---|
| 1 ★ | A, an array of length n | ∀ i ∈ [n]: OPT[i] = OPT given A[1 : i] | Max-in-Array, Sum (PS 4.1), no two adjacent (PS 4.6), Fibonacci | i = 1 … n · OPT[n] |
| 2 | A | ∀ i ∈ [n]: OPT[i] = OPT given A[i : n] | Alice-and-Bob game (Day 5 worksheet), skip the next B[i] (Practice Final 7) | i = n … 1 · OPT[1] |
| 3 ★ | A | ∀ i ∈ [n]: OPT[i] = OPT given A[1 : i] that somehow involves A[i] | LIS, contiguous LIS (PS 4.2), jumps (PS 4.3), stock (PS 4.5) | i = 1 … n · max or min over i |
| 4 | A | ∀ i ∈ [n] ∀ j ∈ [i, n]: OPT[i][j] = OPT given A[i : j] | LPS | bottom row up · OPT[1][n] |
| 5 | (A, k), k ≥ 0 an integer | ∀ i ∈ [n] ∀ j ∈ {0, …, k}: OPT[i][j] = OPT given (A[1 : i], j) | 0/1 Knapsack, Unbounded Knapsack | row by row · OPT[n][k] |
| 6 ★ | (A, B), lengths m and n | ∀ i ∈ [m] ∀ j ∈ [n]: OPT[i][j] = OPT given (A[1 : i], B[1 : j]) | Edit Distance, shuffle (Practice Midterm 2, Problem 4), grid paths (PS 4.4) | row by row · OPT[m][n] |
| 7 | T, a rooted tree with vertex set V | ∀ u ∈ V: OPT[u] = OPT given Tu | MIS with grandchildren (Section 6.4), OPT[u] in tree matching | children first · OPT[root] |
| 8 | T | ∀ u ∈ V: OPT[u] = OPT given Tu that somehow involves u | OPTin, OPTout for MIS; OPTout in tree matching | children first · combine at the root |
Two more shapes appear in the problem sets and exams, and both fit the list once you see the "array" correctly. When the input is a target number (PS 4.7, Midterm 2 Problem 4), index by every smaller target, OPT[i] for i = 0, …, n: this is Pattern 1 on the sequence of targets, starting at index 0. When the input is a graph, the shortest-path dynamic programs of course Chapter 5 add their own patterns (Chapter 7).
Algorithm
To design a dynamic program for Problems 3–8, run these steps in order. They are the course's recipe with the pattern choice made explicit.
- Look at the input shape and pick the default pattern from the table: one array → Pattern 1; an array plus a budget → Pattern 5; two strings → Pattern 6; a tree → Pattern 8 with in/out.
- Try the "last element" split. For OPT given A[1 : i], ask: is A[i] in the solution or not? If both answers lead to smaller subproblems of the same kind, you are done (PS 4.6, Knapsack). If you cannot tell whether A[i] may be added without knowing where the previous solution ended, switch to Pattern 3 and return max(OPT) (LIS, PS 4.2). If the rule refers to elements to the right of i (skip the next B[i], remove from the left end), switch to Pattern 2.
- Write the subproblem sentence in the notes' words: "For all i ∈ …, let OPT[i] denote … given …; we will return …". The grader reads this sentence first.
- Write the base cases and the recurrence, one case per option, and the sentence "the recurrence holds because the optimal solution either … or …" (exhaustive cases).
- Write the pseudocode with the fill order that makes every needed value available (left to right, right to left, bottom row up, children first).
- Count: number of subproblems × time per subproblem. If it misses the target, precompute something (suffix sums, a running minimum) or use an identity, as the stock problem and the matching problem did.
The course's example for Pattern 2, the Day 5 worksheet's game, shows steps 2 and 6 in action. "The input is an array A of n positive integers, where n ≥ 3. Alice and Bob take turns (starting with Alice) removing 1, 2, or 3 elements from the beginning of the remaining array. Each player is optimally maximizing the sum of elements they remove. Describe an O(n)-time algorithm that returns the maximum sum that Alice can remove." The game is always played on a suffix, so the official solution sets "OPT[i] denote the maximum sum a player can remove given A[i : n], so we'll return OPT[1]". The base cases are i ∈ {n − 2, n − 1, n}, where the player takes everything, OPT[i] = S[i] with S[i] the sum of A[i : n]. If the player removes k elements, the opponent then scores OPT[i + k] out of the S[i + k] that remain, and the player gets the rest, so OPT[i] is the maximum of A[i] + S[i+1] − OPT[i+1], A[i] + A[i+1] + S[i+2] − OPT[i+2] and A[i] + A[i+1] + A[i+2] + S[i+3] − OPT[i+3]. Computing each S from scratch would be O(n²) ("Naively: O(n²)" on the board), "but we can get O(n) by precomputing S in O(n)". Because every option equals S[i] − OPT[i + k], the recurrence simplifies to OPT[i] = S[i] − min(OPT[i+1], OPT[i+2], OPT[i+3]).
ALG(A):
S = [A[n]]*n
for i = n-1, ..., 1:
S[i] = S[i+1] + A[i]
d = [A[n]]*n
d[n-1] = A[n-1] + A[n]
d[n-2] = A[n-2] + A[n-1] + A[n]
for i = n-3, ..., 1:
d[i] = S[i] - min(d[i+1], d[i+2], d[i+3])
return d[1]
On the lecture's array A = [4, 1, 5, 2, 3, 10, 1, 2], filled from the right:
| i | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| A[i] | 4 | 1 | 5 | 2 | 3 | 10 | 1 | 2 |
| S[i] | 28 | 24 | 23 | 18 | 16 | 13 | 3 | 2 |
| OPT[i] | 18 | 14 | 10 | 15 | 14 | 13 | 3 | 2 |
Some cells worked out. OPT[6], OPT[7], OPT[8] are base cases (13, 3, 2). OPT[5] = 16 − min(13, 3, 2) = 14: take 3, 10, 1 and leave the opponent only the 2. OPT[4] = 18 − min(14, 13, 3) = 15. OPT[1] = 28 − min(OPT[2], OPT[3], OPT[4]) = 28 − min(14, 10, 15) = 18: Alice takes 4 and 1, leaving Bob a position worth only 10 of the remaining 23.
Correctness
Choosing a pattern is not itself something to prove; what you prove is the recurrence, and the notes say that the reason the recurrence holds "suffices as a proof that the algorithm is correct". The proof is always the same shape: name the optimal solution for the subproblem, list the possibilities for its last element (in or out; ends here or extends an earlier one; which child is matched; how many elements the player removes), show they are exhaustive, and show that each possibility is scored by the corresponding term.
Running time
The table size is fixed by the pattern: Patterns 1, 2, 3, 7 and 8 have n entries, Pattern 4 about n²/2, Pattern 5 n(k + 1), Pattern 6 mn. Multiply by the time per entry: O(1) for most recurrences, O(n) when OPT[i] looks at every earlier entry (LIS, O(n²) in total), O(|T[u]|) on trees (O(n) in total). If the target bound is O(n) and the input is one array, you need Pattern 1, 2 or 3 with O(1) per entry.
Check-in 6.7. Name the pattern (1 to 8) you would use, and what you would return: (a) the longest run of equal adjacent elements of A; (b) the maximum value of at most k items chosen from A with no two adjacent; (c) the best score in a game where players remove 1 or 2 elements from the left end; (d) the length of the longest common subsequence of two strings; (e) the minimum weight of a vertex cover of a tree.
Answer
(a) Pattern 3 (run that ends at A[i]), return max(OPT). (b) Pattern 5 with the count of items as the budget, OPT[i][j] for A[1 : i] with at most j items, return OPT[n][k]. (c) Pattern 2 (suffixes), return OPT[1]. (d) Pattern 6, return OPT[m][n]. (e) Pattern 8 (in/out per vertex), return min(OPTin[1], OPTout[1]).Check-in 6.8. Run the Alice-and-Bob algorithm on A = [3, 9, 1, 2, 8, 4]: fill in S and OPT from right to left, then write Alice's maximum sum.
| i | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| A[i] | 3 | 9 | 1 | 2 | 8 | 4 |
| S[i] | ||||||
| OPT[i] |
Answer
S = [27, 24, 15, 14, 12, 4]. OPT[4..6] = 14, 12, 4 (base cases); OPT[3] = 15 − min(14, 12, 4) = 11; OPT[2] = 24 − min(11, 14, 12) = 13; OPT[1] = 27 − min(13, 11, 14) = 16. So OPT = [16, 13, 11, 14, 12, 4] and Alice gets 16 (she takes 3 and 9, and Bob can get only 11 of the remaining 15).6.7 Worked problems from Problem Set 4
Problem Set 4 is the course's dynamic-programming problem set, and its problems have already reappeared word for word: Problem 4.5 was Midterm 2 Problem 2 and Practice Final Problem 3, and Problem 4.2 was Practice Midterm 2 Problem 2. The cover page of the final promises that at least two of Problems 3–8 are identical to problem-set problems, so learn these seven solutions as model answers. Each statement below is copied from the course page; each solution is the official one, laid out with the recipe's labels and expanded where a beginner needs it. Try each on paper before opening it.
PS 4.1. Sum of an array
Solution
PS 4.1. Sum of an array.
Subproblems. For all i ∈ {1, …, n}, let OPT[i] denote the sum of A[1 : i]; we will return OPT[n].
Recurrence. The base case is OPT[1] = A[1], and for i ≥ 2, OPT[i] = OPT[i−1] + A[i].
Correctness. The recurrence holds because the sum of A[1 : i] is equal to the sum of A[1 : i−1] plus A[i]; the base case is the sum of a one-element prefix.
Algorithm.
ALG(A):
d = [A[1]]*n
for i = 2, ..., n:
d[i] = d[i-1] + A[i]
return d[n]
Running time. The algorithm makes n − 1 iterations and each takes O(1) time, so the total running time is O(n).
Pattern: 1 (prefixes), the warm-up of the Day 1 worksheet.
PS 4.2. Longest increasing contiguous subsequence
Solution
PS 4.2. Longest increasing contiguous subsequence.
LeetCode 674; also Practice Midterm 2, Problem 2.
Subproblems. For all i ∈ {1, …, n}, let OPT[i] denote the length of the longest contiguous increasing subsequence in A[1 : i] that must end on A[i]; we will return max(OPT).
Recurrence. The base case is OPT[1] = 1. For i ≥ 2,
OPT[i] = 1 + OPT[i−1] if A[i] > A[i−1], OPT[i] = 1 + 0 otherwise.
Correctness. The longest increasing subarray that ends on A[i] must include A[i] (hence the "1") as well as possibly, if A[i] > A[i−1], a portion that ends on A[i−1]; OPT[i−1] is the maximum length of that portion. If A[i] ≤ A[i−1], no increasing subarray can contain both, so the subarray is just [A[i]]. The best subarray overall ends somewhere, so the answer is the maximum over all i.
Algorithm.
ALG(A):
d = [1] * n
for i = 2, ..., n:
if A[i] > A[i-1]:
d[i] += d[i-1]
return max(d)
Running time. The algorithm makes n − 1 iterations and each takes O(1) time, so the total running time is O(n). On the example, d = [1, 1, 2, 3, 1, 2] and the algorithm returns 3.
Pattern: 3 (the LIS trick), so return max(d), not d[n].
PS 4.3. Minimum-cost jumps
Solution
PS 4.3. Minimum-cost jumps.
LeetCode 746; also Problem 1 of the Day 3 worksheet.
Subproblems. For all i ∈ {1, …, n}, let OPT[i] denote the minimum cost to stop on A[i]. We return min(OPT[n−1], OPT[n]), since we can jump to n + 1 from either index n − 1 or n.
Recurrence. OPT[1] = A[1] and OPT[2] = A[2] (both are reachable directly from index 0). For all i ∈ {3, …, n},
OPT[i] = min(OPT[i−2], OPT[i−1]) + A[i].
Correctness. To land on A[i], we could either jump from A[i−2] or A[i−1] (whichever is cheaper to land on), and we must pay A[i]. These are the only two ways to arrive at i, so the cases are exhaustive. The last jump to n + 1 comes from n − 1 or n, which is why the answer is the smaller of the last two entries.
Algorithm.
ALG(A):
d = [A[1]]*n
d[2] = A[2]
for i = 3, ..., n:
d[i] = min(d[i-2], d[i-1]) + A[i]
return min(d[n-1], d[n])
Running time. O(n) iterations, O(1) each: O(n). On the example, d = [1, 10, 2] and the algorithm returns min(10, 2) = 2.
Pattern: 3 ("stop on A[i]" is the LIS trick; the lecture asked "on your own: why not" the plain prefix version), returning the min of the last two entries.
PS 4.4. Paths in a grid with obstacles
Solution
PS 4.4. Paths in a grid with obstacles.
LeetCode 63.
Subproblems. For all i ∈ {1, …, m} and j ∈ {1, …, n}, let OPT[i][j] denote the number of paths from (1, 1) to (i, j), so we want to return OPT[m][n].
Recurrence. Base cases: in row i = 1, there is exactly one path from (1, 1) to (1, j) until we bump into an obstacle; after that point there are 0 paths. Similar logic holds for column j = 1. For all i, j ≥ 2,
OPT[i][j] = OPT[i−1][j] + OPT[i][j−1] if A[i][j] = 0, OPT[i][j] = 0 otherwise.
Correctness. To get to a free cell (i, j) with i, j ≥ 2, the last step arrives either from (i − 1, j) (moving down) or from (i, j − 1) (moving right). These two sets of paths are disjoint and together contain every path, so their counts add. No path may end on an obstacle, hence 0. In the first row the only possible moves are to the right, so a cell is reached in exactly one way until an obstacle blocks everything after it.
Algorithm.
ALG(A):
d = [0] * (m rows, n columns)
for j = 1, ..., n: # first row
if A[1][j] = 0: d[1][j] = 1
else: break
for i = 1, ..., m: # first column
if A[i][1] = 0: d[i][1] = 1
else: break
for i = 2, ..., m:
for j = 2, ..., n:
if A[i][j] = 0:
d[i][j] = d[i-1][j] + d[i][j-1]
return d[m][n]
Running time. Every iteration of every loop takes O(1) time, so the total running time is O(n) + O(m) + O(mn) = O(mn).
Example. For the first example the rows of d are [1, 1, 1], [1, 0, 1], [1, 1, 2]; for the second, [1, 0] and [1, 1].
Pattern: 6 shape (two indices, one per dimension), filled row by row; the "break" in the base cases is where points are lost.
PS 4.5. Buying and selling a stock
Solution
PS 4.5. Buying and selling a stock.
LeetCode 121; reused verbatim as Practice Final Problem 3 and (with the example [8, 2, 7, 1, 3]) as Midterm 2 Problem 2. Also the Day 5 worksheet, Problem 1.
Subproblems. For all j ∈ {2, …, n}, let OPT[j] denote the maximum profit we could obtain if we had to sell on day j. We return max(OPT).
Recurrence.
OPT[j] = A[j] − mini < j A[i].
Correctness. If we must sell on day j, the profit A[j] − A[i] is largest when A[i] is the smallest price on an earlier day. Every pair (i, j) with i < j sells on some day j ∈ {2, …, n}, so the maximum over j of OPT[j] is the maximum over all pairs.
Algorithm. Evaluated literally, the recurrence "appears to yield an algorithm that runs in O(n²) time (n subproblems, O(n) time each), but we can implement this in O(n) time by updating mini < j A[i] as j increases":
ALG(A):
min_A = A[1]
d = [-inf] * n
for j = 2, ..., n:
d[j] = A[j] - min_A
min_A = min(min_A, A[j])
return max(d)
The order of the two lines in the loop matters: d[j] must use the minimum over days before j, so min_A is updated after d[j] is computed.
Running time. O(n) iterations, O(1) each: O(n). On the example the running minimums before days 2–6 are 8, 2, 2, 2, 1 and d = [−∞, −6, 2, 5, −1, 2], so the algorithm returns 5.
Pattern: 3 (must sell on day j), plus a running minimum to make each entry O(1). The lecture's space-saving version keeps only one number d and the best answer so far.
PS 4.6. Maximum sum with no two adjacent elements
Solution
PS 4.6. Maximum sum with no two adjacent elements.
LeetCode 198. The official solution notes that this "is also a special case of Maximum Independent Set in Trees, if we view A as a path graph and A[i] as the weight of vertex i" (Section 6.3).
Subproblems. For all i ∈ {1, …, n}, let OPT[i] denote the largest feasible value we can obtain given A[1 : i]; we return OPT[n].
Recurrence. OPT[1] = A[1], OPT[2] = max(A[1], A[2]), and for all i ∈ {3, …, n},
OPT[i] = max(OPT[i−1], A[i] + OPT[i−2]).
Correctness. The optimal subsequence S in A[1 : i] either excludes A[i] or includes A[i]. In the former case its value is whatever it could obtain in A[1 : i−1], which is OPT[i−1]. In the latter case its value is A[i] + OPT[i−2], because it cannot include A[i−1] but it can include the optimal solution given A[1 : i−2]. The two cases are exhaustive.
Algorithm.
ALG(A):
if n = 1: return A[1]
if n = 2: return max(A[1], A[2])
d = [A[1]] * n
d[2] = max(A[1], A[2])
for i = 3, ..., n:
d[i] = max(d[i-1], A[i] + d[i-2])
return d[n]
Running time. O(n) iterations, O(1) each: O(n). On the examples, d = [1, 1, 2] (return 2) and d = [3, 8, 8, 9, 20] (return 20: 8 + 12).
Pattern: 1 (prefixes) with the knapsack-style in/out split on the last element.
PS 4.7. Ways to add A's and B's
Solution
PS 4.7. Ways to add A's and B's.
LeetCode 2466.
Subproblems. For all i ∈ {0, 1, …, n}, let OPT[i] denote the optimal value given the instance (A, B, i), that is, the number of ways to reach total i; we return OPT[n].
Recurrence. OPT[0] = 1 (the empty sum). For all i ≥ 1,
OPT[i] = OPT[i − A] + OPT[i − B],
where OPT[j] is interpreted as 0 for all j < 0.
Correctness. Any way of adding to i must end with either A or B. This implies that the number of ways to add to i is the number of ways to add to i − A plus the number of ways to add to i − B. (When A = B the two terms are counted separately, as the problem demands for (1, 1, 1).)
Algorithm.
ALG(A, B, n):
d = [0] * (n+1) # d starts at index 0
d[0] = 1
for i = 1, 2, ..., n:
if i - A >= 0:
d[i] += d[i-A]
if i - B >= 0:
d[i] += d[i-B]
return d[n]
Running time. O(n) iterations, O(1) each: O(n). For (1, 2, 4), d = [1, 1, 2, 3, 5]; for (1, 1, 1), d = [1, 2].
Pattern: 1 on the targets 0, …, n, splitting on the last summand; Midterm 2 Problem 4 generalizes it to n summands.
6.8 Homework-style one-point questions
Homework 4 contained two knapsack questions; its other questions were on LIS and LPS (Chapter 5). Both have the form "Suppose we run the O(nB)-time DP algorithm on the instance. What does the algorithm return?" The homework note said "you are not expected to solve every homework problem using pencil and paper … you can also write and run a program", which is why the second instance is large. On the final you will only see small instances, and the question may ask for the last row instead of the returned value.
Type 1: "What does the algorithm return?" (Homework 4, Q5)
Instance: v = [3, 1, 2], w = [2, 1, 4], B = 4. Fill the table row by row:
| i (v, w) \ j | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| 1 (3, 2) | 0 | 0 | 3 | 3 | 3 |
| 2 (1, 1) | 0 | 1 | 3 | 4 | 4 |
| 3 (2, 4) | 0 | 1 | 3 | 4 | 4 |
The accepted answer is 4 (items 1 and 2, weight 3). Row 3 copies row 2 except possibly at j = 4, where max(OPT[2][4], 2 + OPT[2][0]) = max(4, 2) = 4: item 3 is heavy and cheap, so it never helps. A quick check you can always do: the answer is at least the best single item that fits and at most the sum of all values.
Type 2: a large instance (Homework 4, Q6)
Q6 had 50 items and B = 40; the accepted answer is 137, obtained by typing Knapsack-DP into a program. Nothing about the method changes; this guide recomputed the value with exactly the pseudocode of Section 6.1.
Type 3: "What are the values in the last row of d?" (the final's format)
This is the Practice Final's version (Problem 1e, Section 6.9). The answer has B + 1 numbers starting with 0, and it is row n of the same table. Since the table is never ambiguous (no tie-breaking is involved), the only risks are arithmetic and the "previous row" trap. Write each row on scratch paper before the next, and check that each row is non-decreasing from left to right and is at least the row above it entry by entry: more capacity or more items can never hurt.
6.9 Past exam problems on this chapter
These are the dynamic-programming problems of the course's exams that belong to this chapter: the knapsack part of the Practice Final's Problem 1, and every multi-point dynamic-programming design problem of Midterm 2, Practice Midterm 2 and the Practice Final. Three of the six design problems were copied from Problem Set 4, which is the strongest evidence for the final's promise of repeated problems. (None of these exams had a one-point part on trees.) Statements are verbatim; solutions follow the official ones.
Practice Final, Problem 1e. Last row of the knapsack table
Solution
Practice Final, Problem 1e (one point, no explanation).
[0, 2, 4, 6, 7]. The rows are [0, 0, 3, 3, 3], then [0, 0, 4, 4, 7] (OPT[2][4] = max(3, 4 + OPT[1][2]) = 7), then [0, 2, 4, 6, 7]: OPT[3][1] = 2 + 0 = 2, OPT[3][3] = max(4, 2 + OPT[2][2]) = 6, OPT[3][4] = max(7, 2 + OPT[2][3]) = max(7, 6) = 7.
Practice Final, Problem 3. Stock profit
Solution
Practice Final, Problem 3. The official solution: "This is Problem 4.5 from Problem Set 4." Here is the full answer as it should be written.
Subproblems. For all j ∈ {2, …, n}, let OPT[j] denote the maximum profit if we had to sell on day j; we return max(OPT).
Recurrence. OPT[j] = A[j] − mini < j A[i].
Correctness. Selling on day j, the best purchase is the cheapest earlier day; every valid pair sells on some day j ≥ 2, so the maximum over j is the answer.
Algorithm.
ALG(A):
min_A = A[1]
d = [-inf] * n
for j = 2, ..., n:
d[j] = A[j] - min_A
min_A = min(min_A, A[j])
return max(d)
Running time. Maintaining min_A as j increases makes each entry O(1), so n − 1 iterations take O(n) in total. On the example d = [−∞, −6, 2, 5, −1, 2] and the answer is 5.
Pattern: 3, with a running minimum.
Practice Final, Problem 7. Skip the next B[i] elements
Solution
Practice Final, Problem 7. The official solution: "This is LeetCode 2140; the solution is similar to 0/1 Knapsack."
Subproblems. For all i ∈ {1, …, n}, let OPT[i] denote the maximum feasible sum given A[i : n], so we want to return OPT[1]. Suffixes are the right choice because the rule looks to the right: choosing A[i] affects the next B[i] elements, so what remains after a choice is always a suffix.
Recurrence. The base case is OPT[n] = A[n] (or 0, if A[n] < 0). For all i ∈ {1, …, n − 1},
OPT[i] = max( OPT[i+1], A[i] + OPT[i + B[i] + 1] ),
where OPT[j] = 0 for all j > n.
Correctness. The optimal solution for A[i : n] either excludes A[i] or includes it. If it excludes A[i], its value is whatever is obtainable in A[i+1 : n], which is OPT[i+1]. Otherwise it is A[i] plus whatever is obtainable in A[i + B[i] + 1 : n], since the next B[i] elements are forbidden and everything after them is unconstrained by A[i]. The cases are exhaustive. OPT[i] depends on OPT[j] for j > i, "so we must solve the subproblems from i = n through i = 1."
Algorithm.
ALG(A, B):
d = [max(A[n], 0)]*n
for i = n-1, ..., 1:
if i+B[i]+1 <= n:
d[i] = max(d[i+1], A[i] + d[i+B[i]+1])
else:
d[i] = max(d[i+1], A[i])
return d[1]
Running time. The algorithm makes n − 1 iterations, and each takes O(1) time, so the total running time is O(n).
Check on the examples. First: d = [5, 4, 4, 2], return 5. Second: d = [7, 7, 5, 5, 5], return 7. Third: d = [6, 3, 3, 3], return 6 (d[1] = max(d[2], 3 + d[4]) = max(3, 6)).
Pattern: 2 (suffixes), with the knapsack in/out split. Note the negative case: the array holds integers, so "skip everything" (value 0) must be possible, which is why the base case is max(A[n], 0).
Midterm 2, Problem 2. Stock profit
Solution
Midterm 2, Problem 2. Official solution: "This is Problem 4.5 from Problem Set 4." Write exactly the PS 4.5 answer (subproblem "maximum profit if we had to sell on day j", recurrence OPT[j] = A[j] − mini < j A[i], the running-minimum pseudocode, O(n)).
Trace on this example. Running minimum before day j: 8, 2, 2, 1 for j = 2, 3, 4, 5. d = [−∞, −6, 5, −1, 2]. The algorithm returns 5 (buy at 2, sell at 7). The minimum later drops to 1, but the best sale after that is only 3, which is why the answer is a maximum over all selling days and not "the last day minus the minimum".
Pattern: 3, identical to PS 4.5.
Midterm 2, Problem 4. Counting lists with sum t
Solution
Midterm 2, Problem 4: PS 4.7 with n summands instead of two.
Subproblems. For all i ∈ {0, 1, …, t}, let OPT[i] denote the answer given the input (A, i); we'll return OPT[t].
Recurrence. The base case is OPT[0] = 1, since the only list whose sum is 0 is the empty list. For all i ∈ {1, …, t},
OPT[i] = Σj OPT[i − A[j]],
where the sum is over every index j such that i − A[j] ≥ 0.
Correctness. Every list whose sum is i must end on some element A[j], and removing that last element leaves a list whose sum is i − A[j]; conversely, appending A[j] to any list with sum i − A[j] gives a list with sum i. Lists ending in different elements are different (the A[j] are distinct), so we can calculate OPT[i] by summing over all possible last elements.
Algorithm.
ALG(A, t):
d = [0] * (t+1) # start at index 0
d[0] = 1
for i = 1, ..., t:
for j = 1, ..., n:
if i - A[j] >= 0:
d[i] += d[i - A[j]]
return d[t]
Running time. The algorithm makes t iterations, and each takes O(n) time, so the total running time is O(nt).
Trace on the example. d[0..4] = [1, 1, 2, 4, 7]: d[3] = d[2] + d[0] + d[1] = 2 + 1 + 1 = 4 (last element 1, 3 or 2), d[4] = d[3] + d[1] + d[2] = 4 + 1 + 2 = 7.
Pattern: 1 on the targets 0, …, t, splitting on the last element of the list. Order matters (lists, not sets), which is why the outer loop is over the target; this is the counting cousin of Unbounded Knapsack.
Practice Midterm 2, Problem 2. Longest increasing contiguous subsequence
Solution
Practice Midterm 2, Problem 2. Official solution: "This is Problem 4.2 from Problem Set 4."
Subproblems. OPT[i] = the length of the longest contiguous increasing subsequence in A[1 : i] that must end on A[i]; return max(OPT).
Recurrence. OPT[1] = 1; OPT[i] = 1 + OPT[i−1] if A[i] > A[i−1], else 1.
Correctness. The subarray ending at A[i] contains A[i] and, only if A[i] > A[i−1], an increasing subarray ending at A[i−1], of maximum length OPT[i−1]; the best subarray ends somewhere, hence the max.
Algorithm. d = [1]*n; for i = 2, …, n: if A[i] > A[i−1]: d[i] += d[i−1]; return max(d).
Running time. n − 1 iterations of O(1): O(n). On the example d = [1, 1, 2, 3, 1, 2], answer 3.
Pattern: 3, identical to PS 4.2.
Practice Midterm 2, Problem 4. Is C a shuffle of A and B?
Solution
Practice Midterm 2, Problem 4. The official solution: "Our approach is similar to the Edit Distance DP."
Subproblems. For all i ∈ {0, 1, …, m} and j ∈ {0, 1, …, n}, let OPT[i][j] be True if A[1 : i] and B[1 : j] can be merged to create C[1 : i + j] and False otherwise, so we want to return OPT[m][n].
Recurrence. If i = 0, A[1 : i] is the empty string, so OPT[0][j] is True if and only if B[1 : j] = C[1 : j]; the case j = 0 is analogous. For i ≥ 1 and j ≥ 1 (∧ is "and", ∨ is "or"):
OPT[i][j] = ( (A[i] = C[i+j]) ∧ OPT[i−1][j] ) ∨ ( (B[j] = C[i+j]) ∧ OPT[i][j−1] ).
Correctness. In any merge of A[1 : i] and B[1 : j] into C[1 : i + j], the last character C[i + j] comes from the end of A[1 : i] or from the end of B[1 : j]. If A[i] = C[i + j] and A[1 : i−1] and B[1 : j] can be merged into C[1 : i + j − 1], then the same merge followed by A[i] creates C[1 : i + j]; the B case is analogous. If neither A[i] nor B[j] matches C[i + j], no merge exists. The two cases are exhaustive.
Algorithm. Row 0 first, then column 0, then the rest row by row, left to right:
ALG(A, B, C):
d = [False] * ((m+1) x (n+1)) # rows 0..m, columns 0..n
d[0][0] = True
for j = 1, ..., n: # row 0
d[0][j] = d[0][j-1] and (B[j] = C[j])
for i = 1, ..., m: # column 0
d[i][0] = d[i-1][0] and (A[i] = C[i])
for i = 1, ..., m:
for j = 1, ..., n:
if A[i] = C[i+j]: d[i][j] = (d[i][j] or d[i-1][j])
if B[j] = C[i+j]: d[i][j] = (d[i][j] or d[i][j-1])
return d[m][n]
Running time. There are O(mn) subproblems, and each takes O(1) time, so the total running time is O(mn).
Trace. For A = art, B = bat, C = arbtat (T = True, F = False; rows i = 0..3 are "", a, r, t; columns j = 0..3 are "", b, a, t):
| i \ j | 0 | 1: b | 2: a | 3: t |
|---|---|---|---|---|
| 0 | T | F | F | F |
| 1: a | T | F | F | F |
| 2: r | T | T | F | F |
| 3: t | F | T | T | T |
For example d[2][1] is True because B[1] = b = C[3] and d[2][0] (ar = C[1 : 2]) is True; d[3][3] is True because B[3] = t = C[6] and d[3][2] is True. The algorithm returns True; on rtabat and aabrtt it returns False.
Pattern: 6 (a pair of prefixes), with indices from 0 because empty prefixes matter.
Before moving on
- I can fill a 0/1 knapsack table row by row and write its last row, and I read the previous row in the "include" option.
- I can state how the recurrence changes for Unbounded Knapsack and why the one-array version must sweep right to left.
- I can write the OPTin/OPTout recurrences with leaf cases, compute them children first, and explain the O(n) running time.
- I can write the matching recurrence and the subtraction trick that makes it O(n).
- I can name the pattern (1 to 8) of a new problem and write its subproblem sentence in the course's words.
- I can reproduce every Problem Set 4 solution and the Practice Final's Problem 7.
Exercises
Solution
Rows: [0, 2, 2, 2, 2, 2, 2]; [0, 2, 2, 2, 6, 8, 8]; [0, 2, 3, 5, 6, 8, 9]; last row [0, 2, 3, 5, 7, 8, 10]. For example OPT[4][6] = max(OPT[3][6], 5 + OPT[3][3]) = max(9, 10) = 10 and OPT[4][4] = max(6, 5 + OPT[3][1]) = 7. Walking back from (4, 6): item 4 in (10 ≠ 9), go to (3, 3); item 3 in (5 ≠ 2), go to (2, 1); item 2 out (2 = 2), then item 1 in. Items {1, 3, 4}, weight 6, value 10.Solution
Leaves 5, 6, 3, 7: (2, 0), (4, 0), (2, 0), (6, 0). Vertex 2: (7 + 0 + 0, 2 + 4) = (7, 6). Vertex 4: (3 + 0, 6) = (3, 6). Root: OPTin[1] = 5 + 6 + 0 + 6 = 17, OPTout[1] = max(7, 6) + max(2, 0) + max(3, 6) = 15. The answer is 17, the set {1, 5, 6, 7}.
Vertex cover (Exercise 6.6's recurrences): leaves (w, 0); vertex 2: in = 7 + min(2, 0) + min(4, 0) = 7, out = 2 + 4 = 6; vertex 4: in = 3, out = 6; root: in = 5 + min(7, 6) + min(2, 0) + min(3, 6) = 14, out = 7 + 2 + 3 = 12. Minimum cover weight 12, the set {2, 3, 4}. (Its complement {1, 5, 6, 7} is the maximum independent set: 12 + 17 = 29 is the total weight, as it must be in any graph.)
Solution
Row 1 (⌊j/2⌋ · 3): [0, 0, 3, 3, 6, 6, 9, 9]. Row 2 (max(row 1, 5 + row 2 three to the left)): [0, 0, 3, 5, 6, 8, 10, 11]. It returns 11: one copy of item 1 and two of item 2 (2 + 3 + 3 = 7, value 3 + 5 + 5). The 0/1 version would return 8.Solution
d[5] = 2; d[4] = max(d[5], 6 + d[6]) = max(2, 6) = 6; d[3] = max(d[4], 4 + d[4]) = 10 (B[3] = 0, so nothing is skipped); d[2] = max(d[3], 1 + d[6]) = 10; d[1] = max(d[2], 5 + d[3]) = 15. d = [15, 10, 10, 6, 2], return 15 (5 + 4 + 6: taking A[1] skips A[2], taking A[3] skips nothing, taking A[4] skips A[5]).Solution
The Chapter 3 worksheet's counterexample: v = [4, 4, 7], w = [5, 5, 6], B = 10. Ratios are 0.8, 0.8 and about 1.17, so greedy picks item 3 (value 7) and then nothing else fits (4 units left). Knapsack-DP: rows [0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4], [0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 8], [0, 0, 0, 0, 0, 4, 7, 7, 7, 7, 8]; it returns 8 (items 1 and 2).Solution
Subproblems. For all u ∈ V, let OPTin[u] be the minimum weight of a vertex cover of Tu that includes u, and OPTout[u] the minimum weight of one that excludes u. We return min(OPTin[1], OPTout[1]).
Recurrence. Leaf: OPTin[u] = w[u], OPTout[u] = 0. Otherwise OPTin[u] = w[u] + Σv ∈ T[u] min(OPTin[v], OPTout[v]) and OPTout[u] = Σv ∈ T[u] OPTin[v].
Correctness. A cover of Tu consists of covers of the children's subtrees (which share no edges) plus possibly u, and must also cover the edges (u, v). If u is in the cover, every edge (u, v) is covered, so each child's subtree may use its cheapest cover with or without v. If u is not in the cover, each edge (u, v) must be covered by v, so each child's subtree must use a cover that includes v. A leaf's subtree has no edges. Every cover includes or excludes u, so the cases are exhaustive.
Algorithm.
VC-Tree(T, w):
d_in, d_out = [0]*n, [0]*n
sort V in reverse topological order
for u in V:
d_in[u] = w[u]
for v in T[u]:
d_in[u] += min(d_in[v], d_out[v])
d_out[u] += d_in[v]
return min(d_in[1], d_out[1])
Running time. The order takes O(m + n) = O(n). Vertex u costs O(|T[u]|), and Σu |T[u]| = n − 1, so the total is O(n).
Solution
The "take u" option forgets the rest of the subtree: if u is taken, its children are excluded but its grandchildren's subtrees are still free, so that option must be w[u] + Σv Σx ∈ T[v] OPT[x] (Section 6.4), or the student must switch to OPTin/OPTout. The case analysis is therefore not correct, and the grader takes off for the recurrence and the proof. Counterexample: the path 1 – 2 – 3 rooted at 1 with weights 5, 1, 5. The student gets OPT[3] = 5, OPT[2] = max(1, 5) = 5, OPT[1] = max(5, 5) = 5, but {1, 3} weighs 10.Solution
Subproblems. For all i ∈ {0, 1, …, n} and j ∈ {0, 1, …, B}, let OPT[i][j] be True if some subset of items 1, …, i has total weight exactly j; we return OPT[n][B].
Recurrence. OPT[0][0] = True and OPT[0][j] = False for j ≥ 1 (with no items only weight 0 is possible). For i ≥ 1: OPT[i][j] = OPT[i−1][j] if w[i] > j, and OPT[i][j] = OPT[i−1][j] ∨ OPT[i−1][j − w[i]] otherwise.
Correctness. A subset of [i] with weight exactly j either omits item i (then it is a subset of [i − 1] with weight j) or contains it (then the rest is a subset of [i − 1] with weight j − w[i], possible only if w[i] ≤ j). The two cases are exhaustive, and each direction of the "or" builds an actual subset.
Algorithm. Knapsack-DP with "or" in place of max and rows starting at i = 0:
Subset-Sum(w, B):
d = [False] * ((n+1) x (B+1)) # rows 0..n, columns 0..B
d[0][0] = True
for i = 1, ..., n:
for j = 0, ..., B:
d[i][j] = d[i-1][j]
if j >= w[i]:
d[i][j] = d[i][j] or d[i-1][j-w[i]]
return d[n][B]
Running time. (n + 1)(B + 1) entries, O(1) each: O(nB).
Run. Reachable weights after item 1: {0, 3}; after item 2: {0, 3, 5} (3 + 5 = 8 exceeds 7); after item 3: {0, 2, 3, 5, 7}. So OPT[3][7] is True (5 + 2).
Course Ch. 5 · Oct 20–277. Shortest paths
Course Chapter 5 asks for the shortest route from one vertex to the others in a directed graph whose edges have lengths, and then for the shortest route between every pair of vertices. The course notes split the chapter into four sections: §5.1 (DAG DP), §5.2 (Bellman-Ford) and §5.3 (Dijkstra's algorithm) solve the single-source problem under three different assumptions about the graph and its lengths, and §5.4 (Floyd-Warshall) solves the all-pairs problem. In the notes' words, "every section, except 5.3 (Dijkstra's algorithm) uses dynamic programming", so the subproblem-and-recurrence recipe of Chapter 5 is the main tool, and Dijkstra's algorithm is a greedy algorithm in the style of Prim's algorithm from Chapter 4. The algorithm you may use depends on what the graph is allowed to contain (cycles, negative lengths, negative cycles), so this chapter keeps track of the assumptions throughout and ends with a table that says which algorithm to call when. On the final, shortest paths can appear as a one-point trace ("what are the final values in d?", as on Midterm 2 and the Practice Midterm 2) and as a design problem: the Practice Final's Problem 5 is a shortest-path problem, and Midterm 2 reused Problem Set 5, Problem 4 word for word. Every algorithm in this chapter rests on one fact: a shortest path to v consists of a shortest path to some in-neighbor u of v followed by the edge (u, v); the algorithms differ only in the order in which they can safely use it.
7.1 The shortest-path problem and edge relaxation
In plain words. Every edge of a directed graph has a number attached, its length, and the length of a route is the sum of the lengths of its edges. We want, for every vertex, the length of the shortest route from a fixed starting vertex, which the course calls the source. Lengths may be negative, which is natural when an edge represents a gain rather than a cost, but then a loop of negative total length would let a route become shorter forever, so such loops must be ruled out. All the algorithms of the chapter fill an array d of distance estimates and improve it by one basic move, called relaxing an edge.
- Input: a directed graph G, a length ℓ(e) on every edge (an integer, possibly zero or negative), and a source vertex s. Output: an array d with d[v] = the distance from s to v.
- The distance from s to v is the smallest length of any s→v path; it is ∞ when v cannot be reached from s.
- Relaxing the edge (u, v) means d[v] = min(d[v], d[u] + ℓ(u, v)): "check if we can improve d[v] through d[u]," in the lecture's words.
- A negative cycle (a cycle whose lengths sum to less than 0) makes "shortest" meaningless, so the chapter assumes there is none.
- The paths themselves are recovered by keeping a parent pointer for each vertex and tracing it back; the course's algorithms return only d.
- BFS (Chapter 3) already solves the problem when every edge has the same positive length.
Problem
- Length of a path
- The sum of the lengths of its edges; a path with no edges has length 0.
- Walk
- Like a path, but vertices and edges may repeat. The notes remark that "a 'path' is not allowed to repeat vertices by definition, but in this context, it's common to use 'path' when we really mean 'walk.'"
- Negative cycle
- "A cycle C is a negative cycle if Σe ∈ C ℓ(e) < 0."
- Relaxing an edge
- The update d[v] = min(d[v], d[u] + ℓ(u, v)). The notes: "Intuitively, when we relax (u, v), we're checking if we can decrease our current estimate of the distance from s to v by following an s-u path plus the edge (u, v)."
The lecture of October 20 opened by recalling that BFS "works when all ℓ(e) are the same and > 0": then the shortest path is the one with fewest edges, which is what BFS computes in O(m + n) time. The four new algorithms handle more general lengths. The one fact behind all of them is the one in bold above. If P is a shortest s→v path and its last edge is (u, v), then the part of P before that edge is a shortest s→u path (if there were a shorter s→u path, attaching (u, v) to it would beat P). So the distance to v is the minimum, over the in-neighbors u of v, of the distance to u plus ℓ(u, v). Relaxing (u, v) is exactly one term of that minimum.
In the graph above the cycle 2 → 3 → 2 has length −3 + 1 = −2. A walk from 1 to 2 can go around it as often as it likes, getting 2 shorter each time, so there is no shortest walk from 1 to 2 or to 3. The notes explain why the course does not simply forbid repeated vertices instead: "then the SSSP problem becomes much more difficult"; it becomes NP-hard (course Chapter 7), which "means it appears to be impossible to solve in polynomial time." Course Chapter 7 is not on the final (see Chapter 10), so all you need is the conclusion: the chapter assumes there is no negative cycle whenever lengths can be negative.
7.2 DAG DP: shortest paths in a DAG
In plain words. When the graph has no cycles, the vertices can be listed in an order in which every edge points forward. Processing the vertices in that order, each vertex looks back at the vertices with an edge into it, all of which are already finished, and takes the best of "their distance plus the connecting edge." No vertex ever needs to be revisited, so the whole computation is one pass over the edges. Negative lengths cause no trouble at all, because without cycles there is no loop to exploit.
- Input: a DAG G with any integer lengths (negative allowed) and a source s. Output: the distance array d.
- Subproblems: OPT[v] = the distance from s to v, for every vertex v; base case OPT[s] = 0.
- Recurrence: OPT[v] = min over in-neighbors u of v of OPT[u] + ℓ(u, v), and ∞ when v has no in-neighbor.
- Order: topological order, so every in-neighbor of v is done before v (Chapter 3).
- The reverse graph GR lists the in-neighbors of every vertex; building it up front keeps the time at O(m + n).
- Running time O(m + n), the same as BFS.
- Replace min by max (and initialize d to −∞) and the same algorithm finds longest paths, which only makes sense because a DAG has no cycles.
Problem
Problem (course notes §5.1). "SSSP, where G is a Directed Acyclic Graph (DAG). Describe an O(m + n)-time algorithm for this problem, prove that it's correct, and analyze its running time." The lecture added that the lengths "can be anything." For a tiny instance, take the edges (1, 2) of length 3 and (2, 3) of length −5 with s = 1: the answer is d = [0, 3, −2].
Subproblems
"For all v ∈ V, let OPT[v] denote the distance from s to v. We will return the entire array d = OPT." The subproblems are the vertices themselves, which is why the notes say the chapter's dynamic programs use "the vertices as subproblems."
Recurrence
OPT[v] = minu: (u, v) ∈ E ( OPT[u] + ℓ(u, v) ),
"since the shortest path P from s to v must arrive at some in-neighbor u of v and traverse the edge (u, v). The subpath of P from s to u must be a shortest path from s to u." If v has no in-neighbor the minimum is over nothing and OPT[v] = ∞.Algorithm
The recurrence for v needs OPT of every in-neighbor of v, so the in-neighbors must be finished first. In a DAG this is always possible: sort the vertices in topological order (every edge goes from an earlier vertex to a later one, so every in-neighbor of v comes before v) and fill d in that order. The notes compare it with the tree DP of Chapter 6: "This is like Section 4.6, except the edge directions are reversed." The second ingredient is access to the in-neighbors: the adjacency list G[v] holds the out-neighbors of v, so the algorithm first builds the reverse graph GR, in which every edge is flipped and GR[v] lists exactly the in-neighbors of v. Building it is one scan of the lists: for each u, for each v in G[u], append u to GR[v]. Then, for each v in topological order, relax every edge coming into v. The pseudocode is the notes':
DAG-DP(G, s):
d = [inf]*n; d[s] = 0
sort V in topological order
G^R = reverse of G
for v in V: # in topological order
for u in G^R[v]: # every in-neighbor u of v
d[v] = min(d[v], d[u] + l(u,v)) # relax (u, v)
return d
The lecture's example (October 20) has s = 1 and six edges, drawn here in the topological order 1, 3, 4, 2 so that every edge points to the right:
| Step | v | In-neighbors (GR[v]) | Candidates d[u] + ℓ(u, v) | d[v] | d = [d[1], d[2], d[3], d[4]] |
|---|---|---|---|---|---|
| 0 | initialization | [0, ∞, ∞, ∞] | |||
| 1 | 1 | none | none (d[1] stays 0) | 0 | [0, ∞, ∞, ∞] |
| 2 | 3 | 1 | 0 + 10 = 10 | 10 | [0, ∞, 10, ∞] |
| 3 | 4 | 1, 3 | 0 + (−4) = −4; 10 + 3 = 13 | −4 | [0, ∞, 10, −4] |
| 4 | 2 | 1, 3, 4 | 0 + 5 = 5; 10 + (−7) = 3; −4 + (−2) = −6 | −6 | [0, −6, 10, −4] |
Some cells worked out: vertex 3 has the single in-neighbor 1, so d[3] = 10 even though the edge is long, because there is no other way in. Vertex 4 can be reached directly (−4) or through 3 (10 + 3 = 13), and the direct edge wins. Vertex 2 has three in-neighbors; the best route is 1 → 4 → 2 of length −4 − 2 = −6, which is what the lecture wrote in red next to vertex 2. The answer is d = [0, −6, 10, −4], and the shortest-path tree (each vertex's best last edge) is:
Correctness
The argument has two parts, and both are needed on the exam. The recurrence is right (exhaustive cases): a shortest s→v path with v ≠ s has a last edge (u, v) for some in-neighbor u, and the part before it is a shortest s→u path, so its length is OPT[u] + ℓ(u, v) for that u; conversely, for every in-neighbor u, a shortest s→u path plus (u, v) is an s→v path of length OPT[u] + ℓ(u, v). So the distance is the minimum over all in-neighbors. The order is right: in topological order every in-neighbor of v comes before v, so when the loop reaches v every d[u] it reads is already final (by induction on the position in the order). Vertices that come before s in the order, and vertices not reachable from s, keep d = ∞, which is correct.
Running time
In the notes' words: "We can sort V in topological order in O(m + n) time, and we can also compute GR in O(m + n) time. Computing d[v] takes O(in-deg(v)) time, and the sum of in-degrees is m. Thus, the total running time is O(m + n)." The notes also say why GR is built in advance: "Finding v's in-neighbors as we're computing d[v] could take Ω(n) time per vertex, which would exceed our target running time of O(m + n)."
Variant: longest paths in a DAG (Worksheet for Day 1, Problem 1)
"Can we use similar logic to DAG DP to find the longest path from s to every vertex in a DAG?" The official answer: "Yes, basically by replacing 'min' with 'max'. More specifically, if OPT[v] is the length of the longest s-v path in a DAG, then it is equal to the maximum value of OPT[u] + ℓ(u, v) over every in-neighbor u of v." Initialize d to −∞ (except d[s] = 0) and keep the topological order. On the lecture's example the longest-path values are d[3] = 10, d[4] = max(−4, 10 + 3) = 13 and d[2] = max(5, 10 − 7, 13 − 2) = 11, so d = [0, 11, 10, 13]. The same argument works because in a DAG a path can never revisit a vertex; Section 7.3 shows why it fails as soon as there is a cycle.
Variant: widest paths (Problem Set 5, Problem 1)
The width of a path is its smallest edge width, its "bottleneck," and the problem asks for the widest path to every vertex. The recurrence becomes OPT[v] = maxu min(OPT[u], w(u, v)) with OPT[s] = ∞. It is worked in full in Section 7.7.
Check-in 7.1. Run DAG-DP from s = 1 on the DAG with edges (1, 2) of length 2, (1, 3) of length 6, (2, 3) of length −3, (2, 4) of length 4, (3, 4) of length 5, (3, 5) of length 1, (4, 5) of length −2. The topological order is 1, 2, 3, 4, 5. Fill in d.
| v | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| d[v] |
Answer
d = [0, 2, −1, 4, 0]: d[3] = min(0 + 6, 2 − 3) = −1, d[4] = min(2 + 4, −1 + 5) = 4, d[5] = min(−1 + 1, 4 − 2) = min(0, 2) = 0 (along 1 → 2 → 3 → 5).7.3 Bellman-Ford
In plain words. Once the graph may contain cycles, there is no order in which every vertex's in-neighbors are finished first, so the DAG recurrence cannot be evaluated. Bellman-Ford adds a second index, the number of edges a walk is allowed to use, and computes the best walk to every vertex with at most 0 edges, then at most 1, then at most 2, and so on. Each round only needs the previous round, so there is no circularity. Because there is no negative cycle, a shortest walk never needs more than n − 1 edges, so after n − 1 rounds the values are the true distances.
- Input: any directed graph with integer lengths (negative allowed) and no negative cycle, and a source s. Output: the distance array d.
- Subproblems: OPT[v][j] = the length of the shortest s→v walk with at most j edges, for j = 0, 1, …, n − 1; return the last column j = n − 1.
- Recurrence: OPT[v][j] = min(OPT[v][j − 1], min over in-neighbors u of OPT[u][j − 1] + ℓ(u, v)); base OPT[s][0] = 0 and OPT[v][0] = ∞ otherwise.
- Why n − 1 columns suffice: with no negative cycle, a shortest walk can be taken to be a path, which has at most n − 1 edges.
- Bellman-Ford-2, the space-saving version, keeps one array and relaxes every edge in each of n − 1 rounds; it returns the same final answer.
- Running time O(mn) for both versions: n − 1 rounds, each relaxing all m edges in O(1) apiece.
- Stopping after k columns of the table version gives "shortest walk with at most k edges" in O(mk) time (Practice Final, Problem 5).
Problem
Problem (course notes §5.2). "SSSP, where G has no negative cycle. Describe an O(mn)-time algorithm for this problem, prove that it's correct, and analyze its running time." A tiny instance: edges (1, 2) of length 5, (1, 3) of length 2, (2, 3) of length −4, s = 1 (the lecture's Day 2 example). The answer is d = [0, 5, 1], because 1 → 2 → 3 has length 5 − 4 = 1, shorter than the direct edge of length 2.
Why the DAG recurrence breaks
The lecture first wrote OPT[v] = minu(OPT[u] + ℓ(u, v)) and then crossed it out "because of cycles": on a cycle 3 → 5 → 7 → 3, OPT[5] needs OPT[3], which needs OPT[7], which needs OPT[5]. The recurrence is still a true statement about distances, but there is no order in which to evaluate it. The repair is the knapsack trick of Chapter 6. The notes put it this way: "we want to apply the recurrence from DAG-DP, but cycles in G create dependency problems. However, we can still 'shrink' the SSSP problem by drawing inspiration from 0/1 Knapsack (Section 4.4). To solve that problem, we shrunk the knapsack capacity from B to j; similarly, in Bellman-Ford, we shrink the number of edges we can use from n − 1 to j."
Subproblems
Recurrence
OPT[v][j] = min( OPT[v][j − 1], minu: (u, v) ∈ E OPT[u][j − 1] + ℓ(u, v) ).
In the notes' words, "the path corresponding to OPT[v][j] either contains at most j − 1 edges, or it consists of an s-u walk that contains at most j − 1 edges followed by the edge (u, v)."Algorithm
Picture the table with one row per vertex and one column per j = 0, 1, …, n − 1. Column 0 is 0 in the row of s and ∞ everywhere else, since with zero edges you can only be at s. "Column j depends on column j − 1, so we compute the recurrence column by column." To fill entry (v, j), copy the entry to its left (the walk that uses at most j − 1 edges) and then, for every in-neighbor u of v, try the entry of u in the previous column plus ℓ(u, v). As in DAG DP, the in-neighbors come from GR. The last column is returned.
Bellman-Ford(G, s):
d = [inf]*(n * n); d[s][0] = 0 # rows = vertices, columns j = 0..n-1
G^R = reverse of G
for j = 1, ..., n-1:
for v in V:
d[v][j] = d[v][j-1] # at most j-1 edges
for u in G^R[v]: # or: last edge (u, v)
d[v][j] = min(d[v][j], d[u][j-1] + l(u,v))
return d[.][n-1] # last column of d
The lecture's Day 1 example has s = 1 and n = 4, so the columns are j = 0, 1, 2, 3:
| v \ j | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| 1 | 0 | 0 | 0 | 0 |
| 2 | ∞ | 4 | 2 | 2 |
| 3 | ∞ | ∞ | 3 | 1 |
| 4 | ∞ | 5 | 5 | 5 |
Some cells worked out. Column 1: OPT[2][1] = min(∞, OPT[1][0] + 4) = 4 and OPT[4][1] = min(∞, OPT[1][0] + 5) = 5; vertex 3 has in-neighbors 2 and 4, both ∞ in column 0, so OPT[3][1] = ∞. Column 2: OPT[2][2] = min(4, OPT[1][1] + 4, OPT[4][1] − 3) = min(4, 4, 2) = 2, using 1 → 4 → 2; OPT[3][2] = min(∞, OPT[2][1] − 1, OPT[4][1] + 2) = min(∞, 3, 7) = 3. Column 3: OPT[3][3] = min(3, OPT[2][2] − 1, OPT[4][2] + 2) = min(3, 1, 7) = 1, using the three-edge walk 1 → 4 → 2 → 3. The returned column is d = [0, 2, 1, 5], and the shortest-path tree is:
Correctness
The proof is the exhaustive-case argument of every dynamic program (Chapter 5) plus one fact about the last column. The recurrence: consider a shortest s→v walk W with at most j edges. Either W has at most j − 1 edges, and then its length is OPT[v][j − 1]; or it has exactly j edges, and then it ends with some edge (u, v) and the part before it is an s→u walk with at most j − 1 edges, whose length is at least OPT[u][j − 1], so W costs at least OPT[u][j − 1] + ℓ(u, v). Conversely every term of the minimum is the length of an actual walk to v with at most j edges. So the minimum is exactly OPT[v][j]. The order: column j reads only column j − 1, so filling the columns left to right always reads finished values. The last column is the distance: since there is no negative cycle, removing a cycle from a walk never makes it longer, so some shortest walk to v repeats no vertex; such a walk has at most n − 1 edges, so it is counted in column n − 1.
Running time
The notes: "In both implementations, the algorithm makes n − 1 rounds. In each round, each of the m edges gets relaxed, and relaxing an edge takes O(1) time. Thus, the total running time is O(mn)." The lecture wrote the count per column as "n columns, each takes O(m + n) = O(m)," with the margin remark that m + n = O(m) "assuming G is connected (in undirected sense)," because then n − 1 ≤ m. On the October 27 recap the lecture added that O(mn) "could be O(n³)" when the graph is dense.
The space-saving version, Bellman-Ford-2
Column j depends only on column j − 1, so "our DP table does not actually need to store n separate columns": one array d, overwritten in place, is enough. The notes also point out that "in round j of the algorithm, we relax every edge, and the order in which we relax these edges does not matter." That gives the version found in most textbooks, which needs no reverse graph because it simply visits every edge once per round (in the lecture's words, "for u in V: for v in G[u]"):
Bellman-Ford-2(G, s): # space-saving version
d = [inf]*n; d[s] = 0
for j = 1, ..., n-1:
for (u,v) in E: # relax every edge
d[v] = min(d[v], d[u] + l(u,v))
return d
Variant: at most k edges
Because OPT[v][j] already means "shortest walk with at most j edges," a problem that limits the number of edges is solved by stopping the table early: run k columns instead of n − 1 and return column k, in O(mk) time. With k = 10 this is the Practice Final's Problem 5 (Section 7.9), whose official solution stresses "the original version, not the space-saving one," for exactly the reason in the orange box above.
Variant: longest paths do not work (Worksheet for Day 1, Problem 3)
"Can we use similar logic to Bellman-Ford to find the longest path from s to every vertex in a directed graph with positive edge lengths?" Official answer: "No, because positive-length cycles could result in 'distances' that don't correspond to actual paths." In the lecture's picture below (every edge of length 1), the recurrence with max reaches vertex 1 again after going around the cycle 1 → 2 → 3 → 1, and the value at vertex 1 jumps from 1 to 4, the lecture's "problem!": the number corresponds to the walk s → 1 → 2 → 3 → 1, not to a path, and it keeps growing with every column. The notes add that "this reasoning also explains why the original version of Bellman-Ford assumes that the input graph has no negative cycles."
Variant: a cost budget (Worksheet for Day 3, Problem 3)
If every edge has a positive integer cost and the walk's total cost must be at most B, replace "number of edges" by "total cost" as the second index: OPT[v][b] = shortest s→v walk of total cost at most b. The lecture labels the two ingredients: the budget is the knapsack capacity and the cost is the "weight of item i." It is worked in Section 7.7.
Extra context beyond the notes: if a negative cycle is reachable from s, some edge can still be relaxed after n − 1 rounds, so one extra round that checks for a change detects it in O(m) more time. The course does not ask for this.
Check-in 7.2. Fill in the Bellman-Ford table for s = 1 on the graph with edges (1, 2) of length 4, (1, 3) of length 2, (3, 2) of length −3, (2, 4) of length 1. There are four vertices, so the columns are j = 0, 1, 2, 3.
| v \ j | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| 1 | ||||
| 2 | ||||
| 3 | ||||
| 4 |
Answer
Column 0: [0, ∞, ∞, ∞]; column 1: [0, 4, 2, ∞]; column 2: [0, −1, 2, 5] (d[2] = min(4, 2 − 3), d[4] = 4 + 1); column 3: [0, −1, 2, 0] (d[4] = min(5, −1 + 1)). So d = [0, −1, 2, 0].Check-in 7.3. Same graph as Check-in 7.2. Run Bellman-Ford-2, relaxing the edges in each round in the order (1, 2), (1, 3), (3, 2), (2, 4). What is d after round 1, and is it equal to column 1 of the table?
Answer
After round 1, d = [0, −1, 2, 0]: (1, 2) sets d[2] = 4, (1, 3) sets d[3] = 2, (3, 2) lowers d[2] to −1, and (2, 4) uses the new value to set d[4] = 0. Column 1 is [0, 4, 2, ∞], so they are not equal; Bellman-Ford-2 has already reached the final answer after one round.7.4 Dijkstra's algorithm
In plain words. When no edge is negative, the closest unfinished vertex can never be improved later, because any other route to it would have to pass through a vertex that is at least as far away and then add a nonnegative amount. Dijkstra's algorithm therefore grows a set of finished vertices outward from the source, one at a time, always finishing the unfinished vertex with the smallest current estimate and then relaxing the edges leaving it. It looks like Prim's algorithm, but it compares total distances from the source, not single edge weights. With a plain array it runs in O(n²) time, and with a heap in O(m log n).
- Input: a directed graph with all lengths ℓ(e) ≥ 0 and a source s. Output: the distance array d.
- Repeat n times: pick the vertex u outside S with the smallest d[u], add it to S, and relax every edge leaving u.
- Invariant (proved by induction): when u is added to S, d[u] equals the distance δ(u), and it never changes afterwards.
- The proof uses ℓ(e) ≥ 0; with a negative edge Dijkstra can finalize a wrong value.
- Running time O(n²) with arrays (the course's version); O(m log n) with a heap-based priority queue.
- It is not Prim's algorithm: Prim picks the lightest edge leaving S, Dijkstra picks the smallest total distance d[x] + ℓ(x, u).
- Ties: break in favor of the smallest label (the exam's convention).
Problem
Problem (course notes §5.3). "SSSP, where all edge lengths are non-negative. Describe an O(n²)-time algorithm for this problem, prove that it's correct, and analyze its running time." A tiny instance (Homework 5, Question 4): edges (1, 2) of length 3, (1, 3) of length 5, (2, 3) of length 1, s = 1; the answer is d = [0, 3, 4].
Algorithm
The notes describe it in one paragraph: "Initialize S = ∅ and d[s] = 0. While |S| < n, find the vertex u ∈ V ∖ S with the smallest d-value, add it to S, and process it by relaxing every edge leaving u. Once every vertex has been added to S, return d." The lecture introduced it as "≈ Prim's" and the notes as "closely related to both BFS (Section 2.1) and Prim's algorithm (Section 3.1)": like BFS it reaches vertices in order of distance, and like Prim it grows one set S by repeatedly adding the "closest" outside vertex.
Dijkstra(G, s):
d = [inf]*n; d[s] = 0; S = empty set
while |S| < n:
u = vertex in V\S that minimizes d[u]
add u to S # d[u] is now final
for v in G[u]: # relax every edge leaving u
d[v] = min(d[v], d[u] + l(u,v))
return d
The lecture's example (October 22), with s = 1:
| Step | Chosen u (d[u]) | S after the step | Relaxations | d = [d[1], …, d[5]] |
|---|---|---|---|---|
| 0 | ∅ | initialization | [0, ∞, ∞, ∞, ∞] | |
| 1 | 1 (0) | {1} | d[2] = 0 + 3 = 3; d[4] = 0 + 10 = 10 | [0, 3, ∞, 10, ∞] |
| 2 | 2 (3) | {1, 2} | d[3] = 3 + 1 = 4; d[4] = min(10, 3 + 4) = 7 | [0, 3, 4, 7, ∞] |
| 3 | 3 (4) | {1, 2, 3} | d[4] = min(7, 4 + 2) = 6; d[5] = 4 + 3 = 7 | [0, 3, 4, 6, 7] |
| 4 | 4 (6) | {1, 2, 3, 4} | d[5] = min(7, 6 + 1) = 7 | [0, 3, 4, 6, 7] |
| 5 | 5 (7) | V | no edges leave 5 | [0, 3, 4, 6, 7] |
Some cells worked out: d[4] is improved twice before vertex 4 is chosen, from 10 (the direct edge) to 7 (through 2) to 6 (through 2 and 3), exactly the crossed-out "10, 7, 6" in the lecture's drawing; once 4 is chosen, its value is final. At step 4 the tie for d[5] (7 from 3, and 6 + 1 = 7 from 4) changes nothing. The vertices enter S in the order 1, 2, 3, 4, 5, and the answer is d = [0, 3, 4, 6, 7]. The green edges below are the last edges of the shortest paths:
Correctness
The notes call the algorithm "greedy in the sense that once a vertex u has the smallest d-value, we immediately 'finalize' its value d[u]," and also "a DP in some sense, since it (along with DAG-DP and Bellman-Ford) relies on edge relaxations." The official proof is an induction on the order in which vertices enter S. Learn it in this form; it is short enough to reproduce on the exam.
- Base case. The first vertex added is u = s, and d[s] = 0 = δ(s).
- Setup. Suppose the algorithm is about to add a vertex u ≠ s to S. Let P be the s→u path found by the algorithm (its length is d[u]) and let P* be any s→u path.
- P* leaves S. P* starts at s ∈ S and ends at u ∉ S, so it leaves S through some edge (x, y) with x ∈ S and y ∉ S.
- Greedy choice. u has the smallest d-value outside S, and (x, y) was relaxed when x was added, so d[u] ≤ d[y] ≤ d[x] + ℓ(x, y).
- Induction and nonnegativity. By induction d[x] = δ(x), and since all edge lengths are nonnegative, the rest of P* after y has length ≥ 0, so δ(x) + ℓ(x, y) ≤ ℓ(P*).
- Conclusion. d[u] ≤ ℓ(P*) for every s→u path P*, and d[u] is the length of an actual path, so d[u] = δ(u). ∎
Running time
With arrays (the course's version). "The algorithm makes O(n) iterations. In each iteration, it takes O(n) time to find the vertex u ∈ V ∖ S that minimizes d[u], and O(out-deg(u)) = O(n) time to process u. Thus, the total running time is O(n²)." The lecture's note: "S can be implemented by a binary array," so "add u to S" is S[u] = 1.
With a heap (Worksheet for Day 2, Problem 3). A heap is a priority queue in which the minimum sits at the top. In the lecture's words, with a heap "finding and removing the minimum takes O(log n) (instead of O(n))" and "changing a d-value takes O(log n) (instead of O(1))." Dijkstra finds the minimum n times and changes a d-value at most m times (once per relaxation), so the official answer is n · O(log n) + m · O(log n) = O(m log n). The notes mention, as a tangent the lecture marked "[CLRS]", that a Fibonacci heap gives O(m + n log n); that is not examinable.
Why negative lengths break it
Step 5 of the proof is the only place that uses ℓ(e) ≥ 0, and it really is needed. The lecture's example (October 27) is the three edges (1, 2) of length 5, (1, 3) of length 10 and (3, 2) of length −7, with s = 1: Dijkstra adds vertex 2 to S with d[2] = 5, declaring it final, but the path 1 → 3 → 2 has length 3. This guide adds one more edge, (2, 4) of length 1, to show that the mistake reaches the output:
| Step | Chosen u (d[u]) | Relaxations | d = [d[1], d[2], d[3], d[4]] |
|---|---|---|---|
| 1 | 1 (0) | d[2] = 5; d[3] = 10 | [0, 5, 10, ∞] |
| 2 | 2 (5) | d[4] = 5 + 1 = 6 | [0, 5, 10, 6] |
| 3 | 4 (6) | no edges leave 4 | [0, 5, 10, 6] |
| 4 | 3 (10) | d[2] = min(5, 10 − 7) = 3 | [0, 3, 10, 6] |
The algorithm returns d[4] = 6, but the distance is 4 (along 1 → 3 → 2 → 4). The late relaxation of (3, 2) does lower d[2], because the pseudocode relaxes every edge leaving u whether or not its head is in S, but vertex 4 was finished using the old value and is never revisited. Problem Set 5, Problem 2 (Section 7.7) shows how to cope with a single negative edge.
Why not Prim's algorithm? (Worksheet for Day 2, Problem 2)
"To find shortest paths in an undirected graph from a source s, can we run Prim's?" Official answer: "No; for example, consider an undirected cycle with (1, 2, 3, 4, 1), where s = 1 and all edge lengths are 1 except ℓ(1, 4) = 2. Then Prim's would return the path (1, 2, 3, 4), suggesting that the distance from 1 to 4 is 3, but the actual distance is 2 (by taking the direct edge)."
Prim's rule compares single edges leaving the tree; Dijkstra's compares d[x] + ℓ(x, u), the total distance from the source. In the picture, when S = {1, 2, 3}, Prim takes the edge {3, 4} of weight 1, while Dijkstra compares d[1] + 2 = 2 with d[3] + 1 = 3 and reaches 4 by the direct edge.
Check-in 7.4. Run Dijkstra from s = 1 on the graph with edges (1, 2) of length 5, (1, 3) of length 1, (3, 2) of length 2, (2, 4) of length 1, (3, 4) of length 6. Fill in one row per step: the vertex chosen and d after its edges are relaxed.
| Chosen vertex | d = [d[1], d[2], d[3], d[4]] | |
|---|---|---|
| Step 1 | ||
| Step 2 | ||
| Step 3 | ||
| Step 4 |
Answer
Step 1: vertex 1, d = [0, 5, 1, ∞]. Step 2: vertex 3, d = [0, 3, 1, 7]. Step 3: vertex 2, d = [0, 3, 1, 4]. Step 4: vertex 4, d unchanged. Order 1, 3, 2, 4; d = [0, 3, 1, 4].Check-in 7.5. Cover the blue proof box and write the induction proof of Dijkstra's correctness in four sentences. Then name the step that fails when an edge is negative.
Answer
Base case: s is added first with d[s] = 0 = δ(s). When u ≠ s is about to be added, any s→u path P* leaves S through an edge (x, y) with x ∈ S, y ∉ S; since u has the smallest d outside S, d[u] ≤ d[y] ≤ d[x] + ℓ(x, y). By induction d[x] = δ(x), and because lengths are nonnegative δ(x) + ℓ(x, y) ≤ ℓ(P*). So d[u] ≤ ℓ(P*) for every P*, hence d[u] = δ(u). The step δ(x) + ℓ(x, y) ≤ ℓ(P*) fails with a negative edge, since the rest of P* after y could have negative length.7.5 Floyd-Warshall: all pairs
In plain words. Now we want the distance between every pair of vertices at once, as an n × n table. Floyd-Warshall builds that table in rounds: first allowing no vertex in the middle of a route, then allowing only vertex 1, then vertices 1 and 2, and so on until every vertex is allowed. In the round that adds vertex r, a route either avoids r, and is already known, or goes through r once, and is "best route to r" plus "best route from r," both known from the previous round. Each of the n² entries is updated n times in constant time, for O(n³) in total.
- Input: a directed graph with lengths (negative allowed) and no negative cycle. Output: an n × n array d with d[u][v] = the distance from u to v.
- Subproblems: OPT[u][v][r] = the shortest u→v walk using only vertices 1, …, r as intermediate vertices, for r = 0, 1, …, n; return table r = n.
- Base table r = 0: 0 on the diagonal, ℓ(u, v) for each edge, ∞ elsewhere.
- Recurrence: OPT[u][v][r] = min(OPT[u][v][r − 1], OPT[u][r][r − 1] + OPT[r][v][r − 1]).
- The no-negative-cycle assumption is what lets the walk through r visit r only once.
- Running time O(n³): (n + 1) · n² subproblems, O(1) each.
- Compare: Bellman-Ford "reduces the number of edges we can use; Floyd-Warshall reduces the set of vertices we can use."
Problem
Problem (course notes §5.4, All-Pairs Shortest Path). "The input is a directed graph G with edge lengths ℓ and no negative cycle. Our goal is to return an n × n array d, where for all u, v ∈ V, d[u][v] is the distance from u to v. Describe an O(n³)-time algorithm for this problem, explain why it's correct, and analyze its running time." A tiny instance: edges (1, 2) of length 2 and (2, 1) of length −1; the answer is d = [[0, 2], [−1, 0]].
The lecture (October 27) built up to it in three ideas. Idea 1: run Bellman-Ford from every vertex, n · O(mn) = O(mn²), which "could be O(n⁴)." Idea 2: use Bellman-Ford's logic with the source as an extra index, OPT[u][v][j] = the distance from u to v using at most j edges; that is the Day 3 worksheet's Problem 1 (below) and also costs O(mn²). Idea 3 is Floyd-Warshall, which shrinks the set of allowed intermediate vertices instead of the number of edges.
Subproblems
Recurrence
OPT[u][v][r] = min( OPT[u][v][r−1], OPT[u][r][r−1] + OPT[r][v][r−1] ).
"The walk corresponding to OPT[u][v][r] either contains r as an intermediate vertex or doesn't. If it doesn't, then the walk exists as if vertex r were not allowed as an intermediate vertex. Otherwise, it can be split into a u-r walk plus an r-v walk. (Since G has no negative cycle, neither of these two sub-walks contains r as an intermediate vertex.)"Algorithm
"We can think of the DP 'table' as n + 1 tables, one per r ∈ {0, 1, …, n}, where table r is an n × n array containing the values of OPT[u][v][r]. Since table r only depends on values in table r − 1, the algorithm can compute the recurrence table by table, and within each table, the order of computation does not matter. At the end, we return table n." Table 0 is read off the adjacency lists; then, for r = 1 up to n, every entry of table r is the old entry or the route through r, whichever is shorter.
Floyd-Warshall(G):
d = [inf]*(n * n * (n+1)) # d[u][v][r], r = 0..n
for u in V:
d[u][u][0] = 0
for v in G[u]:
d[u][v][0] = l(u,v)
for r = 1, ..., n:
for u in V:
for v in V:
d[u][v][r] = min(d[u][v][r-1],
d[u][r][r-1] + d[r][v][r-1])
return d[.][.][n]
The lecture's example has four vertices and the edges (2, 1) of length 2, (1, 4) of length 1, (4, 2) of length 5, (3, 2) of length −7 and (4, 3) of length 10:
Each block below is one table; row u, column v holds d[u][v]; entries that changed from the previous table are bold.
| u \ v | 1 | 2 | 3 | 4 | 1 | 2 | 3 | 4 | 1 | 2 | 3 | 4 | ||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| r = 0 | r = 1 | r = 2 | ||||||||||||
| 1 | 0 | ∞ | ∞ | 1 | 0 | ∞ | ∞ | 1 | 0 | ∞ | ∞ | 1 | ||
| 2 | 2 | 0 | ∞ | ∞ | 2 | 0 | ∞ | 3 | 2 | 0 | ∞ | 3 | ||
| 3 | ∞ | −7 | 0 | ∞ | ∞ | −7 | 0 | ∞ | −5 | −7 | 0 | −4 | ||
| 4 | ∞ | 5 | 10 | 0 | ∞ | 5 | 10 | 0 | 7 | 5 | 10 | 0 | ||
| u \ v | 1 | 2 | 3 | 4 | 1 | 2 | 3 | 4 | |
|---|---|---|---|---|---|---|---|---|---|
| r = 3 | r = 4 (returned) | ||||||||
| 1 | 0 | ∞ | ∞ | 1 | 0 | 4 | 11 | 1 | |
| 2 | 2 | 0 | ∞ | 3 | 2 | 0 | 13 | 3 | |
| 3 | −5 | −7 | 0 | −4 | −5 | −7 | 0 | −4 | |
| 4 | 5 | 3 | 10 | 0 | 5 | 3 | 10 | 0 | |
Some cells worked out. r = 1: only row 1 and column 1 of table 0 matter; the only finite pair is d[2][1] + d[1][4] = 2 + 1 = 3 < ∞, so d[2][4] = 3 (the lecture's green "3", route 2 → 1 → 4). r = 2: column 2 has finite entries in rows 3 and 4, row 2 has finite entries in columns 1 and 4; so d[3][1] = −7 + 2 = −5, d[3][4] = −7 + 3 = −4 and d[4][1] = 5 + 2 = 7. r = 3: column 3 is finite only in row 4 (10), so row 4 is compared with 10 + row 3: d[4][1] = min(7, 10 − 5) = 5 and d[4][2] = min(5, 10 − 7) = 3 (the lecture's "3", route 4 → 3 → 2). r = 4: column 4 is finite in rows 1, 2, 3, so those rows are compared with d[·][4] + row 4: d[1][2] = 1 + 3 = 4, d[1][3] = 1 + 10 = 11, d[2][3] = 3 + 10 = 13. Table 4 is the answer; for example the distance from 1 to 3 is 11, along 1 → 4 → 3.
Correctness
Exhaustive cases on the vertex r, exactly as the notes say. A shortest u→v walk with intermediate vertices in {1, …, r} either does not use r in the middle, and then it is a walk with intermediates in {1, …, r − 1}, of length OPT[u][v][r − 1]; or it does, and then it splits at r into a u→r walk and an r→v walk. Because there is no negative cycle, we may assume r appears only once (cutting out the closed walk between two visits of r never makes the walk longer), so each piece uses only {1, …, r − 1} in its middle and costs at least OPT[u][r][r − 1] and OPT[r][v][r − 1] respectively. Conversely both terms of the minimum are lengths of actual walks of the allowed kind. Tables are filled in increasing r, and table r reads only table r − 1, so every value read is finished. Table n allows every vertex, so it holds the true distances.
Running time
"There are O(n³) subproblems, and we solve each one in O(1) time, so the total running time is O(n³)." Precisely, (n + 1) tables of n² entries. Idea 1 costs O(mn²), which is worse than O(n³) for dense graphs where m is close to n².
Variant: walks with at most j edges (Worksheet for Day 3, Problem 1)
"Let OPT[u][v][j] denote the length of the shortest u-v walk that uses at most j edges. Write a recurrence for OPT[u][v][j]." Official answer, "very similar to the recurrence for Bellman-Ford": if j = 0, OPT[u][v][0] is 0 if u = v and ∞ otherwise; for j ≥ 1,
OPT[u][v][j] = min( OPT[u][v][j−1], minw: (w, v) ∈ E OPT[u][w][j−1] + ℓ(w, v) ).
The walk uses at most j − 1 edges or ends with an edge (w, v) from some in-neighbor w. The lecture counted O(mn) per table and n tables, O(mn²) in total, which is why Floyd-Warshall's different third index is better.
Check-in 7.6. Three vertices with edges (1, 2) of length 2, (2, 3) of length 3, and (3, 1) of length −4. Table 0 is given. Fill in table 1 (vertex 1 allowed as an intermediate), then write the final value d[2][1].
| r = 0 | 1 | 2 | 3 |
|---|---|---|---|
| 1 | 0 | 2 | ∞ |
| 2 | ∞ | 0 | 3 |
| 3 | −4 | ∞ | 0 |
| r = 1 | 1 | 2 | 3 |
|---|---|---|---|
| 1 | |||
| 2 | |||
| 3 |
Answer
Table 1: row 1 [0, 2, ∞], row 2 [∞, 0, 3], row 3 [−4, −2, 0] (only d[3][2] changes, along 3 → 1 → 2). Table 2 adds d[1][3] = 2 + 3 = 5; table 3 adds d[2][1] = 3 − 4 = −1. Final d[2][1] = −1.7.6 Which shortest-path algorithm when
In plain words. The five shortest-path algorithms of this chapter differ in what they demand of the graph and in what they return. To pick one, ask about the graph rather than the story: are all lengths equal, is the graph a DAG, are all lengths nonnegative, is there a negative cycle, and do we need one source or every pair? The first question that gets a yes selects the cheapest algorithm that works. Problems that add a parity condition, a budget on edges or one free edge are solved by building a bigger graph and running one of the same algorithms on it.
- BFS needs all lengths equal and positive and runs in O(m + n) from one source.
- DAG-DP needs a DAG but allows negative lengths, also gives longest and widest paths, and runs in O(m + n).
- Dijkstra needs all lengths ≥ 0 and runs in O(n²) with arrays or O(m log n) with a heap.
- Bellman-Ford allows negative lengths as long as there is no negative cycle and runs in O(mn); column k of its table is "at most k edges".
- Floyd-Warshall gives all pairs in O(n³) when there is no negative cycle.
- Decision order: equal lengths → BFS; a DAG → DAG-DP; nonnegative lengths → Dijkstra; otherwise Bellman-Ford; all pairs → Floyd-Warshall.
- Two copies of the graph (or a table indexed by edge count or cost) handle parity, "at most k edges" and "one free edge" without a new algorithm.
A design problem often reduces to "model this as a shortest-path problem and call the right algorithm," and a short-answer question can ask which algorithm applies. The deciding questions are about the graph, not the story: does it have cycles, can lengths be negative, is there a limit on the number of edges, and do we need one source or all pairs. The running times are the ones the course notes state.
| Algorithm (notes) | Requirement on the input | Output | Running time | Technique |
|---|---|---|---|---|
| BFS (§2.1) | all lengths equal and positive | d from s | O(m + n) | search |
| DAG-DP (§5.1) | a DAG; any lengths, negative allowed | d from s (also longest, widest) | O(m + n) | DP over topological order |
| Bellman-Ford (§5.2) | any directed graph with no negative cycle | d from s; column k = at most k edges | O(mn); O(mk) for k columns | DP on (vertex, number of edges) |
| Dijkstra (§5.3) | all lengths ≥ 0 | d from s | O(n²) with arrays; O(m log n) with a heap | greedy |
| Floyd-Warshall (§5.4) | no negative cycle | all-pairs table d[u][v] | O(n³) | DP on (u, v, allowed vertices) |
Check in this order: equal lengths → BFS; a DAG → DAG-DP (it even allows negative lengths and does longest paths); all lengths nonnegative → Dijkstra; otherwise, with no negative cycle → Bellman-Ford; every pair of vertices, or anything about cycles → Floyd-Warshall. An undirected graph with nonnegative lengths is handled by replacing each edge {u, v} with the two directed edges (u, v) and (v, u). Four modelling tricks recur in the problem sets and exams: "at most k edges" is column k of the Bellman-Ford table (Practice Final, Problem 5); "a budget on a positive integer cost" is a Bellman-Ford table indexed by cost (Day 3 worksheet); "one negative edge" is two runs of Dijkstra with the edge removed (PS 5.2); and a small amount of extra state ("an even number of edges," "one free edge") is Dijkstra on a graph with a copy of every vertex per state (PS 5.3, Midterm 2 Problem 5).
Check-in 7.7. Name the algorithm you would call, and its running time: (a) driving distances on a road map from one city; (b) the longest chain of prerequisite courses, each with a duration; (c) a directed graph whose lengths may be negative but which has no negative cycle, from one source; (d) a maze in which every step costs 1; (e) the distance between every pair of airports, with some negative fares but no negative cycle.
Answer
(a) Dijkstra, O(n²) (or O(m log n) with a heap). (b) DAG-DP with max, O(m + n). (c) Bellman-Ford, O(mn). (d) BFS, O(m + n). (e) Floyd-Warshall, O(n³).7.7 Worked problems from Problem Set 5
The final exam reuses at least two problem-set problems word for word, and Midterm 2 and the Practice Midterm 2 already reused Problems 5.4 and 5.2. The four problems of Problem Set 5 are stated below exactly as on the course page, followed by the Day 3 worksheet's design problem, which the lecture worked on the board. Each solution follows the official one, expanded, in the answer recipe of Chapter 1. Attempt each on paper before opening it.
PS 5.1. Widest paths in a DAG
Solution
The official solution notes that it "is similar to DAG DP from Section 5.1, just with a different recurrence." It was also Problem 2 of the Day 1 worksheet, where the lecture called the minimum edge width the "bottleneck."
Subproblems. For every vertex v, let OPT[v] denote the width of the widest path from s to v. We return the whole array.
Recurrence. The base case is OPT[s] = ∞: "this makes the recurrence work, but we can also think of this as saying that the path from s to itself is not constrained by any edge width." For all v ∈ V ∖ {s},
OPT[v] = maxu: (u, v) ∈ E min( OPT[u], w(u, v) ).
Algorithm. Sort the vertices in topological order, build GR, and fill d in that order, initializing every entry to −∞ (meaning "no path yet") except d[s] = ∞.
ALG(G, s):
d = [-inf]*n; d[s] = inf
sort V in topological order
G^R = reverse of G
for v in V:
for u in G^R[v]:
d[v] = max(d[v], min(d[u], w(u,v)))
return d
Correctness. "Every path P to v must arrive from some in-neighbor u, and the minimum edge width in P is either obtained by an edge in P before u, or it is w(u, v)." So the widest path through the last edge (u, v) has width min(OPT[u], w(u, v)), and the widest path overall is the best of these over all in-neighbors u, which is the recurrence (exhaustive cases on the last edge). Topological order guarantees that every d[u] is final when v is processed. Vertices unreachable from s keep −∞.
Running time. "Calculating d[v] takes O(in-deg(v)) time, so the total running time is O(m + n)," including the O(m + n) topological sort and construction of GR.
On the DAG below (s = 1, processed in the order 1, 3, 2, 4, 5, 6), the widths are d = [∞, 4, 2, 3, 2, 2]; for example d[2] = max(min(∞, 4), min(2, 1)) = 4 and d[4] = max(min(4, 3), min(2, 5)) = 3.
Pattern: DAG DP with "+" replaced by "min" and "min" replaced by "max"; only the base case OPT[s] = ∞ needs thought.
PS 5.2. One negative edge
Solution
Also the Day 3 worksheet's Problem 2 and the Practice Midterm 2's Problem 3. Bellman-Ford would be correct but takes O(mn), which can be O(n³); and Dijkstra cannot be run on G directly because of the negative edge (Section 7.4).
Algorithm. "Remove e = (u, v), run Dijkstra's twice (once from s, once from v), and combine the results":
ALG(G, e, s, t):
u, v = endpoints of e
G' = G with e removed
d's = Dijkstra(G', s) # distances from s, avoiding e
d'v = Dijkstra(G', v) # distances from v, avoiding e
return min(d's[t], d's[u] + l(e) + d'v[t])
Correctness. "The shortest s-t path P in G either uses e = (u, v) or it does not. If it does not, then P is preserved in G′," so its length is d′s[t]. "Otherwise, P consists of a path from s to u, the edge e = (u, v), and a path from v to t." A path uses e at most once, so the two pieces avoid e and are paths in G′; the shortest choices have lengths d′s[u] and d′v[t]. "The algorithm considers both options and returns the shorter of the two." Both Dijkstra calls are valid because every length in G′ is nonnegative.
Running time. "Removing one edge takes O(n) time, and Dijkstra's takes O(n²) time, so the total running time is O(n²)."
Pattern: split on whether the special edge is used; each case is a call to a named algorithm on a graph where it is valid.
PS 5.3. Shortest even walk
Solution
Algorithm. "The idea is that we construct a new graph G′, where a path in G′ represents an even walk in G": two copies u0 and u1 of every vertex, and every edge of G crossing from one copy to the other.
ALG(G, s, t):
G' = graph with no vertices or edges
for u in V(G):
add two vertices u0, u1 to G'
for (u,v) in E(G):
add edges (u0, v1) and (u1, v0) to G', each has length l(u,v)
d = Dijkstra(G', s0)
return d[t0]
Correctness. "We think of G′ as two copies of G: the '0' copy and the '1' copy. Edges in G′ alternate between the two copies, and we start at s0, so every s0-t0 path in G′ corresponds to an even s-t walk in G of the same length. Conversely, every even s-t walk in G corresponds to an s0-t0 path in G′ of the same length. So finding a shortest even s-t walk in G is equivalent to finding a shortest s0-t0 path in G′." Dijkstra applies because the lengths are nonnegative, and d[t0] = ∞ exactly when no even walk exists.
Running time. "Constructing G′ takes O(m + n) time, and Dijkstra's takes O(n²) time (since G′ has 2n vertices), so the total running time is O(n²)."
A picture. Think of a light switch that starts OFF at s and flips on every edge: u0 means "at u, switch OFF (even number of edges so far)" and u1 means "at u, switch ON (odd)." In the graph below the shortest s→t path is the single edge of length 2, which is odd; the shortest even walk is s → t → x → y → t of length 5, which visits t twice.
| Step | Edge crossed | Edges so far | Position in G′ | Distance |
|---|---|---|---|---|
| 0 | start | 0 | s0 | 0 |
| 1 | s → t (2) | 1 | t1 | 2 |
| 2 | t → x (1) | 2 | x0 | 3 |
| 3 | x → y (1) | 3 | y1 | 4 |
| 4 | y → t (1) | 4 | t0 | 5 |
The two visits to t are the two different vertices t1 and t0 of G′, so the repeated vertex needs no special care. Returning d[t1] = 2 instead would give the shortest odd walk.
Pattern: extra state (here, parity) becomes extra copies of every vertex; then call Dijkstra on the bigger graph.
PS 5.4. Shortest cycle
Solution
Reused word for word as Midterm 2, Problem 3.
Algorithm. "We run Floyd-Warshall to obtain d and return the smallest value of d[u][v] + d[v][u] over all pairs of vertices (u, v) such that u ≠ v":
ALG(G):
d = Floyd-Warshall(G)
ans = inf
for each vertex u:
for each vertex v not equal to u:
ans = min(ans, d[u][v] + d[v][u])
return ans
Correctness. "The idea is that any cycle C consists of a path from u to v plus a path from v to u, where u and v are any two distinct vertices in C. So finding the smallest d[u][v] + d[v][u] also finds the shortest cycle." Spelled out in both directions: every cycle through distinct vertices u and v has length at least d[u][v] + d[v][u], so the answer is at least the minimum; and d[u][v] + d[v][u] is the length of a closed walk through u and v, which (because no cycle is negative) contains a cycle of at most that length, so the minimum is achieved by a cycle. If G has no cycle, no two vertices reach each other both ways and every sum is ∞.
Running time. "The algorithm is Floyd-Warshall with an additional O(n²)-time check, so the total running time is O(n³) + O(n²) = O(n³)."
Alternative solution (official). "Run Floyd-Warshall but initialize every diagonal entry to d[u][u] = ∞, then return the smallest diagonal value. This is correct because a cycle can be thought of a path, with at least two edges, from some vertex u to itself."
Pattern: call Floyd-Warshall by name and read the answer off its table with an O(n²) scan.
Worksheet 3.3. Shortest walk within a cost budget
Solution
The official solution: "The algorithm is a combination of Bellman-Ford and the DP for 0/1 Knapsack."
Subproblems. "For every vertex v and j ∈ {0, 1, …, B}, let OPT[v][j] denote the length of the shortest s-v walk among all walks whose total cost is at most j." We return OPT[t][B].
Recurrence. "If j = 0, then OPT[v][j] is 0 if v = s and ∞ otherwise." For j ≥ 1,
OPT[v][j] = min( OPT[v][j−1], minu: (u, v) ∈ E, c(u, v) ≤ j OPT[u][j − c(u, v)] + ℓ(u, v) ).
Algorithm.
ALG(G, s, t, B):
d = [inf]*(n*(B+1)); d[s][0] = 0
for j = 1, ..., B:
for v = 1, ..., n:
d[v][j] = d[v][j-1]
for each in-neighbor u of v: # use G^R, as usual
if c(u,v) <= j:
d[v][j] = min(d[v][j], d[u][j-c(u,v)] + l(u,v))
return d[t][B]
Correctness. "The optimal walk has cost at most j − 1, or it consists of an s-u path whose cost is at most j − c(u, v) plus the edge (u, v)" (exhaustive cases on the last edge, as in Bellman-Ford). Every cost is a positive integer, so column j reads only columns with smaller index, which are finished. A negative cycle does no harm: a walk of total cost at most B has at most B edges, so the minimum is over finitely many walks.
Running time. There are B columns; filling one relaxes every edge once, O(m + n) = O(m) for a connected graph, so the total is O(mB).
Pattern: Bellman-Ford with the second index "number of edges" replaced by "total cost," the knapsack capacity.
7.8 Homework-style one-point questions
Homework 5 had one question type, asked about three algorithms: "What is the final value of d[v]?" for DAG-DP, Bellman-Ford and Dijkstra, with s = 1 and the graph given as adjacency lists. In the homework's format, G[u] is a list of pairs [v, ℓ] meaning an edge (u, v) of length ℓ. The three small instances are worked below with the accepted answers; the two large instances (30 vertices) are the same questions on graphs too big to trace by hand in reasonable time, so treat them as programming checks (the accepted answers were d[2] = 53, d[5] = 291, d[10] = −162, d[15] = −52 for the Bellman-Ford one and d[2] = 58, d[5] = 270, d[10] = 235 for the Dijkstra one).
DAG-DP (Homework 5, Question 1)
G = [[[2, 3], [3, 5], [4, 6]], [[3, 4]], [[4, −1]], []], s = 1. Decode the lists first: edges (1, 2) of length 3, (1, 3) of length 5, (1, 4) of length 6, (2, 3) of length 4, (3, 4) of length −1. The order 1, 2, 3, 4 is topological. Then d[2] = 3; d[3] = min(5, 3 + 4) = 5; d[4] = min(6, d[3] − 1) = min(6, 5 − 1) = 4. Accepted answers: d[2] = 3, d[3] = 5, d[4] = 4.
Bellman-Ford (Homework 5, Question 2)
G = [[[2, 4]], [[3, −2], [4, 3]], [[1, 1], [4, 3]], []], s = 1, no negative cycle. Edges: (1, 2) of length 4, (2, 3) of length −2, (2, 4) of length 3, (3, 1) of length 1, (3, 4) of length 3. The cycle 1 → 2 → 3 → 1 has length 4 − 2 + 1 = 3 > 0.
| v \ j | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| 1 | 0 | 0 | 0 | 0 |
| 2 | ∞ | 4 | 4 | 4 |
| 3 | ∞ | ∞ | 2 | 2 |
| 4 | ∞ | ∞ | 7 | 5 |
Column 2: d[3] = 4 − 2 = 2 and d[4] = 4 + 3 = 7. Column 3: d[4] = min(7, d[3] + 3) = 5. Accepted answers: d[2] = 4, d[3] = 2, d[4] = 5. On a small graph you can also find the shortest paths by inspection (1 → 2 → 3 → 4 has length 5); the table is the safe method.
Dijkstra (Homework 5, Question 4)
G = [[[2, 3], [3, 5]], [[3, 1]], []], s = 1. Edges (1, 2) of length 3, (1, 3) of length 5, (2, 3) of length 1. Step 1 chooses 1: d = [0, 3, 5]. Step 2 chooses 2 (3): d[3] = min(5, 3 + 1) = 4. Step 3 chooses 3. Accepted answers: d[2] = 3, d[3] = 4.
7.9 Past exam problems on this chapter
Both course Chapter 4–5 exams opened with a Dijkstra trace and a Bellman-Ford trace on the same drawn graph, and each had shortest-path design problems; the Practice Final's Problem 5 is the only shortest-path problem on the Practice Final. All are stated as on the exams, with the official solutions expanded.
Midterm 2, Problem 1(a) and 1(b)
Solution
[0, 4, 7, 2, 7]. With all lengths positive: choose 1, d = [0, 4, ∞, 2, ∞]; choose 4 (2): d[3] = 2 + 8 = 10, d[5] = 2 + 5 = 7; choose 2 (4): d[3] = min(10, 4 + 3) = 7, d[4] stays 2 (4 + 3 = 7 is worse); choose 3 (7, smaller label than 5 on the tie): d[5] = min(7, 7 + 4) = 7; choose 5.Solution
[0, 4, 7, 1, 3]. The columns are [0, ∞, ∞, ∞, ∞], [0, 4, ∞, 2, ∞], [0, 4, 7, 1, 7], [0, 4, 7, 1, 3], [0, 4, 7, 1, 3]. The shortest paths: 1 → 2 (4); 1 → 2 → 3 (7); 1 → 2 → 4 (4 − 3 = 1, better than the direct 2); 1 → 2 → 3 → 5 (7 − 4 = 3, better than 1 + 5 = 6).Midterm 2, Problem 3 (identical to PS 5.4)
Solution
The official solution: "This is Problem 5.4 from Problem Set 5." In brief:
Algorithm. d = Floyd-Warshall(G); return the minimum of d[u][v] + d[v][u] over all pairs u ≠ v (∞ if every sum is ∞).
Correctness. Any cycle C through two distinct vertices u and v consists of a u→v path and a v→u path, so its length is at least d[u][v] + d[v][u]; conversely, that sum is the length of a closed walk which, with no negative cycle, contains a cycle no longer than it. So the minimum is the shortest cycle length.
Running time. O(n³) for Floyd-Warshall plus O(n²) for the scan: O(n³).
Midterm 2, Problem 5. One free edge
Solution
Algorithm. "Create a graph G′ with two copies of G (representing whether we've used a free edge or not), with a length-0 version of each edge (u, v) added (from u in the first copy to v in the second). Then run Dijkstra's from s in the first copy to t in the second copy":
ALG(G, s, t):
G' = two disjoint copies of G
# each vertex u in G has two copies u0 and u1 in G'
for each edge (u,v) in G:
add edge (u0, v1) to G' with length 0
d = Dijkstra(G', s0)
return d[t1]
Correctness. "We think of G′ as having a '0' layer (free edge not used) and a '1' layer (free edge used). Each edge that crosses from the 0 layer to the 1 layer represents a free version of that edge, so a path in G′ from s0 to t1 corresponds to a path in G that uses exactly one free edge." Conversely every s→t path in G with one edge made free is an s0→t1 path in G′ of the same length (stay in layer 0 until the free edge, cross on its 0-length copy, finish in layer 1). Making an edge free can only help, so using exactly one is never worse than using none. All lengths in G′ are ≥ 0, so Dijkstra is correct on it.
Running time. "Constructing G′ takes O(m + n) time, and running Dijkstra's on a graph with 2n vertices and 3m = O(n²) edges takes O(n²) time. Thus, the total running time is O(n²)."
Alternative solution (official). "Let ds = Dijkstra(G, s) and dt = Dijkstra(GR, t), where GR is the reverse of G. Then for each edge (u, v) in G, calculate ds[u] + dt[v]; track and return the minimum value." Distances from t in GR are distances to t in G, so ds[u] + 0 + dt[v] is the best path whose free edge is (u, v).
The common mistake (at most 2 points). "Call Dijkstra to find the shortest s-t path P in G, then set the length of the heaviest edge in P to 0. This isn't correct because the optimal edge to set to 0 might not be in P." The official counterexample: vertices s, a, t with edges (s, a), (a, t), (s, t) of lengths 1, 1, 10. The shortest path s → a → t has length 2 and this approach returns 1, but making (s, t) free gives 0.
Pattern: the two-layer construction of PS 5.3 with the layer recording "free edge used," exactly as PS 5.3's layer records parity.
Practice Midterm 2, Problem 1(a) and 1(b)
Solution
[0, 2, 4, 6, 5]. With all lengths positive: choose 1, d = [0, 2, 6, ∞, ∞]; choose 2 (2): d[3] = min(6, 2 + 2) = 4, d[4] = 2 + 4 = 6; choose 3 (4): d[4] = min(6, 4 + 3) = 6, d[5] = 4 + 1 = 5; choose 5 (5); choose 4 (6): d[5] = min(5, 6 + 1) = 5.Solution
[0, 2, 0, −2, −3]. Columns: [0, ∞, ∞, ∞, ∞], [0, 2, 6, ∞, ∞], [0, 2, 0, −2, 7], [0, 2, 0, −2, −3], [0, 2, 0, −2, −3]. Shortest paths: 1 → 2 → 3 (2 − 2 = 0), 1 → 2 → 4 (2 − 4 = −2), 1 → 2 → 4 → 5 (−2 − 1 = −3).Practice Midterm 2, Problem 3 (identical to PS 5.2)
Solution
The official solution: "This is Problem 5.2 from Problem Set 5." In brief:
Algorithm. Let e = (u, v) and G′ = G with e removed; d′s = Dijkstra(G′, s), d′v = Dijkstra(G′, v); return min(d′s[t], d′s[u] + ℓ(e) + d′v[t]).
Correctness. The shortest s→t path either avoids e (found by the first call) or is a shortest s→u path, then e, then a shortest v→t path, both avoiding e; G′ has only nonnegative lengths, so Dijkstra is correct on it.
Running time. O(n) to remove e plus two O(n²) Dijkstra calls: O(n²).
Practice Midterm 2, Problem 5. Adding one edge to a Floyd-Warshall table
Solution
Algorithm. "Intuitively, we apply the logic behind Floyd-Warshall, except we replace 'vertex r' with 'edge e.'"
ALG(G, d, e, w):
d' = d
for u in V:
for v in V:
d'[u][v] = min(d'[u][v], d[u][a] + w + d[b][v])
return d'
Correctness. "The shortest u-v path P in G′ either uses e or it does not. If P does not use e, then P is the same as the shortest u-v path in G, so d′[u][v] = d[u][v]. Otherwise, P consists of a shortest u-a path (in G), followed by e, followed by a shortest b-v path (in G). Thus, its length is d[u][a] + w + d[b][v]." (A shortest path uses e at most once, so the two pieces are paths in G, whose distances d already holds.)
Running time. "Since d′ has n² entries and each takes O(1) time to compute, the total running time is O(n²)."
Pattern: exhaustive cases on whether the new edge is used, read off an existing distance table; the same split as PS 5.2.
Practice Final, Problem 5. At most 10 edges
Solution
Algorithm. "Bellman-Ford (the original version, not the space-saving one) solves the following subproblem for all v ∈ V and j ∈ {0, 1, …, n − 1}: OPT[v][j] is the length of the shortest s-v path that uses at most j edges. Thus, it suffices to run Bellman-Ford until j = 10, and return the d-values at that time":
ALG(G, s):
d = [inf]*(n * 11); d[s][0] = 0
# columns of d range from j = 0 to 10
G^R = reverse of G
for j = 1, ..., 10:
for v in V:
d[v][j] = d[v][j-1]
for u in G^R[v]:
d[v][j] = min(d[v][j], d[u][j-1] + l(u,v))
return d[.][10] # last column of d
Correctness. Column j of the table version is exactly "the shortest s→v walk with at most j edges" (Section 7.3: the walk has at most j − 1 edges, or ends with an edge (u, v) after a walk to u with at most j − 1 edges). So column 10 is the requested array, with ∞ exactly where no walk of at most 10 edges exists. The space-saving version would be wrong here, because after round j its d can already reflect walks with more than j edges (the Day 2 worksheet's point).
Running time. "The algorithm calculates 11 = O(1) columns of the DP table. Calculating each column takes O(m) time, so the total running time is O(m)." (Building GR is O(m + n) = O(m) under the usual connectivity assumption.)
Pattern: a limit on the number of edges is a truncated Bellman-Ford table; a constant number of columns makes it linear.
Before moving on
- I can state the DAG-DP recurrence, explain why topological order and GR are needed, and trace it.
- I can define OPT[v][j] for Bellman-Ford, fill its table column by column, and explain why n − 1 columns suffice and why Bellman-Ford-2 can run ahead.
- I can trace Dijkstra, reproduce its induction proof, and give a graph with a negative edge on which it fails.
- I can write the Floyd-Warshall subproblem and recurrence, say what the index r means, and compute table r from table r − 1.
- I can choose the right algorithm from the assumptions on the graph and quote its running time.
- I can reproduce the four Problem Set 5 solutions and the Practice Final's Problem 5 in the Algorithm · Correctness · Running time format.
Exercises
Solution
OPT[s] = 0, and for v ≠ s, OPT[v] = min over in-neighbors u of v of (OPT[u] + ℓ(u, v)), which is ∞ if v has no in-neighbor. Vertices are processed in topological order: every in-neighbor u of v precedes v in that order, so OPT[u] is final when OPT[v] is computed. The in-neighbors are read from GR, built in O(m + n); the topological sort is O(m + n); computing d[v] costs O(in-deg(v)) and the in-degrees sum to m. Total O(m + n).Solution
Order 1, 3, 2, 4, 5 (2 must follow 3 because of the edge (3, 2)). d[1] = 0; d[3] = 1; d[2] = min(0 + 3, 1 − 2) = −1; d[4] = min(−1 + 4, 1 + 7) = 3; d[5] = min(−1 + 2, 3 − 5) = −2. d = [0, −1, 1, 3, −2].Solution
Replace min by max and initialize d to −∞ with d[1] = 0. d[3] = 1, d[2] = max(3, 1 − 2) = 3, d[4] = max(3 + 4, 1 + 7) = 8, d[5] = max(3 + 2, 8 − 5) = 5, so d = [0, 3, 1, 8, 5]. On a graph with a positive cycle there is no topological order, and the Bellman-Ford-style version keeps growing values by going around the cycle, so the numbers correspond to walks, not paths (Day 1 worksheet, Problem 3).Solution
n = 4, columns j = 0, 1, 2, 3. Column 0: [0, ∞, ∞, ∞]. Column 1: [0, 6, 7, ∞]. Column 2: d[2] = min(6, 7 − 3) = 4, d[3] = 7, d[4] = min(∞, 6 − 1, 7 + 2) = 5, so [0, 4, 7, 5]. Column 3: d[4] = min(5, 4 − 1, 7 + 2) = 3, so [0, 4, 7, 3]. d = [0, 4, 7, 3].Solution
OPT[v][n − 1] is the shortest walk to v with at most n − 1 edges. With no negative cycle, cutting a cycle out of a walk never makes it longer, so some shortest walk to v repeats no vertex; a walk that repeats no vertex has at most n − 1 edges, so it is counted in column n − 1. With a reachable negative cycle there is no shortest walk at all (each lap around the cycle shortens it), so no column is "the distance"; the column values would keep decreasing if the table were extended.Solution
Start [0, ∞, ∞, ∞, ∞]. Choose 1: d[2] = 4, d[3] = 1. Choose 3 (1): d[2] = min(4, 1 + 2) = 3, d[4] = 1 + 8 = 9. Choose 2 (3): d[4] = min(9, 3 + 5) = 8, d[5] = 3 + 1 = 4. Choose 5 (4): no outgoing edges. Choose 4 (8). Order 1, 3, 2, 5, 4; d = [0, 3, 1, 8, 4].Solution
Dijkstra needs every edge length to be nonnegative, not just every cycle; the proof's step δ(x) + ℓ(x, y) ≤ ℓ(P*) assumes the rest of P* has nonnegative length. Counterexample (a DAG, so no cycles at all): edges (1, 2) of length 5, (1, 3) of length 10, (3, 2) of length −7, (2, 4) of length 1, s = 1. Dijkstra finishes 2 with d[2] = 5, then 4 with d[4] = 6, then 3; it returns d[4] = 6, but the distance is 10 − 7 + 1 = 4. For this graph Bellman-Ford or DAG-DP is the right call.Solution
r = 0: [0, 3, 5], [∞, 0, −1], [2, ∞, 0]. r = 1 (through 1): d[3][2] = 2 + 3 = 5, giving [0, 3, 5], [∞, 0, −1], [2, 5, 0]. r = 2 (through 2): d[1][3] = min(5, 3 − 1) = 2, giving [0, 3, 2], [∞, 0, −1], [2, 5, 0]. r = 3 (through 3): d[2][1] = −1 + 2 = 1, giving [0, 3, 2], [1, 0, −1], [2, 5, 0]. No negative cycle: 1 → 2 → 3 → 1 has length 4.Solution
Algorithm. Compute distances from s with Dijkstra, then close the cycle with an edge back into s.
ALG(G, s):
d = Dijkstra(G, s)
G^R = reverse of G
ans = inf
for u in G^R[s]: # every in-neighbor u of s
ans = min(ans, d[u] + l(u,s))
return ans
Correctness. A cycle through s leaves s, reaches some in-neighbor u of s, and returns along (u, s); its part from s to u is an s→u path of length at least d[u], so the cycle has length at least d[u] + ℓ(u, s) for that u, and the minimum over all in-neighbors is a lower bound. Conversely, a shortest s→u path followed by (u, s) is a closed walk through s of length d[u] + ℓ(u, s); Dijkstra's d[u] is the length of a shortest s→u path, which visits s only at its start, so adding (u, s) closes a cycle through s. So the minimum is achieved. If s has no in-neighbor reachable from s, every term is ∞.
Running time. Dijkstra O(n²), building GR O(m + n), and the scan O(n): O(n²) in total.
Solution
Algorithm. The PS 5.3 construction with three copies instead of two: copy i records the number of edges so far modulo 3.
ALG(G, s, t):
G' = graph with no vertices or edges
for u in V(G):
add three vertices u0, u1, u2 to G'
for (u,v) in E(G):
for i = 0, 1, 2:
add edge (ui, v((i+1) mod 3)) to G' with length l(u,v)
d = Dijkstra(G', s0)
return d[t0]
Correctness. Every edge of G′ moves from copy i to copy i + 1 (mod 3), and we start in copy 0, so a walk in G′ from s0 ends in copy k mod 3 after k edges. Hence s0→t0 walks in G′ correspond exactly to s→t walks in G whose number of edges is a multiple of 3, with the same length, and vice versa. All lengths are nonnegative, so Dijkstra finds the shortest one; d[t0] = ∞ if none exists.
Running time. G′ has 3n vertices and 3m edges and is built in O(m + n); Dijkstra on 3n vertices takes O((3n)²) = O(n²). Total O(n²).
Course Ch. 6 · Nov 5–128. Flows and cuts
The course notes open Chapter 6 with an analogy: "If the shortest path problem is about sending one truck from a location s to another location t, the maximum flow problem is about sending as many trucks as possible from s to t." The lecture of November 5 drew the same story with little trucks leaving a source and arriving at a sink, every road labelled with how many trucks it can carry. This chapter covers the whole of course Chapter 6: flow networks, flows and cuts (with the Flow-Cut Lemma), the Ford-Fulkerson algorithm (notes Section 6.1), minimum cuts and the Max-Flow Min-Cut Theorem (6.2), and the two applications the notes give, bipartite matching (6.3) and bipartite vertex cover (6.4). It then works every problem of Problem Set 6 and the flow question of the Practice Final. Chapter 6 was taught after Midterm 2, so it has never been examined; the Practice Final opens with "What is the value of a maximum s-t flow in the instance above?", and the instructor's notes promise that at least two of Problems 3–8 on the final are identical to problem-set problems, so Problem Set 6 deserves the same care as every other problem set.
Everything in the chapter rests on one inequality and one trick. The inequality: no flow can be larger than any cut. The trick: when looking for more flow, also allow "undoing" flow that was sent earlier. Ford-Fulkerson combines them, and it finishes with a flow and a cut of the same size, which proves both are optimal. The applications then follow one format, which the notes call out explicitly: translate your problem into a flow network, solve the flow problem, and translate the answer back. A flow is maximum exactly when some cut is full: Ford-Fulkerson augments along paths in the residual graph until no path is left, and the vertices it can still reach form a cut whose capacity equals the flow.
8.1 Flow networks, flows and cuts
In plain words. A flow network is a road map with one-way roads, each with a limit on how much can travel along it per hour, plus a starting point and an ending point. A flow says how much actually travels along each road; it is allowed only if no road carries more than its limit and nothing piles up or appears from nowhere at the intermediate junctions. A cut draws a line around a group of junctions that contains the start but not the end, and its capacity is the total limit of the roads leaving the group. Whatever leaves the start must eventually cross that line, so no flow can be bigger than any cut; that fact is the Flow-Cut Lemma.
- Input: a flow network (G, s, t): a directed graph G whose every edge e has an integer capacity c(e) ≥ 1, a source s and a sink t. The notes assume no edges enter s, no edges leave t, and G is connected if directions are ignored.
- A flow f assigns a number f(e) to every edge. It is feasible if it satisfies the capacity constraints 0 ≤ f(e) ≤ c(e) and conservation fin(u) = fout(u) at every u other than s and t.
- The value of f is |f| = fout(s), the total flow leaving s (the lecture adds that this also equals fin(t)).
- An s-t cut is a set S of vertices with s ∈ S and t ∉ S. Its capacity c(S) is the sum of c(e) over edges e leaving S only.
- Flow-Cut Lemma: for every feasible f and every s-t cut S, |f| = fout(S) − fin(S) ≤ c(S).
- Consequence: if you ever find a flow and a cut with |f| = c(S), the flow is maximum and the cut is minimum.
- Classic trap: adding the capacities of edges that enter S when computing c(S). Entering edges never count toward capacity.
Problem
The notes state Maximum Flow as follows: the input is a flow network (G, s, t), and the goal is to return a maximum s-t flow, that is, a feasible flow whose value |f| is as large as possible. A flow is "one number per edge", as the lecture put it. The lecture's first tiny instance has three vertices: s = 1, t = 3, and edges 1 → 2 with capacity 5, 2 → 3 with capacity 4, and 1 → 3 with capacity 7. The best flow sends 4 along 1 → 2 → 3 (the edge 2 → 3 cannot take more) and 7 along 1 → 3, so the answer is f(1, 2) = 4, f(2, 3) = 4, f(1, 3) = 7 with value |f| = 11. The cut S = {1, 2} has capacity c(2, 3) + c(1, 3) = 4 + 7 = 11, so by the lemma below no flow can do better.
Definitions
- Flow network
- (G, s, t), where G is a directed graph, each edge e has capacity c(e), a positive integer, s is a source vertex, and t is a sink vertex.
- Cut
- A subset S of vertices; S is an s-t cut if s ∈ S and t ∉ S. δout(S) is the set of edges (u, v) with u ∈ S and v ∉ S, the edges leaving (or crossing) the cut, and δin(S) is the set of edges entering S.
- fout(S) and fin(S)
- The total flow on the edges leaving S, and on the edges entering S. For a single vertex the notes write fout(u) instead of fout({u}).
- Feasible flow
- A flow satisfying the capacity constraints (0 ≤ f(e) ≤ c(e) for all e ∈ E) and conservation (fin(u) = fout(u) for all u ∈ V \ {s, t}). The lecture says "f is conserved at u" for the second condition.
- Value, maximum flow
- |f| = fout(s); a maximum flow is a feasible flow maximizing |f|.
- Capacity of a cut, minimum cut
- c(S) = Σe ∈ δout(S) c(e); a minimum s-t cut is an s-t cut S minimizing c(S). The lecture's story for a cut: a competitor wants to block every s-t path, and blocking edge e costs c(e); c(S) is the cost of blocking the edges leaving S.
In the figures of this chapter an edge labelled with one number shows its capacity, and an edge labelled "f/c" shows its flow f and capacity c, which is how the lecture writes them ("4/4", "1/3", "2/8"). Here is the network from the first Chapter 6 worksheet, which is the main example of this chapter, with s = 1 and t = 5:
The Flow-Cut Lemma
Correctness
The notes' proof is a sum over the vertices of S. Write the net outflow of every vertex in S and add them up.
- For s, the net outflow fout(s) − fin(s) equals |f|, because no edges enter s, so fin(s) = 0.
- For every other u ∈ S, the net outflow fout(u) − fin(u) is 0 by conservation (u is neither s nor t, because t ∉ S).
- So |f| = Σu ∈ S (fout(u) − fin(u)). Expand each term into "flow on edges leaving u minus flow on edges entering u".
- Look at one edge e = (x, y). If both x and y are in S, f(e) is added once (as it leaves x) and subtracted once (as it enters y): it contributes nothing. If x ∈ S and y ∉ S, it is only added. If x ∉ S and y ∈ S, it is only subtracted. Edges with no endpoint in S never appear.
- Therefore |f| = fout(S) − fin(S). Finally fout(S) ≤ Σe ∈ δout(S) c(e) = c(S) by the capacity constraints, and fin(S) ≥ 0, so |f| ≤ c(S). ∎
The lemma says something useful in both directions. Read from left to right, it says the flow crossing any s-t cut (out minus in) is the same number, the value of the flow. Read as an inequality, it says every cut is an upper bound on every flow. That second reading is how the course proves that Ford-Fulkerson is optimal, that its cut is minimum, and that the reductions in Sections 8.4 and 8.5 are correct.
Running time
The Flow-Cut Lemma is a statement about flows and cuts, not an algorithm, so it has no running time of its own. Two checks that use it are cheap, though: deciding whether a given f is feasible takes one pass over the edges, O(m + n), and computing c(S) for a given S takes O(m + n) as well.
Check-in 8.1. The figure shows a proposed flow on the Practice Final network (s = 1, t = 4), written f/c. Is it feasible? If not, name the constraint that fails and the vertex or edge where it fails.
Answer
Every edge respects its capacity (5 ≤ 6, 2 ≤ 2, 2 ≤ 3, 3 ≤ 8, 1 ≤ 1), and vertex 2 is conserved (in 5, out 2 + 3 = 5). But vertex 3 receives 2 + 2 = 4 and sends only 1, so conservation fails at vertex 3 and the flow is not feasible.Check-in 8.2. In the main example (capacities in the figure above, s = 1, t = 5), compute c(S) for each cut, then say which one is smallest.
| S | {1} | {1, 2} | {1, 3} | {1, 2, 3} | {1, 2, 3, 4} |
|---|---|---|---|---|---|
| c(S) |
Answer
c({1}) = 3 + 12 = 15; c({1, 2}) = 12 + 8 + 1 = 21; c({1, 3}) = 3 + 3 + 5 = 11 (2 → 3 enters S and does not count); c({1, 2, 3}) = 1 + 3 + 5 = 9; c({1, 2, 3, 4}) = 5 + 15 = 20. The smallest is c({1, 2, 3}) = 9, so no flow in this network has value above 9.8.2 Ford-Fulkerson
In plain words. Ford-Fulkerson starts with no flow and keeps finding a route from s to t along which more flow can still be pushed, then pushes as much as that route allows. The twist is where it looks for routes: in the residual graph, which contains the leftover capacity of every edge and also, pointing backwards, the flow already sent on every edge, so that a later route may cancel an earlier decision. When no route remains, the flow is maximum. Each round raises the value by at least 1, so the number of rounds is at most the maximum flow value v.
- Input: a flow network (G, s, t) with positive integer capacities. Output: a maximum s-t flow f (stored, like an edge weight, as a third entry of each adjacency-list tuple (v, c, f)).
- The residual graph Gf has, for every edge e = (u, v) of G, a forward edge (u, v) with capacity c(e) − f(e) if f(e) < c(e), and a backward edge (v, u) with capacity f(e) if f(e) > 0. So m ≤ |E(Gf)| ≤ 2m.
- Each iteration: find an s-t path P in Gf (DFS), let ΔP be the smallest residual capacity on P, add ΔP to f on forward edges and subtract it on backward edges, rebuild Gf.
- The first edge of P leaves s and is always a forward edge, so |f| grows by ΔP ≥ 1 every iteration: at most v iterations.
- Running time O(mv), where v is the value of the maximum flow (assume v ≥ 1).
- Optimality: at the end, the set S* of vertices reachable from s in Gf is an s-t cut with c(S*) = |f|.
- Classic trap: searching for paths in G with reduced capacities (the plain greedy algorithm) instead of in Gf; without backward edges the algorithm gets stuck below the maximum.
Problem
From the notes, Section 6.1: "The input is a flow network (G, s, t), and our goal is to return a maximum s-t flow. Describe an O(mv)-time algorithm for this problem (where v is the value of the maximum flow), prove that it's correct, and analyze its running time. (We can assume v ≥ 1.)" On the main example the answer is a flow of value 9, computed below.
Why the plain greedy algorithm fails
The lecture's "Idea 1" is greedy: find an s-t path P in G with DFS, add the smallest capacity on P to f(e) for every e on P, subtract it from each c(e), delete edges whose capacity drops to 0, and repeat until no s-t path remains. Worksheet Day 1, Problem 1 asks you to show that this is not correct. The notes' answer uses the graph below with s = 1, t = 4 and every capacity equal to 1. DFS (smallest label first) finds 1 → 2 → 3 → 4 and sends one unit along it:
After that, the edges 1 → 2, 2 → 3 and 3 → 4 are used up, the remaining edges are 1 → 3 and 2 → 4, and there is no s-t path left. The greedy algorithm stops with value 1, in the notes' words it "gets stuck", but the maximum flow value is 2: send one unit along 1 → 2 → 4 and one along 1 → 3 → 4. The greedy flow is shown below in f/c form; nothing more can be pushed without first removing the unit on 2 → 3.
The fix, in the lecture's words: "Ford-Fulkerson: allow 'undo'". Instead of searching G, search the residual graph, which contains "leftover capacity" edges (as in greedy) and "undo" edges.
The residual graph
The lecture's picture: an edge u → v carrying 7 units out of a capacity of 10 becomes, in Gf, a forward edge u → v with capacity 3 (the leftover, 10 − 7) and a backward edge v → u with capacity 7 (the amount that could be undone). The notes give the construction as pseudocode:
Residual(G, f):
G_f = (V(G), E_f = empty set)
for e = (u,v) in E(G):
if f(e) < c(e):
# create a forward edge
add (u, v) to E_f with capacity c(e) - f(e)
if f(e) > 0:
# create a backward edge
add (v, u) to E_f with capacity f(e)
return G_f
"Intuitively, for any flow f, the 'forward' edges in Gf represent the 'leftover' capacity in G, and the 'backward' edges in Gf represent the amount of flow in f we can 'undo.'" A saturated edge (f(e) = c(e)) contributes only a backward edge; an empty edge (f(e) = 0) contributes only a forward edge; an edge in between contributes both. In the residual-graph figures below, backward edges are dashed.
Here is the residual graph of the greedy example after its first unit. The forward edges 1 → 3 and 2 → 4 still have capacity 1; the three used edges have become backward edges 2 → 1, 3 → 2 and 4 → 3. The highlighted path 1 → 3 → 2 → 4 uses the backward edge 3 → 2:
Augmenting along this path means: increase f(1, 3) by 1 (forward), decrease f(2, 3) by 1 (the backward edge 3 → 2 undoes flow on 2 → 3), and increase f(2, 4) by 1 (forward). The new flow has f(1, 2) = f(2, 4) = f(1, 3) = f(3, 4) = 1 and f(2, 3) = 0, value 2. In the new residual graph s = 1 has no outgoing edges at all, so the algorithm stops; the reachable set is {1}, a cut of capacity 2, equal to the flow. The lecture drew the same example with capacity 5 on 3 → 4; nothing changes except that a forward edge 3 → 4 of capacity 4 stays in the residual graph.
Algorithm
Ford-Fulkerson never modifies G. It keeps a flow f, starting at 0 on every edge, and repeats three steps. First, search for an s-t path P in the current residual graph Gf with DFS (or any path-finding algorithm). Second, compute the bottleneck ΔP, the minimum residual capacity over the edges of P. Third, "augment f along P": for every edge of P that is a forward edge (u, v), increase f(u, v) by ΔP; for every edge of P that is a backward edge (u, v), the corresponding edge of G is (v, u), so decrease f(v, u) by ΔP. Then rebuild Gf = Residual(G, f). When Gf has no s-t path, return f. The notes' pseudocode:
Ford-Fulkerson(G, s, t):
G_f = G; f(e) = 0 for all e in E(G)
while G_f has an s-t path P:
Delta_P = minimum c_f(e) over all e in P
for e = (u,v) in P:
if e is a forward edge:
f(u,v) += Delta_P
else:
f(v,u) -= Delta_P
G_f = Residual(G, f)
return f
The lecture also wrote a "concise" version that is worth memorizing as the one-line idea: while Gf has an s-t path P: augment f along P; update Gf.
A complete trace (Worksheet Day 1, Problem 2)
The worksheet asks: "In the example below, what is the residual graph at the end of Ford-Fulkerson?" The network is the main example (s = 1, t = 5). The lecture of November 5 ran the algorithm on it with DFS, ties broken toward the smallest label. Initially Gf = G. DFS from 1 goes to 2, then 3 (smaller than 4), then 4 (smaller than 5), then 5:
Iteration 1. P = 1 → 2 → 3 → 4 → 5, all forward. Residual capacities 3, 8, 3, 15, so ΔP = 3. The flow becomes f(1, 2) = f(2, 3) = f(3, 4) = f(4, 5) = 3 and |f| = 3. The new residual graph: 1 → 2 and 3 → 4 are saturated, so they appear only backwards (2 → 1 and 4 → 3, capacity 3); 2 → 3 splits into forward 5 and backward 3; 4 → 5 splits into forward 12 and backward 3; untouched edges are unchanged. The next DFS path is highlighted:
Iteration 2. From 1 the only edge is 1 → 3 (capacity 12). From 3, DFS tries 2 first, through the backward edge 3 → 2 (capacity 3); from 2 the edge 2 → 1 leads back to a visited vertex and 2 → 3 too, so DFS takes 2 → 4 (capacity 1), then 4 → 5 (capacity 12). So P = 1 → 3 → 2 → 4 → 5 with residual capacities 12, 3, 1, 12 and ΔP = 1. Augmenting: f(1, 3) rises to 1, f(2, 3) falls from 3 to 2 (backward edge), f(2, 4) rises to 1, f(4, 5) rises to 4. Now |f| = 4. In plain words: one of the units that went 2 → 3 is rerouted 2 → 4 → 5, and the unit entering 3 from 1 takes its place on 3 → 4.
Iteration 3. From 1: 1 → 3 (capacity 11). From 3: 3 → 1 is visited; 3 → 2 (capacity 2) leads to 2, whose edges 2 → 1 and 2 → 3 lead only to visited vertices, a dead end; so DFS backs up and takes 3 → 5 (capacity 5). P = 1 → 3 → 5, ΔP = min(11, 5) = 5. Now f(1, 3) = 6, f(3, 5) = 5, and |f| = 9.
Termination. The final residual graph is below, and it is exactly the notes' answer to the worksheet. From 1 one can reach 3 (forward edge, capacity 6) and from 3 one can reach 2 (backward edge 3 → 2), but every edge out of {1, 2, 3} toward 4 or 5 is gone: 2 → 4, 3 → 4 and 3 → 5 are saturated. There is no s-t path, so the algorithm returns f with value 9. The shaded vertices are the reachable set S = {1, 2, 3}, used in Section 8.3.
| Iteration | Path P in Gf | Edge types | Residual capacities on P | ΔP | |f| after |
|---|---|---|---|---|---|
| 1 | 1 → 2 → 3 → 4 → 5 | F F F F | 3, 8, 3, 15 | 3 | 3 |
| 2 | 1 → 3 → 2 → 4 → 5 | F B F F | 12, 3, 1, 12 | 1 | 4 |
| 3 | 1 → 3 → 5 | F F | 11, 5 | 5 | 9 |
| Edge of G | (1, 2) | (1, 3) | (2, 3) | (2, 4) | (3, 4) | (3, 5) | (4, 5) |
|---|---|---|---|---|---|---|---|
| c(e) | 3 | 12 | 8 | 1 | 3 | 5 | 15 |
| f after iteration 1 | 3 | 0 | 3 | 0 | 3 | 0 | 3 |
| f after iteration 2 | 3 | 1 | 2 | 1 | 3 | 0 | 4 |
| f after iteration 3 | 3 | 6 | 2 | 1 | 3 | 5 | 4 |
Some cells worked out: in iteration 2 the entry for (2, 3) goes down from 3 to 2 because P used the backward edge 3 → 2; this is the only way flow on an edge ever decreases. Conservation can be checked at the end: vertex 2 receives 3 and sends 2 + 1 = 3; vertex 3 receives 6 + 2 = 8 and sends 3 + 5 = 8; vertex 4 receives 1 + 3 = 4 and sends 4. The value is fout(1) = 3 + 6 = 9 = fin(5) = 5 + 4.
Reading the final flow off the final residual graph is mechanical, and the worksheet can be asked in either direction: a dashed (backward) edge v → u with capacity x means f(u, v) = x; a solid edge u → v with capacity y and no dashed partner means f(u, v) = 0 and c(u, v) = y.
Correctness
The notes prove two things: the algorithm stops, and what it returns is a maximum flow. (Feasibility of f, that every augmentation keeps capacities and conservation intact, is "relatively straightforward and tedious", so the notes omit it.)
Termination within v iterations. Any augmenting path P starts at s, so its first edge leaves s. No edge of G enters s, so Gf has no backward edges leaving s, and the first edge of P is a forward edge out of s. Augmenting increases f on that edge by ΔP, so |f| = fout(s) increases by ΔP. All capacities are integers, so every residual capacity and every ΔP is a positive integer, ΔP ≥ 1. The value starts at 0, grows by at least 1 per iteration, and can never exceed the maximum value v, so there are at most v iterations. (The same integrality means the final flow is integral on every edge, which Section 8.4 relies on.)
Optimality, via a cut (the Flow-Cut Lemma). By the Flow-Cut Lemma it suffices to find one s-t cut S* with |f| = c(S*): every flow is at most c(S*) = |f|. Let S* be the set of vertices reachable from s in the last Gf. It contains s, and it does not contain t because the loop stopped when there was no s-t path; so S* is an s-t cut.
- Every edge e = (u, v) of G leaving S* is saturated, f(e) = c(e). Otherwise Gf would contain the forward edge (u, v), and since u is reachable from s, v would be reachable too, contradicting v ∉ S*.
- Every edge e′ = (x, y) of G entering S* carries no flow, f(e′) = 0. Otherwise Gf would contain the backward edge (y, x) with y ∈ S*, making x reachable, contradicting x ∉ S*.
- By the lemma, |f| = fout(S*) − fin(S*) = Σe ∈ δout(S*) c(e) − 0 = c(S*). So f is a maximum flow. ∎
Running time
The correctness proof shows there are at most v iterations, v the value of the maximum flow. In each iteration, DFS on Gf takes O(n + |E(Gf)|) = O(m) time (Gf has at most 2m edges, and G is connected ignoring directions, so n ≤ m + 1), augmenting along P takes O(n), and rebuilding Gf with Residual takes O(m). So each iteration is O(m) and the total is O(mv). The lecture's summary: "|f| starts at 0, increases by ΔP ≥ 1 each iteration ⇒ # iterations ≤ v; O(m + n) = O(m) per iteration; total O(mv)."
Note what the bound depends on: v is a number in the input's capacities, not its size, so O(mv) is fast when capacities are small. That is why every application in this chapter first bounds v: in a matching network v ≤ n (Section 8.4), in a unit-capacity graph v ≤ n − 1 (PS 6.1, 6.2), in PS 6.4 v ≤ 2.
Check-in 8.3. The lecture of November 10 used the network below (s = 1, t = 4). After the first augmentation along 1 → 2 → 3 → 4 with Δ = 1, fill in, for each edge of G, its flow, the capacity of its forward edge in Gf and the capacity of its backward edge in Gf (write "none" if the edge is absent).
| Edge (c) | (1, 2) (1) | (1, 3) (3) | (2, 3) (2) | (2, 4) (1) | (3, 4) (2) |
|---|---|---|---|---|---|
| f(e) | |||||
| forward | |||||
| backward |
Answer
f = 1, 0, 1, 0, 1 for (1, 2), (1, 3), (2, 3), (2, 4), (3, 4). Forward capacities: none, 3, 1, 1, 1. Backward capacities: 1, none, 1, none, 1. So Gf has edges 1 → 3 (3), 2 → 3 (1), 2 → 4 (1), 3 → 4 (1) forward and 2 → 1 (1), 3 → 2 (1), 4 → 3 (1) backward.Check-in 8.4. Finish Ford-Fulkerson on the same network (DFS, ties toward the smallest label): list each augmenting path with its Δ, give the maximum flow value, and give the set S of vertices reachable from 1 in the final residual graph together with c(S).
Answer
Paths: 1 → 2 → 3 → 4 (Δ = 1); 1 → 3 → 2 → 4 (Δ = 1, using the backward edge 3 → 2, which resets f(2, 3) to 0); 1 → 3 → 4 (Δ = 1). Maximum flow value 3, with f(1, 2) = 1, f(1, 3) = 2, f(2, 3) = 0, f(2, 4) = 1, f(3, 4) = 2. Final residual graph: 1 → 3 has capacity 1 left, and from 3 only 3 → 1 leaves, so S = {1, 3}, and c(S) = c(1, 2) + c(3, 4) = 1 + 2 = 3, matching the lecture's "c(S) = 3".8.3 Minimum cut and the Max-Flow Min-Cut Theorem
In plain words. The minimum cut problem asks for the cheapest way to separate s from t, where cutting an edge costs its capacity. Ford-Fulkerson already solves it: after the last iteration, collect every vertex you can still reach from s in the residual graph, and that set is a cheapest cut. Its capacity equals the maximum flow value. So in every network the largest flow and the smallest cut are the same number, which is the Max-Flow Min-Cut Theorem.
- Input: a flow network (G, s, t). Output: a minimum s-t cut S (a set of vertices, s ∈ S, t ∉ S).
- Algorithm: run Ford-Fulkerson; S = the vertices reachable from s in the last residual graph (one BFS or DFS).
- Why it is minimum: |f| = c(S) from the Ford-Fulkerson proof, and any cheaper cut would be smaller than a flow, contradicting the Flow-Cut Lemma.
- Running time O(mv) + O(m + n) = O(mv).
- Max-Flow Min-Cut Theorem: in every flow network, the value of a maximum s-t flow equals the capacity of a minimum s-t cut.
- The edges leaving S are all saturated and the edges entering S all carry 0 flow.
- Classic trap: answering with the set of saturated edges, or with "the vertices that cannot reach t"; the answer is the set reachable from s in Gf, and a saturated edge need not leave it.
Problem
Notes, Section 6.2: "The input is a flow network (G, s, t), and our goal is to return a minimum s-t cut. Describe an O(mv)-time algorithm for this problem (where v is the value of the maximum flow), prove that it's correct, and analyze its running time." In the main example the answer is S = {1, 2, 3} with c(S) = c(2, 4) + c(3, 4) + c(3, 5) = 1 + 3 + 5 = 9, the smallest value in Check-in 8.2.
Algorithm
Run Ford-Fulkerson to completion, keep the last residual graph Gf, run BFS (or DFS, or any path-finding algorithm) from s in Gf, and return the set of vertices it reaches.
Minimum-Cut(G, s, t):
G_f = last residual graph after calling
Ford-Fulkerson(G, s, t)
S = set of vertices reachable from s in G_f
return S
On the main example, the final residual graph (shaded figure in Section 8.2) has edges out of 1 only to 3, out of 3 only to 1 and 2, and out of 2 only to 1 and 3. BFS from 1 visits 1, 3, 2 and stops: S = {1, 2, 3}. The edges of G leaving S are 2 → 4, 3 → 4 and 3 → 5, all saturated (1/1, 3/3, 5/5), and no edge of G enters S. Capacity 9 = |f|. The same reading on the lecture's November 10 network gives S = {1, 3} with c(S) = 3 (Check-in 8.4), and on the Practice Final network S = {1, 3} with c(S) = 7 (Section 8.7).
| Network | Max flow value | S reachable from s at the end | Edges leaving S | c(S) |
|---|---|---|---|---|
| Greedy counterexample (all capacities 1) | 2 | {1} | 1 → 2, 1 → 3 | 2 |
| Main example (Worksheet Day 1) | 9 | {1, 2, 3} | 2 → 4, 3 → 4, 3 → 5 | 9 |
| Lecture 11-10 example | 3 | {1, 3} | 1 → 2, 3 → 4 | 3 |
| Practice Final 1a | 7 | {1, 3} | 1 → 2, 3 → 4 | 7 |
Correctness
The notes' argument is a two-line contradiction built on the Flow-Cut Lemma. The correctness proof of Ford-Fulkerson showed that the returned flow f and the reachable set S satisfy |f| = c(S). Suppose some s-t cut S′ had c(S′) < c(S). Then c(S′) < |f|, a feasible flow larger than a cut, which the Flow-Cut Lemma forbids. So no cut is cheaper than S, and S is a minimum s-t cut. ∎
The notes call this "the following (surprising) fact", and the lecture marks which half is surprising: max |f| ≤ min c(S) is "not so surprising" (it is the Flow-Cut Lemma), while equality is the content of the Ford-Fulkerson proof, which actually builds a flow and a cut of the same size.
Running time
Ford-Fulkerson takes O(mv); one BFS on Gf (at most 2m edges) takes O(m + n). Assuming v ≥ 1, the total is O(mv) + O(m + n) = O(mv).
Check-in 8.5. True or False, with one sentence each: (a) if some s-t cut has capacity 10, every feasible flow has value at most 10; (b) the minimum s-t cut of a network is always unique; (c) if every capacity is doubled, the maximum flow value doubles.
Answer
(a) True, by the Flow-Cut Lemma. (b) False: in the path s → a → t with both capacities 1, the cuts {s} and {s, a} both have capacity 1. (c) True: every cut's capacity doubles, so the minimum cut doubles, and by Max-Flow Min-Cut so does the maximum flow.8.4 Bipartite matching
In plain words. The lecture's story: children on one side, gifts (or users and ads) on the other, a line whenever a child would accept a gift, and the goal is to hand out as many gifts as possible with no child getting two and no gift shared. Turn this into a flow network: a source feeding each child one unit, each child passing its unit along one of its lines, and each gift passing at most one unit to the sink. A maximum flow then picks out a largest set of child-gift pairs, because the unit capacities at the two ends force every child and every gift to be used at most once.
- Input: a bipartite graph G = (L ∪ R, E), every edge with one endpoint in L and one in R. Output: a maximum matching, a largest set of edges no two of which share an endpoint.
- Build G′: add a source s and a sink t, direct every edge of G from L to R with capacity n = |V(G)|, add (s, u) with capacity 1 for every u ∈ L and (v, t) with capacity 1 for every v ∈ R.
- Run Ford-Fulkerson on (G′, s, t) and return M = {e ∈ E : f(e) = 1}.
- M is a matching because each u ∈ L receives at most 1 unit (and conserves it), and each v ∈ R can send at most 1 unit; |M| = |f|.
- M is maximum because any larger matching would give a larger flow.
- Running time O(mn): G′ has O(m) edges and the flow value is at most n.
- Classic trap: forgetting the capacity-1 edges at s or at t, which lets a vertex be matched twice.
Problem
Notes, Section 6.3: "The input is a bipartite graph G = (L ∪ R, E). Our goal is to return a maximum matching in G. Describe an O(mn)-time algorithm for this problem, prove that it's correct, and analyze its running time." The notes add that a bipartite graph can be labelled L/R in O(m + n) time, and that "in any undirected graph, a subset of edges is a matching if no two edges in the subset share an endpoint." The example used here has L = {1, 2, 3}, R = {4, 5, 6} and edges {1, 4}, {1, 5}, {2, 4}, {3, 5}, {3, 6}; its maximum matching has size 3: {1, 5}, {2, 4}, {3, 6}.
Algorithm
Build the network G′ = (V′, E′) exactly as the notes say: V′ = V ∪ {s, t}; E′ contains every edge of G directed from L to R with capacity n = |V(G)| ("any value in ℤ+ works, but this one will be useful in the next section"; the lecture drew ∞), plus (s, u) with capacity 1 for all u ∈ L and (v, t) with capacity 1 for all v ∈ R. Call Ford-Fulkerson on (G′, s, t) to get a maximum flow f, and return the edges of G whose directed copy carries one unit.
Bipartite-Matching(G):
G' = (V' = V, E' = E)
add s, t to V'
direct every edge in G' from L to R
for e in E':
c(e) = n
for u in L:
add (s, u) to E' with capacity 1
for v in R:
add (v, t) to E' with capacity 1
f = Ford-Fulkerson(G', s, t)
return M = {edges e in E such that f(e) = 1}
For the example, n = 6, and G′ looks like this:
Ford-Fulkerson with DFS (s first tries 1, then 2, then 3; ties toward the smallest label) runs three iterations:
| Iteration | Augmenting path in G′f | Δ | Matching after the iteration |
|---|---|---|---|
| 1 | s → 1 → 4 → t | 1 | {1, 4} |
| 2 | s → 2 → 4 → 1 → 5 → t (4 → 1 is a backward edge) | 1 | {2, 4}, {1, 5} |
| 3 | s → 3 → 6 → t | 1 | {2, 4}, {1, 5}, {3, 6} |
Some cells worked out: in iteration 2, vertex 4 is already full (4 → t is saturated), so DFS follows the backward edge 4 → 1, which "unmatches" 1 from 4 so that 2 can take 4, and 1 is rematched to 5. This is exactly the "undo" that greedy matching lacks. In iteration 3, DFS from 3 first tries 5, finds 5 → t full, follows the backward edge 5 → 1, then 1 → 4, finds 4 → t full and 4 → 2 leading only back toward s, and gives up on that branch; it then takes 3 → 6 → t. Afterwards every edge out of s is saturated, so no s-t path remains. The final flow and the matching it encodes:
Correctness
The notes' proof has three parts, and they are the template for every reduction proof in this chapter.
M is a matching. Ford-Fulkerson with integer capacities produces an integer flow, so every L-to-R edge carries 0 or 1 (it cannot carry more than the single unit that can enter its tail). For any u ∈ L, fin(u) ≤ 1 because the only edge into u is (s, u) with capacity 1, and f is conserved at u, so fout(u) ≤ 1: u is incident to at most one edge of M. Similarly every v ∈ R has fout(v) ≤ 1 because its only outgoing edge is (v, t) with capacity 1, so fin(v) ≤ 1 and v is incident to at most one edge of M.
|M| = |f|. Apply the Flow-Cut Lemma to the cut S = {s} ∪ L: the edges leaving S are the L-to-R edges, each edge of M contributes one unit to fout(S), and no edge enters S, so |f| = fout(S) − fin(S) = |M| − 0.
M is maximum. For contradiction, suppose a matching M* has |M*| > |M|. Convert it into a flow f* by setting f*(s, u) = f*(u, v) = f*(v, t) = 1 for every (u, v) ∈ M* and 0 elsewhere. This is feasible (M* is a matching, so no vertex gets two units) and |f*| = |M*| > |M| = |f|, contradicting the optimality of Ford-Fulkerson. ∎
Running time
Constructing G′ and reading off M take O(m + n) time. G′ has m + |L| + |R| = O(m) edges (every vertex has an edge, as in the notes), and the maximum flow value is at most n because the cut {s} has capacity |L| ≤ n. So Ford-Fulkerson takes O(mv) = O(mn), and the total is O(m + n) + O(mn) = O(mn). The lecture wrote it as "RT: O(mv) = O(mn), v ≤ n".
Variant: more than one unit per vertex (Worksheet Day 2, Problem 2). Children are L, gifts are R, edges are wish lists; each gift goes to at most one child who wants it, every child receives at most 2 gifts, and the number of gifts given is to be maximized in O(mn) time. The notes' solution: the algorithm of Section 6.3 of the notes (Section 8.4 here), "except instead of setting the capacity of every edge leaving s to 1, we set it to 2. This allows for two units of flow to leave from each vertex on the left, which corresponds to the child receiving two gifts." The flow value is still at most |R| ≤ n, so the running time is still O(mn).
Variant: several sources and sinks (Worksheet Day 2, Problem 1). If there is a set S of sources, each able to produce any amount, and a set T of sinks, each able to absorb any amount, and the goal is to maximize the total flow leaving all sources, call Ford-Fulkerson once on a new graph: add a "super source" s with an edge (s, u) of capacity ∞ to every u ∈ S and a "super sink" t with an edge (u, t) of capacity ∞ from every u ∈ T, find a maximum s-t flow, and restrict it to the original edges. (The lecture notes that Σ c(e) works in place of ∞.)
Check-in 8.6. Run Bipartite-Matching on L = {1, 2}, R = {3, 4}, edges {1, 3}, {1, 4}, {2, 3} (DFS from s tries 1 before 2; ties toward the smallest label). Give each augmenting path and the matching returned.
Answer
Path 1: s → 1 → 3 → t, matching {1, 3}. Path 2: s → 2 → 3 → 1 → 4 → t, using the backward edge 3 → 1 to unmatch 1 from 3. M = {1, 4}, {2, 3}, size 2 (a perfect matching).Check-in 8.7. Children 1 and 2, gifts 3, 4, 5. Child 1 wants 3, 4 and 5; child 2 wants only 3. Each child may receive at most 2 gifts. What capacities do the edges out of s get, and how many gifts can be given?
Answer
Each edge (s, u) gets capacity 2 (edges to t keep capacity 1). 3 gifts: child 1 receives 4 and 5, child 2 receives 3. No more is possible because there are only 3 gifts (the cut {s} ∪ L ∪ R has capacity 3).8.5 Bipartite vertex cover
In plain words. A vertex cover is a set of vertices that touches every edge; the lecture's story is placing security cameras at intersections so that every street is watched. On a bipartite graph, build the same network as for matching and find a minimum cut instead of a maximum flow. The cut tells you which left vertices to drop out of the cover and which right vertices to add, and the number of vertices chosen equals the capacity of the cut. Because the middle edges are too expensive to cut, the chosen set always covers every edge.
- Input: a bipartite graph G = (L ∪ R, E). Output: a minimum vertex cover, a smallest set of vertices such that every edge has at least one endpoint in it.
- Build (G′, s, t) as in Section 8.4 (L-to-R edges have capacity n), find a minimum s-t cut S with Minimum-Cut, and return C = (L \ S) ∪ (R ∩ S).
- C covers every edge: an uncovered edge (u, v) would have u ∈ L ∩ S and v ∈ R \ S, so the capacity-n edge (u, v) would leave S and c(S) ≥ n > |L| = c({s}), impossible for a minimum cut.
- |C| = c(S): the edges leaving S are (s, u) for u ∈ L \ S and (v, t) for v ∈ R ∩ S, each of capacity 1.
- C is minimum: a smaller cover C* gives the cut S* = {s} ∪ (L \ C*) ∪ (R ∩ C*) with c(S*) = |C*| < c(S).
- Running time O(mn), the same analysis as matching.
- Classic trap: setting the L-to-R capacities to 1. Then a minimum cut may cut a middle edge and C may miss it; capacity n is what makes the proof work.
Problem
Notes, Section 6.4: "The input is a bipartite graph G = (L ∪ R, E). Our goal is to return a minimum vertex cover of G. Describe an O(mn)-time algorithm for this problem, prove that it's correct, and analyze its running time." The example here has L = {1, 2, 3}, R = {4, 5, 6} and edges {1, 4}, {2, 4}, {3, 4}, {3, 5}, {3, 6}. Vertex 4 covers the first three edges and vertex 3 covers the last three, so a minimum vertex cover is {3, 4}, of size 2 (one vertex is not enough: no single vertex touches both {1, 4} and {3, 6}).
Algorithm
Construct (G′, s, t) exactly as in Section 8.4. Find a minimum s-t cut S in G′ using Minimum-Cut (Section 8.3), that is, run Ford-Fulkerson and take the vertices reachable from s in the final residual graph. Return C: the vertices of L that are not in S, together with the vertices of R that are in S.
Bipartite-VC(G):
construct the flow network (G', s, t)
(as in Section 6.3)
S = minimum s-t cut in G'
return (L \ S) ∪ (R ∩ S)
Trace. Here n = 6. Ford-Fulkerson with DFS finds s → 1 → 4 → t first. Next, DFS from s tries 2: 2 → 4, then 4 → t is full, so it follows the backward edge 4 → 1, from which only 1 → s (visited) and 1 → 4 (visited) leave, a dead end; it then tries 3 and finds s → 3 → 5 → t. Now the flow has value 2 (matching {1, 4}, {3, 5}). In the final residual graph, s still has its forward edge to 2; from 2 you reach 4; from 4 the backward edge 4 → 1 reaches 1; nothing else is reachable (s → 1 and s → 3 are saturated, 4 → t is saturated, and 4 → 3 does not exist because f(3, 4) = 0). So S = {s, 1, 2, 4}.
Then L \ S = {3} and R ∩ S = {4}, so C = {3, 4}. The edges of G′ leaving S are s → 3 and 4 → t, so c(S) = 2 = |C|, and also 2 = the maximum flow value = the size of the maximum matching. No middle edge leaves S: 1 and 2 are in S, and their only neighbor 4 is in S too.
In the matching example of Section 8.4 the final reachable set is S = {s} (every edge out of s is saturated), so C = (L \ S) ∪ (R ∩ S) = {1, 2, 3} ∪ ∅ = {1, 2, 3}, a cover of size 3, again equal to the maximum matching.
Correctness
The notes prove three claims.
C is a vertex cover. For contradiction, suppose an edge {u, v} of G with u ∈ L, v ∈ R is not covered by C. Not covered means u ∉ L \ S, so u ∈ L ∩ S, and v ∉ R ∩ S, so v ∈ R \ S. Then in G′ the edge (u, v) leaves S, so c(S) ≥ n. But the cut {s} has capacity |L| < n, so S would not be a minimum cut, a contradiction.
|C| = c(S). There are two types of edges leaving S: (s, u) with u ∈ L \ S, and (v, t) with v ∈ R ∩ S. (Since S is a minimum cut, no edge (u, v) from L to R leaves S, by the previous paragraph.) Each has capacity 1, so c(S) = |L \ S| + |R ∩ S| = |C|.
C is minimum. For contradiction, suppose C* is a vertex cover with |C*| < |C|. Consider the s-t cut S* = {s} ∪ (L \ C*) ∪ (R ∩ C*). Because C* is a cover, no L-to-R edge leaves S* (its L endpoint is outside C*, so its R endpoint is in C*, hence in S*), and by the same counting as above c(S*) = |C*|. So c(S*) < |C| = c(S), contradicting that S is a minimum s-t cut. ∎
Running time
"This analysis is essentially identical to the one in Section 6.3": constructing G′ takes O(m + n); G′ has O(m) edges and its maximum flow value is at most n, so Ford-Fulkerson plus one BFS takes O(mn); computing C takes O(n). Total O(mn).
Putting Sections 8.4 and 8.5 together through the Max-Flow Min-Cut Theorem: in a bipartite graph, the size of a maximum matching (= the max flow value) equals the size of a minimum vertex cover (= the min cut capacity). The lecture of November 12 summarized the two reductions as "6.3 is reducible to 6.1: Max Flow" and "6.4 is reducible to 6.2: Min s-t Cut".
Extra context beyond the notes: the equality of maximum matching and minimum vertex cover in bipartite graphs is known as Kőnig's theorem. The name is not used in the course.
Check-in 8.8. Worksheet Day 2, Problem 3: True or False? In any undirected graph, the size of the maximum matching is equal to the size of the minimum vertex cover. Explain your answer.
Answer
False. In a triangle (3 vertices, 3 edges), any two edges share an endpoint, so the maximum matching has size 1, but one vertex covers only two of the three edges, so the minimum vertex cover has size 2. (The equality does hold in bipartite graphs, by Sections 8.4–8.5; the triangle is not bipartite.)8.6 Worked problems from Problem Set 6
Problem Set 6 has five problems, and Worksheet Day 3 reuses two of them (Problem 1 there is PS 6.3 verbatim; Problem 2 is a numerical instance of PS 6.5). Every statement below is copied from the course page. The solutions follow the official ones, expanded, in the course's format: Algorithm (idea and pseudocode), Correctness, Running time.
PS 6.1. Global minimum cut with unit capacities
Solution
Here a "cut" is any set S of vertices other than ∅ and V, and its capacity is the number of edges leaving S; there is no s or t given.
Algorithm. Fix any vertex s (for example s = 1). For each other vertex t, compute the capacity of a minimum s-t cut and of a minimum t-s cut (roles swapped), and return the smallest of all these numbers.
ALG(G):
s = vertex 1, ans = inf
for t = 2, ..., n:
min_st = min-st-cut(G, s, t)
min_ts = min-st-cut(G, t, s)
ans = min(ans, min_st, min_ts)
return ans
Correctness. Let S be a minimum cut of G. Since S ≠ ∅ and S ≠ V, there is a vertex inside S and a vertex outside it. Either S includes s or it doesn't. If s ∈ S, pick any t ∉ S; then S is an s-t cut, so the minimum s-t cut computed in the iteration for this t has capacity at most c(S). If s ∉ S, pick any t ∈ S; then S is a t-s cut, and min_ts for this t is at most c(S). The algorithm tries every t ∈ V \ {s} in both directions, so ans ≤ c(S). Conversely, every value it computes is the capacity of a real cut (an s-t cut is neither ∅ nor V), so ans ≥ c(S). Hence ans = c(S).
Running time. All capacities are 1, so the maximum flow value of any s-t pair is at most the number of edges leaving s, at most n − 1. Hence one call of min-st-cut (Ford-Fulkerson plus a BFS) takes O(mv) = O(mn). The algorithm makes 2(n − 1) = O(n) calls, for a total of n · O(mn) = O(mn²).
Pattern: a problem with no s and t is solved by guessing them: fix one side, try every partner in both directions, take the best.
PS 6.2. Removing k edges to cut the flow
Solution
Algorithm. Find a minimum s-t cut S using Ford-Fulkerson, and return any k edges leaving S. (If fewer than k edges leave S, return them all.)
ALG(G, s, t, k):
S = minimum-st-cut(G, s, t), F = empty list
for (u, v) in E:
if u in S and v not in S:
add (u,v) to F
return F[1:k]
Correctness. The official solution's key sentence: by the Max-Flow Min-Cut Theorem, in any G the maximum s-t flow value equals the minimum s-t cut capacity, "thus, if we want to minimize the former, it is equivalent to minimize the latter." In detail, let v = c(S) be the original maximum flow value, which is also the number of edges leaving S since every capacity is 1. Removing k of those edges (or all of them, if c(S) < k) lowers c(S) to max(v − k, 0), so after removal the minimum cut, and therefore the maximum flow, is at most max(v − k, 0). No choice of k edges can do better: removing one edge lowers the capacity of every cut by at most 1, so removing k edges leaves every cut with capacity at least (its old capacity) − k ≥ v − k, and flows are never negative. So the new maximum flow is at least max(v − k, 0) whatever we remove, and the algorithm achieves exactly that.
Running time. Every capacity is 1, so the maximum flow value is at most n (at most n − 1 edges leave s), and Ford-Fulkerson plus a BFS takes O(mn). Scanning E for edges leaving S takes O(m). Total O(mn).
Pattern: "make the maximum flow as small as possible" means "attack a minimum cut", justified by Max-Flow Min-Cut.
PS 6.3. Vertex capacities (= Worksheet Day 3, Problem 1)
Solution
Algorithm. Split every vertex u other than s and t into two vertices uin and uout joined by a directed edge (uin, uout) of capacity c(u). Every original edge (u, v) becomes (uout, vin) with capacity c(u, v): edges arrive at the "in" copy and leave from the "out" copy. Find a maximum s-t flow in the new graph and map it back to the original edges. The lecture's picture:
ALG(G, s, t):
G' = ({s, t}, no edges)
for each u in V \ {s, t}:
add vertices u_in, u_out to G'
add edge (u_in, u_out) of capacity c(u) to G'
for each edge (u,v) in G:
# letting s_out = s_in = s and t_out = t_in = t
add edge (u_out, v_in) of capacity c(u,v) to G'
f' = Max-Flow(G', s, t)
# map f' back to edges in G
f = empty flow in G
for each edge (u,v) in G:
f(u,v) = f'(u_out, v_in)
return f
Correctness. In G′ all flow that enters uin must leave through the single edge (uin, uout), whose capacity is c(u); so the flow through u is at most c(u). Conversely, every flow in G that respects both the edge and the vertex capacities becomes a feasible flow in G′ of the same value by putting fin(u) on the edge (uin, uout), and every feasible flow f′ in G′ maps back to a flow in G that respects edge capacities, conservation (conservation at uin and uout combine into conservation at u) and vertex capacities, with the same value. So the two problems have the same feasible flows and values, and a maximum flow in G′ maps to a maximum flow for our problem.
Running time. G′ has at most 2n vertices and m + n edges, O(m) since G is connected ignoring directions; building it and mapping back take O(m + n). Its maximum flow value is v, the same as the optimum for our problem, so Ford-Fulkerson takes O(mv). Total O(mv).
Pattern: a constraint on a vertex becomes a constraint on an edge by splitting the vertex into an "in" half and an "out" half.
PS 6.4. A path from s to t through u
Solution
The lecture first asks whether "BFS(s)[u] + BFS(u)[t]" works and answers no: a shortest s-u path and a shortest u-t path may share a vertex, and gluing them repeats it. What we need is a u-s path and a u-t path with no vertex in common except u, which is a flow of value 2 out of u when every vertex can be used once.
Algorithm. Replace every undirected edge by two directed edges, one in each direction. Add a new vertex w with edges (s, w) and (t, w). Set every edge and vertex capacity to 1. Find a maximum u-w flow with the algorithm of PS 6.3, and return whether its value is 2.
ALG(G, s, t, u):
G' = G where each edge {u,v} is replaced by (u,v) and (v, u)
add vertex w to G' and edges (s, w), (t, w)
set all edge and vertex capacities to be 1
f = Max-Flow(G', u, w) # using the ALG from Problem 6.3
return |f| == 2
Correctness. (If.) If |f| = 2, the two units reach w through its only two incoming edges, so one unit goes from u to s and then to w, and the other from u to t and then to w. Because every vertex has capacity 1, the two units pass through disjoint sets of vertices (apart from u, the source of the flow), so the u-s path and the u-t path share no vertex. Reversing the u-s path and following it with the u-t path gives an s-t path through u with no vertex repeated. (Only if.) Conversely, an s-t path through u splits at u into a u-s part and a u-t part with no common vertex; sending one unit along each (in the direction pointing away from u), plus the edges (s, w) and (t, w), gives a u-w flow of value 2 that respects all capacities. The value can never exceed 2, since the cut V′ \ {w} has capacity 2. So the answer is True exactly when the maximum flow value is 2.
Running time. Constructing G′ takes O(m) (2m directed edges, two new edges, and the vertex splitting of PS 6.3 adds O(n) = O(m) more since G is connected). The maximum flow value is at most 2, so Ford-Fulkerson runs at most 2 iterations, each O(m). Total O(m).
Pattern: "disjoint paths" means unit capacities and a flow whose value counts the paths; vertex-disjoint means unit vertex capacities, handled by PS 6.3. A tiny bound on v turns O(mv) into O(m).
PS 6.5. Baseball elimination
Solution
The lecture (credited to Kleinberg and Tardos, "[KT]") first makes the problem concrete. Assume τ wins all of its remaining games, ending with W = w[τ] + Σj g[τ][j] wins, the best it can do. Remove τ from the picture. The question becomes: can the remaining games among the other teams end so that every team i finishes with at most W wins, that is, wins at most W − w[i] more games?
Algorithm. In the official solution's words, we "push" g[i][j] units of flow (each unit is a win) to teams i and j without letting any team win more than τ can. Build a network with a source s, a sink t, a vertex "ij" for every pair of teams i, j other than τ, and a vertex for every team other than τ. Edge (s, ij) has capacity g[i][j] (the games to be played); edges (ij, i) and (ij, j) have capacity ∞ (each game's win goes to one of its two teams); edge (i, t) has capacity W − w[i] (the most wins team i may still collect). Compute a maximum flow and answer True exactly when it saturates every edge out of s.
ALG(w, g, tau):
W = maximum possible number of totals wins for tau
G = graph with vertices s, t
for each pair of teams i, j where i, j != tau:
add vertices ij, i, j and edges (ij, i), (ij, j) with capacity inf
add edge (s, ij) with capacity g[i][j]
add edge (i, t) with capacity W - w[i]
add edge (j, t) with capacity W - w[j]
g* = capacity of the cut {s}
return (Ford-Fulkerson(G, s, t) == g*)
(If W − w[i] < 0 for some team, i already has more wins than τ can reach and the answer is False; the official pseudocode leaves this check implicit.)
Correctness. The maximum flow value equals g* (the total number of games left among the other teams) if and only if all those wins can be allocated so that every team i wins at most W − w[i] more games. (If.) An allocation of all game results with these limits gives an integer flow: send one unit s → ij → i for every game between i and j that i wins; edge (i, t) then carries the number of new wins of team i, at most W − w[i]; the value is g*. (Only if.) Ford-Fulkerson returns an integer flow; if its value is g*, every edge (s, ij) is full, and the units on (ij, i) and (ij, j) say how many of the g[i][j] games each team wins, with team i's total new wins bounded by c(i, t) = W − w[i]. Finally, "every other team ends with at most W wins" is exactly "τ (with W wins) can end with the most wins, possibly tied", because W is τ's best possible total and τ winning more of its own games never hurts it.
Running time. There are O(n²) pair vertices, each with three edges, plus n team edges: O(n²) vertices and edges, built in O(n²) time. The capacity of the cut {s} is at most v, the total number of remaining games, so the maximum flow value is at most v and Ford-Fulkerson takes O(n² · v). Total O(n²v).
Worksheet Day 3, Problem 2 (a numerical instance). w = [90, 88, 87, 79]; team 4 has 12 games left (4 against each other team), team 2 has two games left (one each with teams 1 and 3), and teams 1 and 3 play each other 6 more times. Can team 4 end with the most wins? The notes' answer: No. Team 4 reaches at most W = 79 + 12 = 91. Teams 1 and 3 have 90 + 87 = 177 wins and play each other 6 more times, so together they end with at least 183; since 2 · 91 = 182 < 183, one of them ends with at least 92 > 91. In the network (below), g* = 1 + 6 + 1 = 8 while the maximum flow is only 7: the games between 1 and 3 can give at most 1 + 4 = 5 wins to those two teams, and there are 6.
The lecture adds that when τ cannot win, the minimum cut "forms an argument for why τ cannot win": the teams on the s side of the minimum cut are a group whose games among themselves force one of them past W. Here the minimum cut is S = {s, (1,3), 1, 3} with capacity 1 + 1 + 1 + 4 = 7, and the teams in S are exactly 1 and 3, the pair used in the argument above.
Pattern: a "can the totals work out" question becomes a bipartite network: supply on the left (games), limits on the right (allowed wins), and the answer is whether the maximum flow uses all the supply.
8.7 Homework-style one-point questions
Homework 6 was never captured, so it is missing from the sources of this guide; the question types below are built from the Chapter 6 worksheets, Practice Final Problem 1a, and fresh instances. Each type is worked once, in the form of a one-point answer with no explanation, followed by how to get it by hand.
Type 1: the value of a maximum s-t flow (Practice Final, Problem 1a)
"What is the value of a maximum s-t flow in the instance above? (Your answer should just be an integer.)" The network has s = 1, t = 4 and capacities 1 → 2: 6, 1 → 3: 2, 2 → 3: 3, 2 → 4: 8, 3 → 4: 1.
Accepted answer: 7. By hand: everything reaching 4 comes through 2 → 4 or 3 → 4, and everything leaving 1 goes through 1 → 2 or 1 → 3. Vertex 2 can receive at most 6 (from 1) and pass all of it on through 2 → 4 (capacity 8); vertex 3 can pass at most 1 to 4. So a flow of 6 + 1 = 7 is possible: f(1, 2) = 6, f(2, 4) = 6, f(1, 3) = 1, f(3, 4) = 1, f(2, 3) = 0. To be sure it is maximum, find a cut of capacity 7: S = {1, 3}, with leaving edges 1 → 2 (6) and 3 → 4 (1); the edge 2 → 3 enters S and does not count. Running Ford-Fulkerson with DFS gives the same number in three augmentations: 1 → 2 → 3 → 4 (Δ = 1), 1 → 2 → 4 (Δ = 5), 1 → 3 → 2 → 4 (Δ = 1, through the backward edge 3 → 2).
A fresh instance of the same type: s = 1, t = 6 in the network below. Answer: 7. A flow of 7: 3 along 1 → 2 → 4 → 6, 2 along 1 → 3 → 5 → 4 → 6, and 2 along 1 → 3 → 5 → 6. A cut of 7: S = {1, 2, 3}, leaving edges 2 → 4 (3) and 3 → 5 (4).
Type 2: the minimum cut
"List the vertices of a minimum s-t cut" or "what is the capacity of a minimum s-t cut?" On the main example the answers are {1, 2, 3} and 9; on the Practice Final network, {1, 3} and 7. By hand: the capacity is always the maximum flow value; the vertices are those reachable from s in the final residual graph, which you can find without drawing it by asking, from s, "along which edges could I still push one more unit, forward on an unsaturated edge or backward on an edge with flow?"
Type 3: reading or writing a residual graph
"In the network above, after augmenting along P, what is the capacity of the edge (v, u) in Gf?" or Worksheet Day 1's "what is the residual graph at the end of Ford-Fulkerson?" On the fresh network X after the first augmentation 1 → 2 → 4 → 6 (Δ = 3), the residual graph is shown below: the backward edge 4 → 2 has capacity 3, the forward edge 1 → 2 has capacity 1, and 2 → 4 has no forward edge because it is saturated. By hand: for each edge with flow f and capacity c, write a forward edge with c − f (if positive) and a backward edge with f (if positive), and nothing else.
Type 4: maximum matching and minimum vertex cover sizes
"What is the size of a maximum matching in this bipartite graph?" For the graph of Section 8.4 the answer is 3; for the graph of Section 8.5 it is 2, and so is the minimum vertex cover. By hand: find a matching greedily, then look for a cover of the same size; for bipartite graphs the two sizes are always equal, so equal numbers prove both optimal.
Type 5: True or False
Statements in the style of the Practice Final's True/False parts, with the accepted reasoning: "In any undirected graph, the size of the maximum matching is equal to the size of the minimum vertex cover": False (triangle: 1 versus 2). "In every flow network, the value of a maximum s-t flow equals the capacity of a minimum s-t cut": True (Max-Flow Min-Cut). "Ford-Fulkerson runs in O(m + n) time": False, it is O(mv). "The flow on an edge can decrease during Ford-Fulkerson": True, whenever an augmenting path uses its backward edge.
Extra context beyond the notes: the lecture of November 12 also sketched image segmentation (choose a set S of foreground pixels to maximize Σi ∈ S a[i] + Σj ∉ S b[j] − Σe crossing S p[e]) and said it "is reducible to Min s-t Cut", with s connected to pixels by a-edges and pixels to t by b-edges; it appears only in the handwritten notes, without a full algorithm, and is not in the typed notes or the problem set.
Before moving on
- I can state the capacity and conservation constraints, the value |f|, and the capacity c(S) of a cut, counting only edges leaving S.
- I can state and prove the Flow-Cut Lemma.
- I can build a residual graph from a flow and run Ford-Fulkerson by hand, including an augmentation through a backward edge.
- I can read a minimum cut off the final residual graph and explain why its capacity equals the flow (Max-Flow Min-Cut).
- I can write the matching and vertex-cover reductions with their three-part correctness proofs and the O(mn) bound on v.
- I can solve PS 6.1–6.5 in the Algorithm / Correctness / Running time format.
Exercises
Solution
| Iteration | Path | Types | Residual capacities | Δ | |f| |
|---|---|---|---|---|---|
| 1 | 1 → 2 → 3 → 4 → 5 | F F F F | 2, 3, 1, 4 | 1 | 1 |
| 2 | 1 → 2 → 3 → 5 | F F F | 1, 2, 2 | 1 | 2 |
| 3 | 1 → 3 → 2 → 4 → 5 | F B F F | 4, 2, 3, 3 | 2 | 4 |
| 4 | 1 → 3 → 5 | F F | 2, 1 | 1 | 5 |
In iteration 3 the backward edge 3 → 2 (capacity f(2, 3) = 2) returns both units on 2 → 3, so f(2, 3) becomes 0. Final flow: f(1, 2) = 2, f(1, 3) = 3, f(2, 3) = 0, f(2, 4) = 2, f(3, 4) = 1, f(3, 5) = 2, f(4, 5) = 3. Maximum flow value 5. In the final residual graph, 1 reaches only 3 (1 → 3 has 1 left), and from 3 only backward edges to 1 leave; so S = {1, 3} with c(S) = c(1, 2) + c(3, 4) + c(3, 5) = 2 + 1 + 2 = 5 (2 → 3 enters S and does not count).
Solution
The residual graph (Type 3 figure in Section 8.7) has 1 → 2 (1), 1 → 3 (5), 2 → 1 (3), 3 → 2 (2), 3 → 5 (4), 4 → 2 (3), 4 → 6 (2), 5 → 4 (2), 5 → 6 (3), 6 → 4 (3). DFS from 1 tries 2 first; from 2 the only edge is back to 1, a dead end. It then tries 3; from 3, vertex 2 is already visited, so it takes 3 → 5, then 5 → 4 (4 is smaller than 6), then 4 → 6. P = 1 → 3 → 5 → 4 → 6, Δ = min(5, 4, 2, 2) = 2, raising the value to 5. (A third path 1 → 3 → 5 → 6 with Δ = 2 then reaches the maximum 7.)Solution
Ford-Fulkerson on the Section 8.4 network (n = 8) augments along s → 1 → 5 → t, then s → 2 → 5 → 1 → 6 → t (backward edge 5 → 1 rematches 1 to 6), then s → 4 → 7 → t; vertex 3 cannot be matched because its only neighbor 5 is taken and every alternative path dead-ends. Maximum matching size 3: {1, 6}, {2, 5}, {4, 7}.
In the final residual graph, s still reaches 3 (s → 3 is unused), 3 reaches 5, 5 reaches 2 by the backward edge 5 → 2, and 2 reaches only s and 5. So S = {s, 2, 3, 5}, and C = (L \ S) ∪ (R ∩ S) = {1, 4} ∪ {5} = {1, 4, 5}, of size 3 = c(S) (edges s → 1, s → 4, 5 → t). Check: 5 covers {1, 5}, {2, 5}, {3, 5}; 1 covers {1, 6}; 4 covers {4, 7} and {4, 8}.
Solution
(a) False: O(mv), where v is the maximum flow value; each of up to v iterations costs O(m). (b) True: that is the loop's stopping condition. (c) False: in the main example 1 → 2 carries 3/3 but does not leave the only minimum cut {1, 2, 3}; the correct statement is the converse, every edge leaving a minimum cut is saturated by every maximum flow. (d) True, by the Max-Flow Min-Cut Theorem.Solution
The 8 is the capacity of 2 → 3, which enters S (its tail 2 is outside S). c(S) sums capacities of edges leaving S only: c({1, 3}) = c(1, 2) + c(3, 4) + c(3, 5) = 3 + 3 + 5 = 11. Entering edges matter only in the flow identity |f| = fout(S) − fin(S), never in the capacity.Solution
Algorithm. Give every edge capacity 1 and return the value of a maximum s-t flow. (Edges entering s or leaving t can be deleted first, since no path that uses them is needed; this matches the course's assumption about flow networks.)
ALG(G, s, t):
G' = G without edges entering s or leaving t
set c(e) = 1 for every edge e of G'
f = Ford-Fulkerson(G', s, t)
return |f|
Correctness. (Paths give a flow.) If there are k edge-disjoint s-t paths, put one unit on every edge of every path: no edge carries more than 1 because the paths share no edge, conservation holds because each path enters and leaves each inner vertex equally often, and the value is k. So the maximum flow is at least the maximum number of disjoint paths. (A flow gives paths.) Ford-Fulkerson returns an integer flow, so every edge carries 0 or 1. Starting at s, follow edges carrying one unit; by conservation every inner vertex entered can be left on an unused unit edge, so the walk reaches t; remove its edges (shortcutting any repeated vertex) and repeat. Each round removes one unit from the value, so a flow of value k yields k edge-disjoint s-t paths. Hence the maximum flow value equals the maximum number of edge-disjoint paths.
Running time. The cut {s} has capacity at most n − 1 (one unit per edge leaving s), so v ≤ n − 1 and Ford-Fulkerson takes O(mv) = O(mn). Building G′ takes O(m + n). Total O(mn).
Solution
Algorithm. The Bipartite-Matching network with one change: the edge (j, t) for each project j gets capacity k[j] instead of 1. Run Ford-Fulkerson and assign student i to project j whenever f(i, j) = 1.
ALG(G, k):
build (G', s, t) as in Bipartite-Matching
for each project j in R:
c(j, t) = k[j]
f = Ford-Fulkerson(G', s, t)
return {(i, j) in E such that f(i, j) = 1}
Correctness. The flow is integral. Each student i receives at most one unit (c(s, i) = 1) and conserves it, so it is assigned to at most one project; each project j sends at most k[j] units to t, so it receives at most k[j] students; and the number of assigned students equals |f| (Flow-Cut Lemma on the cut {s} ∪ L). Conversely, any valid assignment of a students gives a feasible flow of value a (one unit along s → i → j → t per assigned pair). So a larger assignment would give a larger flow than Ford-Fulkerson's, a contradiction: the assignment is maximum.
Running time. G′ has O(m) edges; the cut {s} has capacity |L| ≤ n, so v ≤ n and Ford-Fulkerson takes O(mn). Building G′ and reading off the assignment take O(m + n). Total O(mn).
Solution
No. Team 4 plays teams 2 and 3 once each, so W = 90 + 2 = 92. The other games are (1, 2), (1, 3), (2, 3), one each, so g* = 3. Capacities into t: W − w[1] = 0, W − w[2] = 1, W − w[3] = 1. At most 0 + 1 + 1 = 2 units can reach t, so the maximum flow is 2 < 3 = g*, and τ cannot finish first. The lecture's direct argument: teams 1, 2, 3 have 92 + 91 + 91 = 274 wins and play 3 games among themselves, so together they end with at least 277 > 3 · 92 = 276, and one of them ends with at least 93.Solution
For matching, the capacity-1 edges at s and at t already limit every vertex to one unit, so the middle capacities never bind and the proof goes through for any positive value. For vertex cover, the proof that C covers every edge needs "a minimum cut never cuts a middle edge", which holds only because cutting one costs n > |L| = c({s}). With middle capacity 1 on the single-edge graph, the cuts {s}, {s, 1} and {s, 1, 2} all have capacity 1, so a minimum cut could be S = {s, 1}; then C = (L \ S) ∪ (R ∩ S) = ∅ ∪ ∅ = ∅, which covers nothing. With capacity n = 2, the cut {s, 1} costs 2, the minimum cuts are {s} and {s, 1, 2}, and C = {1} or {2}, both correct covers.Course Ch. 8 · Nov 17–199. Approximation algorithms
Every algorithm in Chapters 2 through 8 of this guide returns an optimal answer: the shortest path, the minimum spanning tree, the maximum flow. Course Chapter 8 starts from the takeaway of Chapter 7 (see Chapter 10, not examined): for some problems nobody knows an algorithm that is both (1) polynomial-time and (2) optimal. In the lecture's words, in Chapter 8 "we'll give up on optimality, but not entirely": the algorithms are fast and simple, and they come with a proof that their answer is never worse than a fixed factor times the best possible answer. The chapter has four such algorithms (Vertex Cover, Load Balancing, Metric k-Center, Maximum Cut), each a few lines long, and the interesting part is always the proof. This material was taught on November 17 and 19, after Midterm 2, so it has never been examined; the Practice Final spends three one-point parts (2c, 2d, 2e) and two full five-point problems (4 and 8) on it, and Problem 4 is Problem Set 8.1 word for word. An approximation proof never computes the optimum; it compares the algorithm's answer with a bound that every solution, including the optimal one, must satisfy.
9.1 What an approximation algorithm is
In plain words. An approximation algorithm is a fast algorithm that does not promise the best answer, only an answer that is guaranteed to be close to the best. "Close" is measured by a single number, the approximation factor, which says how far from optimal the answer can be on the worst possible input. For a minimisation problem the factor is at least 1 (a 2-approximation never returns more than twice the minimum), and for a maximisation problem it is at most 1 (a 1/2-approximation never returns less than half the maximum). Because the optimum is unknown, the proof always goes through a quantity that is easy to reason about and is known to bound the optimum.
- The input is an instance X of an optimisation problem; the output is a feasible solution (a real vertex cover, a real assignment of jobs) whose value is provably close to OPT(X).
- Minimisation, α ≥ 1: OPT(X) ≤ ALG(X) ≤ α · OPT(X) for every instance X.
- Maximisation, α ≤ 1: OPT(X) ≥ ALG(X) ≥ α · OPT(X) for every instance X.
- A proof has two parts: the output is feasible, and its value is within the factor α. In this chapter any polynomial running time is acceptable, and the notes say an analysis "is not even necessary".
- The approximation ratio is the smallest α that works; a 2-approximation is automatically a 3-approximation, and a 1/2-approximation is automatically a 1/3-approximation.
- The trick that makes every proof work: find a bound on OPT (a lower bound for minimisation, an upper bound for maximisation) and compare ALG with that bound.
- Classic trap: proving the inequality on one example. "For every instance" means a general argument; one example can only refute a claimed ratio.
Problem
The notes open the chapter as follows: "For many problems, it is not known if there exists a polynomial-time algorithm that optimally solves the problem. One way to address this is to settle for a polynomial-time algorithm that approximately solves the problem." The lecture's first example is Vertex Cover, a problem that, in the lecture's margin note, is "in NP but unknown if in P". If a minimum vertex cover of some graph has 3 vertices, a 2-approximation algorithm may return any vertex cover with 3, 4, 5 or 6 vertices, and nothing larger.
The definition
OPT(X) ≤ ALG(X) ≤ α · OPT(X).
The approximation ratio of an algorithm is the smallest α such that the algorithm is an α-approximation algorithm. For maximisation problems all inequalities flip, so α ≤ 1 and every instance satisfiesOPT(X) ≥ ALG(X) ≥ α · OPT(X).
The notes use "ALG" both for the algorithm and for the value of its output, and "OPT" both for an optimal solution and for its value; the context keeps them apart. The left inequality, OPT(X) ≤ ALG(X) for minimisation, is free: OPT is the best value over all feasible solutions, and ALG's output is one of them. All the work is in the right inequality.
Why a 2-approximation is also a 3-approximation. If ALG(X) ≤ 2 · OPT(X) for every X, then, since values are non-negative, ALG(X) ≤ 2 · OPT(X) ≤ 3 · OPT(X), which is exactly the definition of a 3-approximation. The same holds for every α′ ≥ α. For maximisation, ALG(X) ≥ 12 OPT(X) ≥ 13 OPT(X), so a 1/2-approximation is a 1/3-approximation, and in general an α-approximation is an α′-approximation for every α′ ≤ α. A weaker guarantee is implied by a stronger one; that is why the approximation ratio is defined as the smallest α (for maximisation, the largest) that works. Practice Final 2d and 2e test exactly this, and both answers are True.
Arguing about an OPT you cannot compute. The proofs in this chapter never find OPT. Instead they find a quantity that OPT cannot beat, for structural reasons that hold for every solution, and compare ALG with that quantity:
| Problem | Type | Bound on OPT used in the notes | Why every solution obeys it |
|---|---|---|---|
| Vertex Cover | min | |OPT| ≥ |M| for the matching M the algorithm builds | each vertex covers at most one edge of a matching |
| Load Balancing | min | T* ≥ Σ ℓ[j] / m and T* ≥ ℓ[k] for every job k | the maximum load is at least the average load; every job sits on some machine |
| Metric k-Center | min | two points in one optimal cluster are within 2r* of each other | triangle inequality through the cluster's center |
| Maximum Cut | max | OPT ≤ w(E) | a cut cannot contain more than all the edges |
Check-in 9.1. (a) A 3/2-approximation algorithm for a minimisation problem is run on an instance whose optimal value is 12. What values can its output have? (b) A 1/2-approximation algorithm for a maximisation problem returns a solution of value 9. What is the largest possible optimal value? (c) True or false: a 3/2-approximation algorithm for Vertex Cover is also a 2-approximation algorithm.
Answer
(a) Any value from 12 to 18, since 12 ≤ ALG ≤ (3/2) · 12 = 18. (b) 9 ≥ OPT/2, so OPT ≤ 18. (c) True: ALG ≤ (3/2) OPT ≤ 2 OPT.9.2 Vertex Cover: a 2-approximation via a matching
In plain words. A vertex cover is a set of vertices that touches every edge, and the goal is to use as few vertices as possible. The algorithm repeatedly picks any edge that is not yet covered, puts both of its endpoints into the cover, and deletes them from the graph. Taking both endpoints looks wasteful, but any cover must contain at least one of them, so the algorithm takes at most twice what any cover must take. The edges it picks share no endpoints, which is what makes the counting work.
- Input: an undirected graph G. Output: a vertex cover S, a set of vertices such that every edge has at least one endpoint in S.
- Idea: while an edge {u, v} remains, add both u and v to S and remove them (with all their edges) from G.
- The picked edges form a matching M (no two share an endpoint), and |S| = 2 · |M|.
- Bound on OPT: each vertex of an optimal cover covers at most one edge of M, so |OPT| ≥ |M|.
- Conclusion: |S| = 2|M| ≤ 2|OPT|, a 2-approximation. Running time polynomial (linear with adjacency lists).
- The ratio 2 is tight: on a graph made of k disjoint edges, ALG = 2k and OPT = k.
- Trap: the natural greedy (repeatedly take a vertex of maximum remaining degree) is not optimal and not a 2-approximation.
Problem
The notes state it this way: "The input is an undirected graph G. Our goal is to return a minimum vertex cover of G. Describe a 2-approximation algorithm for this problem and prove that it's correct. (Again, in this chapter, any polynomial running time is acceptable.)" The lecture's two warm-up instances are a triangle, where the algorithm returns 2 vertices and the optimum is 2, and a square (a 4-cycle), where the algorithm returns all 4 vertices and the optimum is 2 (two opposite corners). The square already shows the factor 2 is reached.
Why the naive approach fails
Worksheet Day 1/2, Problem 1 asks you to "show that the greedy algorithm for vertex cover (i.e., keep picking a vertex whose remaining degree is maximized and remove that vertex from the graph) is not optimal." The lecture's hint was "7 vertices, 6 edges", and the official solution is the graph with edges {1, 2}, {1, 3}, {1, 4}, {2, 5}, {3, 6}, {4, 7}: vertex 1 with three legs of length 2.
Greedy first takes vertex 1 (degree 3, the only vertex of degree more than 2). The remaining edges {2, 5}, {3, 6}, {4, 7} are disjoint, so greedy needs one more vertex for each: with ties broken by the smallest label it takes 2, 3, 4. ALG = {1, 2, 3, 4}, size 4. The optimal cover {2, 3, 4} has size 3: vertex 2 covers {1, 2} and {2, 5}, and so on.
The lecture added that there are graphs on which this greedy's cover exceeds OPT by a factor that grows like log n, so it is not an α-approximation for any constant α.
Algorithm
Start with an empty set S. As long as the graph still has an edge, pick any edge e = {u, v}, add both u and v to S, and delete u and v from the graph; deleting a vertex also deletes every edge touching it, so every edge covered by u or v disappears. When no edge is left, return S. The notes' pseudocode:
VC-Matching(G):
S = empty set
while G has an edge e = {u,v}: # ALG must include u or v (or both)
add u and v to S
remove u and v from G
return S
The trace below runs it on the spider graph above, picking at each step the remaining edge whose endpoints come first in label order (any choice is allowed; this is the convention used throughout the guide).
| Step | Edges left before the step | Edge picked | S after the step |
|---|---|---|---|
| 1 | {1,2}, {1,3}, {1,4}, {2,5}, {3,6}, {4,7} | {1, 2} | {1, 2} |
| 2 | {3,6}, {4,7} | {3, 6} | {1, 2, 3, 6} |
| 3 | {4,7} | {4, 7} | {1, 2, 3, 6, 4, 7} |
| 4 | none | stop | {1, 2, 3, 4, 6, 7}, size 6 |
Some cells worked out: removing vertices 1 and 2 in step 1 deletes the four edges {1,2}, {1,3}, {1,4}, {2,5}, which is why only two edges remain for step 2. The matching is M = {{1, 2}, {3, 6}, {4, 7}}, so |S| = 6 = 2|M|, and since OPT = 3 the algorithm returns exactly 2 · OPT here.
Correctness
Two things must be shown: S is a vertex cover, and |S| ≤ 2|OPT|.
Feasibility. An edge leaves the graph only when one of its endpoints is removed, and every removed vertex is put into S. The loop stops only when no edges are left, so every edge has an endpoint in S.
The ratio (the notes' three-step argument, numbered as in the lecture):
- Let M be the set of edges the algorithm "focuses on". Each iteration adds exactly two new vertices, so |S| = 2 · |M|.
- M is a matching: after {u, v} is picked, u and v are removed, so no later edge can share an endpoint with {u, v}.
- Bound on OPT: OPT must cover every edge of M, and a single vertex covers at most one edge of a matching (two edges of M never share a vertex). So OPT needs a different vertex for each edge of M, and |OPT| ≥ |M|.
Combining, |S| = 2 · |M| ≤ 2 · |OPT|. ∎
Running time
The notes do not ask for an analysis ("any polynomial running time is acceptable"). Extra context beyond the notes: scanning the adjacency lists once, skipping edges with an already-removed endpoint, gives O(n + m).
Variants. In a bipartite graph, a minimum vertex cover can be found exactly with Bipartite-VC from course Chapter 6 (Chapter 8); the 2-approximation matters for general graphs. The same algorithm read as "return M" instead of "return S" is the greedy maximal-matching algorithm of Problem Set 8.1, a 1/2-approximation for Maximum Matching (Section 9.6).
Check-in 9.2. Run VC-Matching on the graph below (two triangles joined by the edge {3, 4}), always picking the remaining edge whose endpoints come first in label order. List the edges picked and S, then give the size of a minimum vertex cover.
Answer
Picked {1, 2}, then {3, 4}, then {5, 6}; S = {1, 2, 3, 4, 5, 6}, size 6. A minimum cover has 4 vertices (for example {1, 2, 4, 5}: a triangle needs 2 of its 3 vertices, so 4 is also a lower bound). 6 ≤ 2 · 4, as promised.9.3 Load Balancing: greedy is a 2-approximation
In plain words. There are n jobs of given lengths and m identical machines, and every job must be placed on one machine. The load of a machine is the total length of its jobs, and the makespan is the largest load; the goal is to make the makespan as small as possible. The greedy algorithm takes the jobs one at a time, in the given order, and puts each on the machine that is currently least loaded. Its makespan is at most twice the optimum, because the machine that ends up heaviest was the lightest when it received its last job.
- Input: (ℓ, m), an array ℓ of n positive job lengths and m machines. Output: an assignment of jobs to machines; its makespan is the maximum load.
- Greedy: for j = 1, …, n, assign job j to the machine with the smallest current load (ties to the smallest label).
- Two lower bounds on the optimal makespan T*: T* ≥ Σj ℓ[j] / m (the average load) and T* ≥ ℓ[k] for every job k.
- Key fact: if machine i has the final makespan T and job k was its last job, then when k arrived every machine had load at least T − ℓ[k].
- Result: T ≤ Σ ℓ[j]/m + ℓ[k] ≤ T* + T* = 2T*; the improved analysis gives T ≤ (2 − 1/m) T*, and Problem Set 8.2 shows this is tight.
- Sorting the jobs longest first (Problem Set 8.3) improves the guarantee to 3/2.
- Trap: process the jobs in the given order, and compare loads before adding the new job.
Problem
The notes: "In a typical scheduling problem, there are n jobs and m machines, and we need to assign each job to a machine. Every job has a length, and the load on a machine is the sum of the lengths of the jobs assigned to that machine. The makespan of an assignment is the maximum load created by that assignment." Then: "The input is (ℓ, m), where ℓ is an array of n positive integers representing job lengths and m is the number of machines. Our goal is to return an assignment of jobs to machines that minimizes the makespan. Describe a 2-approximation algorithm for this problem and prove that it's correct." The lecture's example is ℓ = [5, 1, 4, 2, 3] with m = 3: greedy reaches makespan 6, while the optimum is 5. The lecture also asked "minimizing average load?" and answered it: Σ ℓ[i] / m is the average load of every assignment, so the average cannot be the objective; the maximum is.
Algorithm
Go through the jobs in order j = 1, 2, …, n. For each job, look at the current loads of all m machines, choose the machine with the smallest load (on a tie, the smallest machine number, per the exam's tie-breaking rule), and add job j to it. The order of the jobs is "any order" in the notes, but on the exam it is ℓ[1] through ℓ[n] unless a problem says otherwise.
Load-Balance(l, m):
for j = 1, ..., n:
i = machine with smallest current load
assign job j to machine i
Hand trace on the lecture's example, ℓ = [5, 1, 4, 2, 3], m = 3. The loads column is the load of machines 1, 2, 3 after the step.
| Job j | ℓ[j] | Loads before | Machine chosen | Loads after |
|---|---|---|---|---|
| 1 | 5 | [0, 0, 0] | 1 (tie, smallest label) | [5, 0, 0] |
| 2 | 1 | [5, 0, 0] | 2 (tie between 2 and 3) | [5, 1, 0] |
| 3 | 4 | [5, 1, 0] | 3 | [5, 1, 4] |
| 4 | 2 | [5, 1, 4] | 2 | [5, 3, 4] |
| 5 | 3 | [5, 3, 4] | 2 | [5, 6, 4] |
The makespan is T = 6 (machine 2). Some cells worked out: job 5 goes to machine 2 because its load 3 is smaller than 4 and 5, even though putting it on machine 3 would have given 7 there; greedy only looks at current loads. The optimum puts 5 alone, 1 + 4 together, and 2 + 3 together, for makespan T* = 5.
Correctness
Feasibility is immediate: every job is assigned to exactly one machine. For the ratio, the proof is a bound on OPT argument with two lower bounds. Let T be ALG's makespan, let i be a machine whose load is T, let k be the last job assigned to i, and let T* be the optimal makespan.
- Bound on ALG. When ALG assigned job k to machine i, machine i had the smallest load, and that load was T − ℓ[k] (the final load minus the last job). Loads never decrease, so at the end every machine has load at least T − ℓ[k]. Summing over the m machines, Σj=1n ℓ[j] ≥ m (T − ℓ[k]), which rearranges to T ≤ Σ ℓ[j]m + ℓ[k].
- First lower bound on OPT. Σ ℓ[j] / m is the average load of every assignment, including OPT's, and the maximum load is at least the average: T* ≥ Σ ℓ[j] / m.
- Second lower bound on OPT. OPT must put job k on some machine, whose load is then at least ℓ[k]: T* ≥ ℓ[k].
- Conclusion. T ≤ Σ ℓ[j]m + ℓ[k] ≤ T* + T* = 2T*. ∎
This is exactly Worksheet Day 1/2, Problem 2: "Assuming Σ ℓ[j] ≥ m(T − ℓ[k]) and T* ≥ Σ ℓ[j]/m, show that T ≤ 2T*." The official answer: rearranging the first inequality gives T ≤ Σ ℓ[j]/m + ℓ[k]; with the second this is T ≤ T* + ℓ[k]; and ℓ[k] ≤ T* because the optimal solution must assign job k to some machine.
The improved analysis. The notes sharpen step 1: when job k arrived, job k itself was not yet on any machine, so the sum of all lengths excluding job k is at least m(T − ℓ[k]). Then
T ≤ Σ ℓ[j] − ℓ[k]m + ℓ[k] = Σ ℓ[j]m + (1 − 1m) ℓ[k] ≤ (2 − 1m) T*,
so the greedy algorithm is a (2 − 1/m)-approximation. On the lecture's example (m = 3) this promises T ≤ (5/3) · 5 ≈ 8.33, and indeed T = 6.
Running time
Not required by the notes. Extra context beyond the notes: finding the least loaded machine by scanning all m loads takes O(m) per job, so O(nm) in total.
Variant: sorting first. Worksheet Day 2/2 and Problem Set 8.3 sort the jobs in non-increasing order and then run the same greedy; the guarantee becomes 3/2 (proof in Section 9.7). On the lecture's example the sorted order is [5, 4, 3, 2, 1] and greedy gives loads [5, 5, 5], the optimum. Sorting does not always give the optimum: ℓ = [3, 3, 2, 2, 2], m = 2 gives makespan 7 sorted, while 3 + 3 | 2 + 2 + 2 achieves 6.
Check-in 9.3. Run greedy on ℓ = [2, 3, 4, 6, 2, 2], m = 3 (jobs in order, ties to the smallest machine). Fill in the loads after each job, give the makespan, and use the two lower bounds to show the optimum is at least 7.
| job j | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| ℓ[j] | 2 | 3 | 4 | 6 | 2 | 2 |
| machine | ||||||
| loads after |
Answer
Machines 1, 2, 3, 1, 2, 3; loads [2, 0, 0], [2, 3, 0], [2, 3, 4], [8, 3, 4], [8, 5, 4], [8, 5, 6]. Makespan 8. Lower bounds: T* ≥ 19/3 ≈ 6.33 and T* ≥ 6; loads are integers, so T* ≥ 7, and 6 | 4 + 3 | 2 + 2 + 2 achieves 7.9.4 Metric k-Center: farthest-point greedy is a 2-approximation
In plain words. We are given n points with distances between them and must choose k of them as centers; every point is then served by its closest center, and we want the worst-served point to be as close as possible. The greedy algorithm picks an arbitrary first center and then, k − 1 times, adds the point that is currently farthest from all chosen centers. Its worst distance is at most twice the optimum, and the proof needs the triangle inequality, which is why the problem is called metric k-Center. The notes point out the resemblance to Load Balancing: both greedily attack the largest value among several groups.
- Input: (d, k), an n × n array d giving a metric on X = {1, …, n}, and a positive integer k. Output: a set S of k centers; the objective is the maximum radius, the largest distance from a point to its closest center.
- Metric: d(u, v) ≥ 0, d(u, v) = d(v, u), d(u, v) = 0 exactly when u = v, and the triangle inequality d(u, v) ≤ d(u, w) + d(w, v).
- Greedy: S = {1}; repeat k − 1 times: add the point whose distance to its closest center in S is largest.
- Proof idea: any two points in the same optimal cluster are within 2r* of each other (triangle inequality through the optimal center).
- Two cases: an ALG center lies in p's optimal cluster (then p is within 2r*), or by pigeonhole two ALG centers share an optimal cluster (then the later one, when added, was the farthest point and was within 2r*).
- Trap: without the triangle inequality the guarantee is false; it is used twice, once in each case.
Problem
The notes: "For any S ⊆ X, we create 'clusters' according to S by assigning each point in X to its closest point in S; each point in S is the 'center' of its cluster. The radius of a cluster is the maximum distance from its center to a point in the cluster." Then: "The input is (d, k), where d is an n × n array representing a metric on a set of points X = [n] and k ∈ ℤ+. Our goal is to return a subset S of k points such that the maximum radius across the k clusters is minimized. Describe a 2-approximation algorithm for this problem and prove that it's correct." The lecture's story: n houses, pick k of them for stores, and minimise the maximum distance from a house to its closest store. Homework 8's instance is the points {1, 2, 3, 4, 5} with d(i, j) = |j − i| and k = 3: the optimum radius is 1 (for example, with centers {2, 4, 5}, points 1 and 3 are at distance 1 from center 2), and it cannot be 0 because only 3 of the 5 points are centers.
Algorithm
Start with point 1 as the only center (any point works; Homework 8 starts with point 2). Then repeat k − 1 times: for every point not yet a center, compute its distance to the closest center chosen so far; add the point for which this distance is largest. Return the k centers. The notes' pseudocode:
Metric-k-Center(d, k):
S = {1}
for i = 1, ..., k-1:
u = point in X \ S whose distance to
its closest point in S is maximized
add u to S
return S
Worked example (constructed for this guide, the notes have no numeric trace): six points on a line at positions 0, 2, 3, 9, 10, 15, with d(i, j) the difference of their positions (distances along a line form a metric), and k = 3.
| Round | Centers S | dist to closest center: points 1, 2, 3, 4, 5, 6 | Farthest point added |
|---|---|---|---|
| start | {1} | 0, 2, 3, 9, 10, 15 | 6 (distance 15) |
| 1 | {1, 6} | 0, 2, 3, 6, 5, 0 | 4 (distance 6) |
| 2 | {1, 6, 4} | 0, 2, 3, 0, 1, 0 | stop (k centers) |
The returned centers are S = {1, 6, 4}, with maximum radius 3 (point 3 is at distance 3 from center 1). Some cells worked out: in round 1 point 4 is at distance 9 from center 1 and 15 − 9 = 6 from center 6, so its closest-center distance is 6, the largest. The optimum is r* = 2 with centers {2, 4, 6}: cluster {1, 2, 3} around 2 has radius 2, {4, 5} around 4 has radius 1, {6} has radius 0. Indeed 3 ≤ 2 · 2.
Correctness
The argument is a case analysis with a bound on OPT. Let r* be the optimal maximum radius, and for a center c of OPT let OPT(c) be the set of points OPT assigns to c. The building block: if two points a and b both lie in OPT(c), then d(a, b) ≤ d(a, c) + d(c, b) ≤ r* + r* = 2r*, by the triangle inequality and because every point of OPT(c) is within r* of c. Now take any point p, and let t* be the OPT center with p ∈ OPT(t*).
- Case 1: ALG has a center t in OPT(t*). Then p and t are in the same optimal cluster, so d(p, t) ≤ d(p, t*) + d(t*, t) ≤ r* + r* = 2r*. Point p's closest ALG center is at most as far as t, so p is within 2r*.
- Case 2: no ALG center lies in OPT(t*). ALG has k centers, and every one of them lies in some optimal cluster; since OPT(t*) contains none of them, they lie in at most k − 1 clusters. By the pigeonhole principle some optimal cluster OPT(c) contains two ALG centers u₁ and u₂, so d(u₁, u₂) ≤ 2r*. Say u₁ was added before u₂. When u₂ was added, it was the point farthest from its closest center, and that distance was at most d(u₂, u₁) ≤ 2r*. So at that moment every point was within 2r* of some center, and adding more centers only shrinks distances; in particular p is within 2r* of an ALG center at the end.
- Conclusion. In both cases p is within 2r* of its closest ALG center, so ALG's maximum radius is at most 2r*. ∎
Running time
Not required by the notes. Extra context beyond the notes: keep, for every point, its distance to the closest center; adding a center updates all n values in O(n), so the k − 1 rounds take O(nk) time after reading d.
Check-in 9.4. Six points on a line at positions 0, 4, 5, 11, 12, 20 (point i at the i-th position, distance = difference of positions), k = 3, first center 1. Fill in the farthest point added in each round, then give the final centers and maximum radius.
| round | centers before | closest-center distances of points 1–6 | point added |
|---|---|---|---|
| 1 | {1} | ||
| 2 |
Answer
Round 1: distances 0, 4, 5, 11, 12, 20, add 6. Round 2: centers {1, 6}, distances 0, 4, 5, 9, 8, 0, add 4. Final S = {1, 6, 4}, maximum radius 5 (point 3 to center 1). The optimum is 4 (centers {2, 4, 6}), and 5 ≤ 2 · 4.9.5 Maximum Cut: local search is a 1/2-approximation
In plain words. A cut splits the vertices into two sides, and its weight is the total weight of the edges that go from one side to the other; the goal is a cut of maximum weight. The local search algorithm starts with everything on one side and keeps moving a single vertex to the other side whenever that increases the cut weight. When no single move helps, every vertex has at least half of its own edge weight crossing the cut. Adding that up over all vertices shows the cut has at least half of all edge weight, and no cut can have more than all of it.
- Input: an undirected graph G with positive integer edge weights w(e). Output: a cut S ⊆ V; δ(S) is the set of edges with exactly one endpoint in S, and the value is w(δ(S)).
- Local search: start with S = ∅; while moving one vertex u across (into or out of S) increases w(δ(S)), make the move.
- Termination: each move gains at least 1 (integer weights) and w(δ(S)) ≤ w(E), so at most w(E) moves; this is not polynomial in general, and the notes say so.
- At the end, α(u) ≥ w(δ(u))/2 for every vertex u, where α(u) is the weight of u's edges that cross the cut and δ(u) is the set of all edges at u.
- Summing: 2 · w(δ(S)) = Σ α(u) ≥ 12 Σ w(δ(u)) = w(E) ≥ OPT, so ALG ≥ OPT/2.
- Upper bound on OPT: OPT ≤ w(E), since a cut contains at most all the edges.
- Trap: in a hand trace, move the smallest-labelled vertex whose move helps, not the one that helps most.
Problem
The notes: "Suppose G is an undirected graph. For any cut S ⊆ V, we let δ(S) denote the set of edges crossing S (i.e., those with exactly one endpoint in S). If edge e has weight w(e), then for any F ⊆ E, we let w(F) = Σe∈F w(e)." Then: "The input is G, an undirected graph where each edge e has some positive integer weight w(e). Our goal is to return a cut S that maximizes w(δ(S)). Describe a 1/2-approximation algorithm for this problem and prove that it's correct." It is the opposite of the minimum s-t cut of course Chapter 6 (Chapter 8), which is solvable exactly with max flow. Homework 8's instance, used for the trace below, has edges {1,2} of weight 4, {1,3} of 4, {1,4} of 1, {2,4} of 5 and {3,4} of 7; its maximum cut has weight 20.
Algorithm
Begin with S empty, so no edge crosses and the cut weight is 0. In each iteration, look for a vertex u such that moving u to the other side (into S if it is outside, out of S if it is inside) increases the cut weight; on the exam, check the vertices in label order and move the first one that helps. Moving u changes only the edges at u: those that crossed stop crossing, and those that did not cross start crossing, so the gain is (weight of u's non-crossing edges) − (weight of u's crossing edges). Stop when no vertex has a positive gain and return S. The notes call this "local search":
Max-Cut(G):
S = empty set
while we can increase w(delta(S)) by moving one vertex u:
move u from S to V \ S (or vice versa)
return S
Hand trace on the Homework 8 graph, moving the smallest-labelled vertex with a positive gain:
| Iteration | S before | Vertex moved, gain | S after | Crossing edges after | w(δ(S)) |
|---|---|---|---|---|---|
| 1 | ∅ | 1, +9 (4 + 4 + 1) | {1} | {1,2}, {1,3}, {1,4} | 9 |
| 2 | {1} | 2, +1 (gain 5 on {2,4}, lose 4 on {1,2}) | {1, 2} | {1,3}, {1,4}, {2,4} | 10 |
| 3 | {1, 2} | 3, +3 (gain 7 on {3,4}, lose 4 on {1,3}) | {1, 2, 3} | {1,4}, {2,4}, {3,4} | 13 |
| 4 | {1, 2, 3} | 1 out of S, +7 (gain 4 + 4, lose 1) | {2, 3} | {1,2}, {1,3}, {2,4}, {3,4} | 20 |
| 5 | {2, 3} | no vertex has a positive gain | stop | 20 |
Some cells worked out: in iteration 2, vertex 2 has edges {1, 2} (weight 4, crossing, since 1 ∈ S) and {2, 4} (weight 5, not crossing); moving 2 into S makes {2, 4} cross and {1, 2} stop, a gain of 5 − 4 = 1. In iteration 4, vertex 1 is checked first and its gain is +7, so it moves even though it was the first vertex put into S. In the final cut S = {2, 3}, the only non-crossing edge is {1, 4} of weight 1, so w(δ(S)) = 21 − 1 = 20, which is the maximum.
Correctness
Termination. "In each iteration, w(δ(S)) increases by at least 1, and the maximum possible value of w(δ(S)) is w(E). Thus, the algorithm terminates in at most w(E) iterations."
The ratio, a local optimality plus upper bound on OPT argument:
- At the end, take any vertex u, and let α(u) be the total weight of u's edges that cross the cut (u's contribution). The rest of u's edges weigh w(δ(u)) − α(u).
- Moving u would lose α(u) and gain w(δ(u)) − α(u). The algorithm stopped, so this net gain is at most 0: α(u) ≥ w(δ(u)) − α(u), that is, α(u) ≥ w(δ(u))/2. "Every vertex is contributing at least half as much as it possibly could."
- Sum over all vertices. Each crossing edge is counted at both of its endpoints, so Σu α(u) = 2 · w(δ(S)); each edge is at two vertices, so Σu w(δ(u)) = 2 · w(E).
- Upper bound on OPT: no cut contains more than all edges, so OPT ≤ w(E).
- Conclusion: 2 · w(δ(S)) = Σ α(u) ≥ 12 Σ w(δ(u)) = w(E) ≥ OPT, so w(δ(S)) ≥ OPT/2. ∎
Running time
The notes are explicit that this is not polynomial in general: the number of iterations is at most w(E), and w(E) "could be, say, 2n". They add that a slightly modified version, moving u only when w(δ(S)) increases by at least a factor of about (1 + 0.1/n), runs in polynomial time and is a 0.49-approximation with a similar analysis. With all weights equal to 1, w(E) = m and the local search takes at most m iterations.
Check-in 9.5. Run the local search from S = ∅ on the graph below, moving the smallest-labelled vertex with a positive gain. Fill in the vertex moved and the cut weight after each iteration, and give the returned cut.
| iteration | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| vertex moved | |||||
| w(δ(S)) after |
Answer
Move 1 (weight 7), move 3 (10), move 1 back out (11), move 2 (13), then stop. Note that in iteration 2 vertex 2 has gain 2 + 1 − 3 = 0, which is not an increase, so 3 is moved. Returned S = {2, 3}, weight 13 out of w(E) = 15; this is also the maximum.9.6 Proving a ratio or refuting it
In plain words. The final asks about approximation algorithms in two forms: "Prove that this is an α-approximation algorithm", and "Is this an α-approximation algorithm? Prove it, or give a counterexample and explain." Both proofs follow the same pattern as Sections 9.2 to 9.5: a bound on OPT, a bound on ALG, and a one-line conclusion. A refutation needs only one small instance on which the algorithm's value violates the ratio, with both values computed. The Practice Final has one problem of each form, and both are worked below with the official solutions.
- Label the three parts: Bound on OPT (lower bound for minimisation, upper bound for maximisation), Bound on ALG, Conclusion (the ratio). Also state feasibility if it is not obvious.
- The most common bound is a charging (assignment) argument: assign every element of OPT to an element of ALG, show each element of ALG receives at most c, and conclude |OPT| ≤ c · |ALG|.
- The assignment must be well defined: show that every element of OPT has somewhere to go, usually because otherwise the algorithm would not have stopped.
- To refute, give a specific instance, the algorithm's run on it (including how it may break ties), ALG's value, OPT's value, and the ratio that violates the claim.
- "Prove it or give a counterexample": the first word must be "Yes" or "No"; decide by trying the smallest bad instances (a path, a star, a triangle, disjoint edges) first.
- Trap: an example on which ALG happens to be optimal proves nothing; a proof must hold for every instance.
- Feasibility. One sentence: why the output is a valid solution (a matching, a cover, an independent set).
- Name the objects. "Let M be ALG's output and M* an optimal solution; we want |M*| ≤ 2|M|" (maximisation with α = 1/2), or "|S| ≤ 2|S*|" (minimisation with α = 2).
- Bound on OPT via the algorithm's structure. Assign each element of OPT to an element of ALG that "blocked" it; explain why every element of OPT can be assigned (otherwise the algorithm would have taken it).
- Bound on ALG. Show each element of ALG receives at most c elements of OPT.
- Conclusion. Count: |OPT| ≤ c · |ALG|, so ALG ≥ OPT/c for a maximisation problem. (For a minimisation problem, charge the elements of ALG to elements of OPT instead and conclude |ALG| ≤ c · |OPT|.)
- Decide. Try small instances where the algorithm's freedom ("any vertex", "any edge") can hurt it. If the worst you find still meets the ratio, look for a Recipe A proof; if one violates it, answer No.
- First word. "Yes." or "No."
- If Yes: follow Recipe A.
- If No: give the instance (draw it or list the edges), say what ALG does on it (a run the algorithm is allowed to make), compute ALG and OPT, and show ALG > α · OPT (minimisation) or ALG < α · OPT (maximisation).
Recipe A on Practice Final Problem 4 (Problem Set 8.1)
The problem: "The input is an undirected, connected graph G, and our goal is to return a maximum matching in G. Consider the following algorithm: [repeatedly add any remaining edge e to F and remove e and all edges incident to either endpoint of e]. Prove that this is a 1/2-approximation algorithm." The instructor's solution on December 1 was introduced with the words "in our heads (not in ALG)": the assignment below is a proof device, not part of the algorithm.
- Feasibility. After e = {u, v} is added, every edge touching u or v is removed, so no later edge shares an endpoint with e: F is a matching.
- Name the objects. Let M = F be ALG's output and M* a maximum matching. We want |M*| ≤ 2 · |M|, which is the same as |M| ≥ 12 |M*|.
- Assignment. For each e* ∈ M*, assign e* to any edge of M that shares at least one endpoint with e*. This is well defined: if some e* shared no endpoint with any edge of M, it would never have been removed, so the loop could not have stopped (equivalently, M ∪ {e*} would be a matching and ALG would have picked e*).
- Each edge of M receives at most 2. An edge e = {u, v} ∈ M has two endpoints, and M* is a matching, so at most one edge of M* touches u and at most one touches v.
- Conclusion. Counting the assigned edges edge by edge of M: |M*| ≤ 2 · |M|. ∎
The ratio is tight: on the path 1–2–3–4, ALG may pick the middle edge {2, 3} first, which removes both other edges, so ALG = 1 while OPT = 2 ({1, 2} and {3, 4}).
Recipe B on Practice Final Problem 8
The problem: "The input is an undirected, connected graph G = (V, E) with maximum degree Δ ≥ 1. An independent set is a subset S of V such that for all u, v ∈ S, {u, v} ∉ E. Our goal is to return an independent set S such that |S| is maximized. Consider the following algorithm: [while G has a vertex, take any vertex u, add u to S, and remove u and its neighbours from G]. Is this a 1/Δ-approximation algorithm? Prove it, or give a counterexample and explain. (The first word of your answer should be 'Yes' or 'No'.)"
Decide. The worst case is a star: a center with Δ leaves. If ALG picks the center first, it removes everything and returns 1 vertex, while the leaves form an independent set of size Δ. The ratio is exactly 1/Δ, not worse, which suggests the answer is Yes.
The official solution, step by step (Recipe A inside Recipe B):
- First word. Yes.
- Feasibility. When u is added, all its neighbours are removed, so no later vertex is adjacent to u: S is independent.
- Name the objects. For every u ∈ S, let Su be the set of vertices (including u) removed in the iteration that added u. We want |S| ≥ |OPT|/Δ, that is, |OPT| ≤ Δ · |S|.
- Each Su contains at most Δ vertices of OPT. Su is u plus at most Δ neighbours, since deg(u) ≤ Δ. If u ∈ OPT, none of u's neighbours is in OPT (OPT is independent), so |OPT ∩ Su| = 1 ≤ Δ. If u ∉ OPT, then OPT ∩ Su consists of neighbours of u, at most Δ of them.
- Every vertex of OPT is in some Su. The algorithm stops only when the graph is empty, so every vertex was removed in some iteration; otherwise ALG would have added it. The sets Su are disjoint.
- Conclusion. |OPT| = Σu∈S |OPT ∩ Su| ≤ Σu∈S Δ = Δ · |S|, so |S| ≥ |OPT|/Δ. ∎
Check-in 9.6. Cover the two recipe boxes and write Recipe A from memory, naming its five steps, then say in one sentence what makes the assignment in Practice Final Problem 4 well defined.
Answer
(1) Feasibility; (2) name ALG's output and OPT and state the target inequality; (3) assign each element of OPT to an element of ALG; (4) show each element of ALG receives at most c; (5) conclude |OPT| ≤ c · |ALG|. The assignment is well defined because an edge of M* sharing no endpoint with M would still be in the graph, so the algorithm would not have stopped (it would have added that edge).Check-in 9.7. Run the Practice Final Problem 8 algorithm on the path 1–2–3–4–5 (Δ = 2). What is the smallest independent set it can return, what is OPT, and does this agree with the "Yes" answer?
Answer
Picking 2 removes 1, 2, 3; then picking 4 removes 4, 5: |S| = 2 (no run returns 1, since one pick removes at most 3 vertices). OPT = {1, 3, 5}, size 3. 2 ≥ 3/Δ = 1.5, so it agrees.9.7 Worked problems from Problem Set 8
Problem Set 8 has four problems; the statements below are copied from the course page. The Practice Final reused Problem 8.1 verbatim as Problem 4, and the instructor announced that at least two final-exam problems are identical to problem-set problems, so all four are worth knowing cold.
PS 8.1. Greedy maximal matching
ALG(G):
F = empty set
while G has >= 1 edge e:
add e to F
remove e and all edges incident to either endpoint of e
return F
Prove that this is a 1/2-approximation algorithm.Solution
Feasibility. When e is added to F, every edge sharing an endpoint with e is removed, so no later edge of F touches e. F is a matching.
Bound on OPT. Let M be the output of the algorithm and M* a maximum matching; we want to show |M*| ≤ 2 · |M|. For each e* ∈ M*, assign e* to any edge in M that shares at least one endpoint with e*. This assignment is well defined, because if some e* did not share an endpoint with any edge in M, then M ∪ {e*} would be a matching, and e* would never have been removed from G, so the algorithm should not have returned M.
Bound on ALG. Iterate through every e ∈ M and count the edges assigned to it. Every e ∈ M is assigned at most two edges of M*, because e has two endpoints and M*, being a matching, has at most one edge at each of them.
Conclusion. |M*| ≤ 2 · |M|, that is, |M| ≥ 12 |M*|, so the algorithm is a 1/2-approximation. (Its running time is polynomial: at most n/2 iterations, each scanning the edges.)
Pattern: charging argument; each ALG element "blocks" at most two OPT elements.
PS 8.2. A tight instance for greedy Load Balancing
Solution
Instance. m(m − 1) jobs of length 1, followed by a single job of length m.
ALG. Greedy distributes the first m(m − 1) unit jobs evenly across the m machines (each block of m consecutive unit jobs puts one job on every machine, because the machine just used is never the least loaded), so each machine has load m − 1. Then one machine receives the final job of length m, so ALG = (m − 1) + m = 2m − 1.
OPT. Assign the length-m job to its own machine and distribute the other m(m − 1) unit jobs evenly across the other m − 1 machines, m per machine, so every machine has load m. No assignment does better, since the length-m job alone gives load m. So OPT = m.
Ratio. ALG / OPT = (2m − 1)/m = 2 − 1/m. For example, with m = 3: six unit jobs and one job of length 3; greedy gives loads [5, 2, 2], makespan 5, while the optimum is 3, and 5/3 = 2 − 1/3.
Pattern: a tight example; many small jobs fill every machine evenly, then one long job lands on top. It shows the (2 − 1/m) analysis cannot be improved.
PS 8.3. Sorted greedy is a 3/2-approximation
ALG(l, m):
sort the jobs l in non-increasing order
for i = 1, ..., n:
j = machine with smallest current load
assign job i to machine j
Prove that this is a 3/2-approximation algorithm.Solution
Setup. Follow the notation from the notes, with ℓ sorted so that ℓ[1] ≥ ℓ[2] ≥ ⋯ ≥ ℓ[n]: let i denote a machine whose load is T (ALG's makespan), let k be the index of the last job (after sorting) assigned to i, and let T* be the optimal makespan. From the analysis of Section 8.2 (Section 9.3 here), T ≤ 1m Σ ℓ[j] + ℓ[k] ≤ T* + ℓ[k]. It remains to bound ℓ[k]. Split into two cases, as the worksheet hint suggests.
Case 1: k is the only job assigned to i. Then T = ℓ[k] ≤ T*, because OPT must put job k somewhere. So ALG = OPT in this case.
Case 2: i has at least two jobs. Then k ≥ m + 1, because each of the first m jobs was assigned to an empty machine at the time (an empty machine has load 0, the smallest possible), so machine i's second job comes later than job m. Among the first m + 1 jobs, OPT must assign two to the same machine (pigeonhole: m + 1 jobs, m machines); both have length at least ℓ[m + 1] since ℓ is sorted, so T* ≥ 2 · ℓ[m + 1]. Hence ℓ[k] ≤ ℓ[m + 1] ≤ T*/2.
Conclusion. In Case 2, T ≤ 1m Σ ℓ[j] + ℓ[k] ≤ T* + T*2 = 32 T*; in Case 1, T ≤ T*. Either way T ≤ (3/2) T*.
Pattern: reuse a known analysis and sharpen one term (ℓ[k] ≤ T*/2) by a case split and the pigeonhole principle.
PS 8.4. Dominating Set via Metric k-Center
Solution
Algorithm. Convert each vertex of G into a point, set distances according to the edges of G (1 for adjacent vertices, 2 for non-adjacent ones, 0 from a point to itself), and call the 1.9-approximation algorithm, here called ALG:
DS-ALG(G, k):
X = V(G), d = [0]*(n * n)
for u, v in X with u != v:
if {u, v} in E(G): d[u][v] = 1
else: d[u][v] = 2
if (radius of ALG(d, k)) = 1: # ALG is the 1.9-approximation algorithm
return "yes"
return "no"
d is a metric. Distances are symmetric, 0 exactly on the diagonal, and the triangle inequality holds because every distance between distinct points is 1 or 2: d(u, v) ≤ 2 ≤ d(u, w) + d(w, v) whenever w differs from u and v. So (d, k) is a valid instance of Metric k-Center.
Correctness, "yes" instances. Suppose G has a dominating set S with |S| ≤ k. Using S (padded with arbitrary extra points if |S| < k) as the centers, every point is a center or adjacent to one, so the maximum radius is at most 1; hence r* ≤ 1. The 1.9-approximation must return a solution of maximum radius at most 1.9; since every distance is 0, 1 or 2, its radius is at most 1. So DS-ALG correctly returns "yes". (The radius could be 0 only if all n points were centers, that is, k ≥ n, when the answer is trivially "yes"; writing the test as "radius ≤ 1" covers that corner case.)
Correctness, "no" instances. Conversely, if the 1.9-approximation algorithm finds a solution S′ with |S′| ≤ k and maximum radius 1, then every point is within distance 1 of a center, which by construction means it is a center or adjacent to one: S′ is a dominating set of G of size at most k, so the answer "yes" was right. Contrapositive: if G has no dominating set of size at most k, every set of k centers has radius 2, and DS-ALG returns "no".
Running time. Building d takes O(n²) time and ALG runs in polynomial time, so DS-ALG is polynomial.
Pattern: a reduction (course Chapter 7, see Chapter 10); the gap between distances 1 and 2 is larger than the 1.9 factor, so the approximation answers the yes/no question exactly.
9.8 Homework-style one-point questions
Homework 8 had five question types, each auto-graded and worth one point per part. Each type is worked here on the homework's own instance, with the accepted answer.
Type 1: greedy makespan and optimal makespan (Q1, Q2)
Q1 gives ℓ = [1, 1, 2] and m = 2. "Suppose we run the greedy 2-approximation algorithm from the course notes on the instance above. (Iterate through the jobs in order, from ℓ[1] through ℓ[n].) What is the makespan of the resulting assignment?" Job 1 goes to machine 1 (loads [1, 0]), job 2 to machine 2 ([1, 1]), job 3 to machine 1 by the tie rule ([3, 1]): accepted answer 3. "What is the optimal makespan?" Put the two unit jobs together and the length-2 job alone: accepted answer 2; it cannot be less, since the average load is 4/2 = 2.
Q2 asks the same question for 100 job lengths and m = 10 (the instance is too long to repeat; it is in Homework 8). By hand, keep a row of 10 running loads and, for each job, add it to the smallest entry; the final loads are [516, 565, 498, 555, 553, 571, 563, 520, 508, 522], and the accepted answer is 571. A sanity check uses the analysis itself: the lengths sum to 5371, so the average load is 537.1, and the makespan must lie between 537.1 and 537.1 plus the length of the last job on the heaviest machine (93), that is, below 630.1.
Type 2: what the ratio allows (Q3)
| Question | Reasoning | Accepted answer |
|---|---|---|
| ALG is a 2-approximation for Vertex Cover and OPT has size 30. Largest possible |S|? | |S| ≤ 2 · 30 | 60 |
| ALG returns a cover of size 30. Smallest possible |S*|? | 30 ≤ 2 |S*|, so |S*| ≥ 15 | 15 |
| True or False? A 2-approximation for Vertex Cover is also a 3-approximation. | |S| ≤ 2 OPT ≤ 3 OPT | True |
Type 3: possible next centers in Metric k-Center (Q4)
Points {1, 2, 3, 4, 5}, distance |j − i|, k = 3, first center 2. "What are the possibilities for the second center?" Distances to center 2 are 1, 1, 2, 3 for points 1, 3, 4, 5; the farthest is 5, so the accepted answer is 5 only. "What are the possibilities for the third center?" Distances to the closest of {2, 5} are 1 (point 1), 1 (point 3) and 1 (point 4): a three-way tie, so any of them can be chosen, and the accepted answer is 1, 3, 4. When a question says "check all that apply", list every tied point.
Type 4: Maximum Cut weights (Q5)
On the graph of Section 9.5 (edges {1,2}: 4, {1,3}: 4, {1,4}: 1, {2,4}: 5, {3,4}: 7), Q5 asks for the maximum cut weight (accepted 20: the total is 21, and the cut {2, 3} misses only the weight-1 edge; no cut reaches 21, because the triangle 1, 2, 4 cannot have all three edges crossing), and, for the local search from S = ∅ with ties to the smallest label, the weight after 1 iteration (given as 9 = 4 + 4 + 1), after 2 iterations (accepted 10), after 3 iterations (accepted 13), and at the end (accepted 20). The full trace is the table in Section 9.5. To find the maximum cut by hand on four vertices, note that an odd cycle can never have all its edges crossing, and drop its lightest edge.
9.9 Past exam problems on this chapter
No midterm covered course Chapter 8. The Practice Final, distributed and solved in class on December 1, has the five problems below. The one-point parts are answered without explanation; Problems 4 and 8 carry 5 points each.
Practice Final, Problem 2c
Solution
4. Loads after each job: [3, 0, 0], [3, 1, 0], [3, 1, 2], and the last job (3) goes to machine 2 (load 1), giving [3, 4, 2]. (The optimum is 3: 3 | 3 | 1 + 2.)Practice Final, Problem 2d
Solution
True. ALG ≤ 2 · OPT ≤ 3 · OPT for every instance.Practice Final, Problem 2e
Solution
True. ALG ≥ OPT/2 ≥ OPT/3 for every instance.Practice Final, Problem 4 (Problem Set 8.1)
ALG(G):
F = empty set
while G has >= 1 edge e:
add e to F
remove e and all edges incident to either endpoint of e
return F
Prove that this is a 1/2-approximation algorithm.Solution
The official solution is "This is Problem 8.1 from Problem Set 8"; the model answer is the same.
Feasibility. Every edge touching a chosen edge is removed, so F = M is a matching.
Bound on OPT. Let M* be a maximum matching; we show |M*| ≤ 2|M|. Assign each e* ∈ M* to an edge of M sharing an endpoint with it. Every e* has such an edge: otherwise e* would still be in G when the loop ended (M ∪ {e*} would be a matching), a contradiction.
Bound on ALG. Each e ∈ M has two endpoints, and M* has at most one edge at each, so at most two edges of M* are assigned to e.
Conclusion. |M*| ≤ 2|M|, so |M| ≥ |M*|/2: a 1/2-approximation.
Practice Final, Problem 8
ALG(G):
S = empty set
while G has >= 1 vertex:
u = any vertex in G
add u to S and remove u (and its neighbors) from G
return S
Is this a 1/Δ-approximation algorithm? Prove it, or give a counterexample and explain. (The first word of your answer should be "Yes" or "No".)Solution
Yes.
Feasibility. Adding u removes all of u's neighbours, so no two vertices of S are adjacent.
Bound on OPT. For every vertex u ∈ S, consider the iteration in which u was added to S, and let Su be the set of vertices (including u) removed from G in that iteration. Every vertex v ∈ OPT is in some Su, because otherwise the algorithm would have added v to S (the loop runs until G is empty). The sets Su are disjoint.
Bound on ALG. |OPT ∩ Su| ≤ Δ: if u ∈ OPT, no neighbour of u is in OPT, so the intersection is {u} and 1 ≤ Δ; if u ∉ OPT, the intersection consists of neighbours of u, and deg(u) ≤ Δ.
Conclusion. |OPT| = Σu∈S |OPT ∩ Su| ≤ Σu∈S Δ = Δ · |S|, so |S| ≥ |OPT|/Δ.
Before moving on
- I can state the definition of an α-approximation algorithm for minimisation and for maximisation, and explain why a 2-approximation is a 3-approximation.
- I can prove VC-Matching is a 2-approximation (|S| = 2|M|, M is a matching, |OPT| ≥ |M|).
- I can run greedy Load Balancing by hand, give the two lower bounds on T*, and prove T ≤ 2T*.
- I can run farthest-point greedy for Metric k-Center and say where the triangle inequality is used in its proof.
- I can run the Maximum Cut local search with the smallest-label rule and prove ALG ≥ w(E)/2 ≥ OPT/2.
- I can write a charging proof (Recipe A) and a counterexample with both values computed (Recipe B).
Exercises
Solution
Loads: [1, 0], [1, 2], [4, 2], [4, 6], [9, 6], [9, 12]. Greedy makespan 12. Optimal 11: the average is 21/2 = 10.5, so T* ≥ 11, and 6 + 5 | 4 + 3 + 2 + 1 = 11 | 10 achieves it.Solution
Distances to center 1 are 1, 5, 6, 7, 14, so the second center is 6. Radius: point 2 is at 1, point 3 at min(5, 9) = 5, point 4 at min(6, 8) = 6, point 5 at min(7, 7) = 7: maximum radius 7. (The optimum is 5, with centers {3, 6}; 7 ≤ 10.)Solution
Iteration 1: vertex 1 has gain 2 + 3 = 5 > 0, so S = {1}, weight 5. Iteration 2: vertex 2 has gain 4 + 6 − 2 = 8, so S = {1, 2}, crossing edges {1,3}, {2,3}, {2,4}, weight 13. Then no move helps (vertex 1: 2 − 3 < 0; vertex 2: 2 − 10 < 0; vertex 3: 1 − 7 < 0; vertex 4: 1 − 6 < 0). Returned weight 13, out of w(E) = 16; 13 is also the maximum.Solution
(a) True: ALG ≤ 1.5 OPT ≤ 2 OPT. (b) False: ALG ≥ OPT/2 does not imply ALG ≥ (2/3) OPT; the implication goes only toward smaller factors. (c) True: 10 ≤ 2 OPT. (d) False: M is maximal (no edge can be added) but not necessarily maximum; on the path 1–2–3–4 the algorithm may pick {2, 3} alone, while {1, 2}, {3, 4} is larger.Solution
Sorted order 3, 3, 2, 2, 2. Loads: [3, 0], [3, 3], [5, 3], [5, 5], [7, 5]: makespan 7. The optimum is 6 (3 + 3 | 2 + 2 + 2), so sorting does not make greedy optimal. 7 ≤ (3/2) · 6 = 9, consistent with the guarantee. Here the heaviest machine's last job is the fifth, k = 5 ≥ m + 1 = 3, and ℓ[5] = 2 ≤ T*/2 = 3, as in Case 2 of the proof.Solution
Yes, it is an m-approximation. Bound on OPT: T* ≥ Σ ℓ[j] / m (average load). Bound on ALG: ALG's makespan is T = Σ ℓ[j]. Conclusion: T = m · (Σ ℓ[j] / m) ≤ m · T*.
No, not a 2-approximation when m ≥ 3. Counterexample: m jobs of length 1. ALG puts all of them on machine 1, so T = m; OPT puts one job on each machine, T* = 1; T/T* = m > 2. (For m = 2 it is a 2-approximation by the first part, since m = 2.)
Solution
No. The output is a vertex cover (an edge leaves the graph only when an endpoint is added), but its size can be far from optimal. Counterexample: the star with center 1 and leaves 2, 3, …, n, edges {1, j}. Every edge has u = 1 and v = j, so the algorithm adds the leaves 2, 3, …, n one at a time: |S| = n − 1. The optimal cover is {1}, of size 1. For n ≥ 4, |S| = n − 1 ≥ 3 > 2 · 1, so the ratio 2 fails (with n = 4: ALG = 3, OPT = 1).
Solution
Two things. First, an example proves nothing about every instance; the claim needs the general argument (the last job k on the heaviest machine i, every machine has load ≥ T − ℓ[k] when k arrives, so Σ ℓ[j] ≥ m(T − ℓ[k])). Second, T* = Σ ℓ[j]/m is false in general: in the lecture's example the average 15/3 = 5 happens to equal T*, but for ℓ = [2, 3, 4, 6, 2, 2] and m = 3 the average is about 6.33 while T* = 7. The correct statement is the lower bound T* ≥ Σ ℓ[j]/m, together with T* ≥ ℓ[k].Solution
Take k disjoint edges {1, 2}, {3, 4}, …, {2k − 1, 2k}. Each iteration picks one of them and adds both endpoints, so |S| = 2k. A cover needs one endpoint of each edge, and one endpoint per edge suffices (for example the odd vertices), so OPT = k. Hence |S| = 2 · OPT. (The lecture's square and the spider graph of Section 9.2 are other examples.)Solution
Algorithm.
Greedy-Cut(G):
S = empty set
for v = 1, ..., n:
a = total weight of edges from v to placed vertices in S
b = total weight of edges from v to placed vertices not in S
if a >= b: place v outside S # cuts weight a
else: place v in S # cuts weight b
return S
Upper bound on OPT. OPT ≤ w(E), since a cut contains at most all the edges.
Bound on ALG. Charge each edge {u, v} with u < v to its later endpoint v. When v is placed, the edges charged to v are exactly its edges to the already-placed vertices, with total weight a + b; the algorithm makes max(a, b) ≥ (a + b)/2 of that weight cross the cut, and placing later vertices never changes whether these edges cross. Every edge is charged to exactly one vertex, so summing over v gives w(δ(S)) ≥ 12 w(E).
Conclusion. w(δ(S)) ≥ w(E)/2 ≥ OPT/2, a 1/2-approximation.
Running time. Placing v scans v's adjacency list once (checking a "placed" flag and a side flag for each neighbour), so the total is O(n + m), which is polynomial.
Course Ch. 7 · Nov 1710. Just in case: computational complexity
Every chapter so far asked for a fast algorithm and found one. Course Chapter 7, taught in the first half of the November 17 lecture, asks the opposite question: are there problems that cannot be solved quickly? It introduces the classes P and NP, the open question of whether they are equal, and the idea of a reduction, all informally and without proofs. "Hard" means "no polynomial-time algorithm is known", and hardness is shown relatively, by reducing a problem believed to be hard to the problem at hand.
10.1 P, NP and the P vs. NP question
In plain words. Theoretical computer science calls an algorithm quick when its running time is a polynomial in the input size, such as n³ or even n¹⁰⁰, but not 2ⁿ. Problems with such an algorithm form the class P; problems that can at least be solved by brute force form the larger class NP. Every problem in COMP 550 is in NP, and most (LIS, MST, Edit Distance, shortest paths) are in P. Whether the two classes are equal is one of the most famous open questions in mathematics.
- "Quick" means polynomial time: n³ and n¹⁰⁰ count, 2ⁿ does not (crossed out on the board).
- P: problems solvable in polynomial time. NP: "nondeterministic polynomial time", which the notes say to think of as "the set of problems that can be solved using brute force".
- P ⊆ NP is known; whether P = NP is open, and it is one of the seven Millennium Prize Problems (one million dollars each).
- To show P ≠ NP: exhibit a problem in NP not in P. To show P = NP: give a polynomial-time algorithm for every problem in NP.
- 0/1 Knapsack and Subset Sum are not known to be in P; the O(nB) Knapsack DP "is not a polynomial-time algorithm".
- Halting is outside NP: no algorithm solves it at all.
Definitions
The lecture writes the two classes as sets of problems A:
P = {A | A can be solved quickly} NP = {A | A can be solved using brute force}
The board draws P inside NP, with LIS and Shortest Path inside P. The lecture's problem outside NP is Halting: given an algorithm A whose input is a string, and a string w, answer "does A halt on w?". No algorithm solves it.
Problem
The notes' example of a problem not known to be in P is Subset Sum: "given an array A of integers and an integer t, find a subsequence of A whose sum is t". For A = [3, 5, 2, 8] and t = 10 the answer exists: 2 + 8 = 10 (and also 3 + 5 + 2 = 10). For t = 6 there is none.
Algorithm, correctness and running time
Brute force places Subset Sum in NP: try every subsequence and check its sum. For A = [3, 5, 2, 8] that is 2⁴ = 16 subsequences, whose sums are 0, 2, 3, 5, 7, 8, 10, 11, 13, 15, 16 and 18, so 10 is reachable and 6 is not. It is correct because it examines every candidate, but it takes about 2ⁿ · n time, which is exponential, and no polynomial-time algorithm is known.
Extra context beyond the slides: why O(nB) is not polynomial. B is written in the input with about log₁₀ B digits. With n = 30 and B = 1,000,000,000 (ten digits) the DP table has 30 · (10⁹ + 1), about 3 · 10¹⁰, entries, and each extra digit of B multiplies that by 10: polynomial in the value of B, exponential in the length of the input. Not examinable.
Check-in 10.1. Mark each running time as polynomial (P) or not polynomial (N) in the size of the input.
| Running time | O(n³) | O(n¹⁰⁰) | O(2ⁿ) | O(mn) for Bipartite-Matching | O(nB) for Knapsack-DP |
|---|---|---|---|---|---|
| P or N |
Answer
P, P, N, P, N. O(n¹⁰⁰) is polynomial even though it is useless in practice; O(mn) is polynomial because m and n measure the size of the graph; O(nB) is not, because B is a number in the input, and the notes say the Knapsack DP "is not a polynomial-time algorithm".10.2 Reductions
In plain words. Proving that a problem B has no polynomial-time algorithm would settle P vs. NP, so the course makes a relative comparison instead: "if A is hard, then B is hard". The tool is a reduction from A to B, "an ALG that solves A using an ALG that solves B". If B were easy, the reduction would make A easy too, so when A is believed to be hard, B probably is as well. Course Chapter 6 already built two reductions.
- A reduction from A to B solves A by calling an algorithm for B (the board writes A ≤ B).
- Direction matters: it transfers easiness from B to A, and hardness from A to B, by a short proof by contradiction.
- The course's examples: Bipartite Matching reduces to Maximum Flow (Section 8.4), and Bipartite Vertex Cover reduces to Minimum s-t Cut (Section 8.5).
- The format, from the notes' remark in Section 6.3: (1) convert the instance X of A to an instance Y of B, (2) solve Y optimally, (3) convert the solution back, (4) show it is optimal for X because it was optimal for Y.
- The conversions must themselves be fast (here O(m + n)).
Problem
The lecture cites "6.3: Reduction from Bip Matching to Max Flow". The notes' problem: "The input is a bipartite graph G = (L ∪ R, E). Our goal is to return a maximum matching in G" (a set of edges, no two sharing an endpoint). For the graph below, with L = {a, b, c}, R = {x, y, z} and edges a–x, a–y, b–x, c–y, c–z, the maximum matching is {a–y, b–x, c–z}, of size 3.
Algorithm
Add a source s and a sink t, direct every edge from L to R with capacity n (the number of vertices of G), and add edges s → u and v → t of capacity 1 for every u ∈ L and v ∈ R. Call Ford-Fulkerson (the algorithm for B) and return the L-to-R edges carrying flow. The notes' pseudocode:
Bipartite-Matching(G):
G' = (V' = V, E' = E)
add s, t to V'
direct every edge in G' from L to R
for e in E':
c(e) = n
for u in L:
add (s, u) to E' with capacity 1
for v in R:
add (v, t) to E' with capacity 1
f = Ford-Fulkerson(G', s, t)
return M = {edges e in E such that f(e) = 1}
On the example n = 6, so the five middle edges have capacity 6 (unlabelled) and the six outer edges capacity 1:
| Step | What the reduction does | Result on the example |
|---|---|---|
| 1. Convert | Build G′ from G | 8 vertices, 11 edges |
| 2. Solve B | Ford-Fulkerson(G′, s, t) | a maximum flow of value 3: s→a→y→t, s→b→x→t, s→c→z→t |
| 3. Convert back | Keep the L-to-R edges with f(e) = 1 | M = {a–y, b–x, c–z} |
Some cells worked out: the flow cannot exceed 3 because only three edges of capacity 1 leave s. Matching a–x would leave b (whose only neighbour is x) unmatched; Ford-Fulkerson's augmenting paths undo such a choice.
Correctness
M is a matching: each u ∈ L receives at most 1 unit from s and flow is conserved, so at most one edge out of u carries flow; likewise for each v ∈ R. The Flow-Cut Lemma on S = {s} ∪ L gives |f| = |M|. M is maximum: a larger matching M* would give a flow f* with |f*| = |M*| > |f|, contradicting the optimality of Ford-Fulkerson. This is step (4): optimal for Y implies optimal for X.
Running time
Building G′ and reading off M take O(m + n) time. G′ has O(m) edges and the flow value is at most n, so Ford-Fulkerson takes O(mn), and the total is O(mn), a polynomial.
Check-in 10.2. Suppose someone finds a fast reduction from Subset Sum to a new problem B. Which conclusion follows: (i) if B can be solved in polynomial time, so can Subset Sum; (ii) if Subset Sum can be solved in polynomial time, so can B? What does this say about B?
Answer
(i). The reduction solves Subset Sum using an algorithm for B, so a fast algorithm for B gives one for Subset Sum. Since Subset Sum is believed to be hard, this is evidence that B is hard too.10.3 From hardness to approximation
In plain words. The lecture closes Chapter 7 with a takeaway: for some problems, nobody knows an algorithm that is both polynomial-time and optimal. Course Chapter 8 (Chapter 9 of this guide) keeps the first requirement and relaxes the second, asking for a polynomial-time algorithm whose answer is provably within a factor α of the optimum. The first example is Vertex Cover, "in NP but unknown if in P" in the lecture's words, although on bipartite graphs Bipartite-VC solves it exactly in O(mn).
- The two goals are (1) polynomial time and (2) optimal; for problems not known to be in P, course Chapter 8 drops (2) "but not entirely".
- An α-approximation algorithm for a minimization problem satisfies OPT(X) ≤ ALG(X) ≤ α · OPT(X) on every instance X, with α ≥ 1 and α as close to 1 as possible.
- Any polynomial running time is acceptable for an approximation algorithm; the course Chapter 8 notes say "an analysis is not even necessary".
- Hardness can depend on a restriction of the input: Vertex Cover is not known to be in P, but bipartite Vertex Cover is in P.
- Approximation ratios, Vertex Cover, Load Balancing, Metric k-Center and Maximum Cut are all in Chapter 9.
10.4 Homework-style one-point questions
Homework 7 had one question type: "True, False, or Unknown?" for "There exists a polynomial-time algorithm for X." Answer True if the course gave a polynomial-time algorithm for X, and Unknown if the course says X is not known to be in P (proving "False" would settle P vs. NP). The four statements and their accepted answers:
| Statement | Accepted answer | Why |
|---|---|---|
| There exists a polynomial-time algorithm for Minimum Spanning Tree. | True | Prim runs in O(mn) in the course notes, a polynomial. |
| There exists a polynomial-time algorithm for 0/1 Knapsack. | Unknown | The notes name it as not known to be in P; O(nB) is not polynomial. |
| There exists a polynomial-time algorithm for Vertex Cover. | Unknown | In NP, unknown if in P; course Chapter 8 approximates it instead. |
| There exists a polynomial-time algorithm for Vertex Cover, assuming that the input is bipartite. | True | Bipartite-VC runs in O(mn). |
Before moving on
- I can define P and NP in the course's informal words and state what is known (P ⊆ NP) and what is open.
- I can explain why the O(nB) Knapsack DP is not a polynomial-time algorithm.
- I can say what a reduction from A to B is and which direction transfers hardness.
- I can answer "True, False, or Unknown" for the existence of a polynomial-time algorithm for any problem in the course.
Exercises
Solution
(a) True: Dijkstra. (b) Unknown: the notes list Subset Sum next to 0/1 Knapsack as not known to be solvable in polynomial time. (c) True: Bipartite-Matching runs in O(mn). (d) False: the lecture's example of a problem not in NP, with "no ALG to solve this problem".Solution
O(nB) is not polynomial in the size of the input: B is a single number written with about log B digits, so the table size n(B + 1) grows exponentially in the length of B. The notes say explicitly that the O(nB) DP "is not a polynomial-time algorithm", and whether 0/1 Knapsack is in P is unknown.Solution
A = Bipartite Vertex Cover, B = Minimum s-t Cut: build the flow network G′, find a minimum s-t cut S, return C = (L \ S) ∪ (R ∩ S). A fast reduction from Vertex Cover to Bipartite Vertex Cover, combined with the O(mn) Bipartite-VC, would give a polynomial-time algorithm for Vertex Cover, turning Homework 7's "Unknown" into "True". Nobody knows such a reduction.Solution
n = 6, so (1, 4), (2, 4), (3, 4), (3, 5) get capacity 6 and the six edges at s and t get capacity 1. Only 4 and 5 can send flow to t (6 has no incoming edge), one unit each, so the flow is at most 2. A maximum flow sends s→1→4→t and s→3→5→t, value 2, giving the matching {1–4, 3–5} ({2–4, 3–5} is equally maximum).11. The official Practice Final, worked
The Practice Final is the closest thing to the real final that exists: same length, same rules, same two halves of quick traces and problem-set-style proofs, and the instructor said the real exam will look like it. The instructor released it on Tuesday, December 1, 2026, and spent that lecture walking through it (the handwritten notes "12-01: Practice Final Exam" record the walk-through, and the official solutions were posted on Canvas the same afternoon). This chapter reproduces every problem verbatim, then writes each solution as a full model answer in the course's format, expanded so that a reader who missed the lectures can follow every step.
The 12-01 notes open with the format of the real final, written in the margin next to the logistics: "3 hours, closed-everything", "8 problems, 5 points each", "P1–P2: ≈ short HW", "P3–P8: ≈ psets", and, underlined, "≥ 2 identical to pset". The Practice Final follows that recipe exactly. Problems 3 and 4 are Problem Set 4, Problem 4.5 and Problem Set 8, Problem 8.1 word for word, and the official solution for each simply says "the solution is on Canvas/Pages". Expect the same on Thursday, December 10: at least two of Problems 3–8 will be problems you can already solve if you have worked the problem sets.
- Closed-everything: no notes, electronics or communication. 3 hours, 40 points, every problem worth 5 points.
- "Anything written outside the boxes will be ignored, even if you reference it in a box."
- Unless the problem says otherwise: (1) all algorithms refer to the ones described in the lectures and notes; (2) describe algorithms in pseudocode similar to the examples in lectures, notes and problem sets (no hashing); (3) array indices start at 1; (4) the values of an array A are listed from A[1] through A[n]; (5) the input graph has vertex set V, edge set E, n = |V|, m = |E|, and is in adjacency-list format.
- You may call, and assume every property proved in the notes for: Max-in-Array, Two-Sum, Binary-Search, Selection-Sort, Merge-Sort, BFS, DFS, Explore, Find-Cycle, Topological-Sort, Prim, Kruskal, Reverse-Delete, Select-Intervals, Fractional-Knapsack, LIS, LPS, Knapsack-DP, Edit-Distance, DAG-DP, Bellman-Ford, Dijkstra, Floyd-Warshall, Ford-Fulkerson, Minimum-st-Cut, Bipartite-Matching, Bipartite-VC, and the approximation algorithms for Vertex-Cover, Load-Balancing, Metric k-Center and Maximum Cut. "You may also call a slightly modified version, but if your modifications are unclear, you might not get full credit."
- Problems 1 and 2: "Do not explain your answers. (1p each, no partial credit)". Ties are broken in favour of the smallest label.
Problem 1 (five parts, one point each, no explanation)
Parts (a)–(c) all refer to the graph printed at the top of the page. Read it once carefully: the edges are directed, and the number on each edge is used as a capacity in (a), ignored in (b), and used as an undirected weight in (c). As an adjacency list with the out-neighbours in increasing order, G = [[2, 3], [3, 4], [4], []], with ℓ(1, 2) = 6, ℓ(1, 3) = 2, ℓ(2, 3) = 3, ℓ(2, 4) = 8 and ℓ(3, 4) = 1.
Solution
7. The fastest certain route is to find a flow and a cut with the same value: by the Flow-Cut Lemma every flow is at most every cut, so if they are equal, both are optimal (Chapter 8). The cut S = {1, 3} has two edges leaving it, (1, 2) with capacity 6 and (3, 4) with capacity 1, so its capacity is 6 + 1 = 7. The edge (2, 3) enters S and does not count. Ford-Fulkerson, finding augmenting paths with DFS and breaking ties towards the smallest label, produces a flow of value 7:
| Iteration | Augmenting path in the residual graph | Bottleneck | Flow value |
|---|---|---|---|
| 1 | 1 → 2 → 3 → 4 | min(6, 3, 1) = 1 | 1 |
| 2 | 1 → 2 → 4 | min(5, 8) = 5 | 6 |
| 3 | 1 → 3 → 2 → 4 (uses the backward edge 3 → 2, undoing the unit on (2, 3)) | min(2, 1, 3) = 1 | 7 |
After iteration 3 the residual graph has edges 1 → 3 (1 unit left), 2 → 1, 2 → 3, 2 → 4 (2 units left), 3 → 1, 4 → 2 and 4 → 3. From vertex 1 the only way out is 1 → 3, and from 3 the only way out is back to 1, so exactly {1, 3} is reachable: that is the minimum cut, shaded below, and its two crossing edges (green) are saturated. The final flow is f(1, 2) = 6, f(1, 3) = 1, f(2, 3) = 0, f(2, 4) = 6, f(3, 4) = 1; 6 + 1 = 7 units enter vertex 4.
Other cuts are larger: {1} has capacity 6 + 2 = 8 and {1, 2, 3} has capacity 8 + 1 = 9, and {1, 2} has capacity 2 + 3 + 8 = 13.
Solution
post = [8, 7, 6, 5].
The clock starts at t = 1 and ticks once at every pre and every post (the course's Explore). Each step below either starts exploring a vertex (pre) or finishes it (post):
| t | Event | Why |
|---|---|---|
| 1 | pre[1] = 1 | start at s = 1 |
| 2 | pre[2] = 2 | 1's first out-neighbour is 2 |
| 3 | pre[3] = 3 | 2's first out-neighbour is 3 |
| 4 | pre[4] = 4 | 3's only out-neighbour is 4 |
| 5 | post[4] = 5 | 4 has no out-neighbours |
| 6 | post[3] = 6 | 3 is finished |
| 7 | post[2] = 7 | 2's other out-neighbour 4 is already visited |
| 8 | post[1] = 8 | 1's other out-neighbour 3 is already visited |
So pre = [1, 2, 3, 4] and post = [8, 7, 6, 5]. The DFS tree is the path 1 → 2 → 3 → 4 (green); (1, 3) and (2, 4) are forward edges.
Solution
{1, 3}, {3, 4}, {2, 3}.
Prim keeps a set S, starting with S = {1}, and in each of n − 1 = 3 rounds adds the lightest edge crossing S:
| Round | S before | Edges crossing S (weight) | Chosen |
|---|---|---|---|
| 1 | {1} | {1, 2} (6), {1, 3} (2) | {1, 3} |
| 2 | {1, 3} | {1, 2} (6), {2, 3} (3), {3, 4} (1) | {3, 4} |
| 3 | {1, 3, 4} | {1, 2} (6), {2, 3} (3), {2, 4} (8) | {2, 3} |
The tree has total weight 2 + 1 + 3 = 6. Write the edges in the order chosen; listing them sorted by weight ({3, 4}, {1, 3}, {2, 3}) would be Kruskal's order and gets no credit.
Solution
d = [1, 1, 2, 3, 2, 3].
In the course's LIS, d[i] is the length of the longest increasing subsequence that ends at A[i]: d[i] = 1 + max{d[j] : j < i, A[j] < A[i]}, or 1 if no such j exists.
| i | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| A[i] | 5 | 1 | 7 | 8 | 2 | 3 |
| d[i] | 1 | 1 | 2 | 3 | 2 | 3 |
Some cells worked out: d[3] = 2 because 7 can follow 5 or 1 (each with d = 1). d[4] = 3 because 8 can follow 7 (d = 2). d[5] = 2 because only A[2] = 1 is smaller than 2. d[6] = 3 because 3 can follow 2 (d = 2), giving 1, 2, 3. The algorithm would return max(d) = 3, but the question asks for the whole array.
Solution
[0, 2, 4, 6, 7].
Knapsack-DP fills d[i][j] = the best value using items 1, …, i with capacity j, for j = 0, …, B. Row 1 is the base case (item 1 fits once j ≥ w[1] = 2); afterwards d[i][j] = d[i−1][j] if j < w[i], and otherwise max(d[i−1][j], v[i] + d[i−1][j − w[i]]).
| d[i][j] | j = 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| i = 1 (v 3, w 2) | 0 | 0 | 3 | 3 | 3 |
| i = 2 (v 4, w 2) | 0 | 0 | 4 | 4 | 7 |
| i = 3 (v 2, w 1) | 0 | 2 | 4 | 6 | 7 |
Some cells worked out: d[2][4] = max(3, 4 + d[1][2]) = max(3, 4 + 3) = 7 (take items 1 and 2). d[3][1] = max(0, 2 + d[2][0]) = 2. d[3][3] = max(4, 2 + d[2][2]) = max(4, 6) = 6. d[3][4] = max(7, 2 + d[2][3]) = max(7, 6) = 7.
Problem 2 (five parts, one point each, no explanation)
Solution
x = [0.5, 1, 1].
Fractional-Knapsack sorts the items by value per weight and takes as much of each as fits. The ratios are v[1]/w[1] = 3/2 = 1.5, v[2]/w[2] = 4/2 = 2 and v[3]/w[3] = 5/1 = 5, so the order is item 3, item 2, item 1.
| Item (ratio) | Capacity left before | Amount taken | Capacity left after |
|---|---|---|---|
| 3 (5) | 4 | x[3] = 1 (weight 1) | 3 |
| 2 (2) | 3 | x[2] = 1 (weight 2) | 1 |
| 1 (1.5) | 1 | x[1] = 1/2 (weight 1 of 2) | 0 |
The value is 5 + 4 + 1.5 = 10.5. List x in index order, x[1] first, not in the order the items were taken.
Solution
2.
One sequence of two moves: insert b at the front (abbc → babbc), then delete the third b (babbc → babc). One move cannot suffice: both strings have length 4, so a single move would have to be a replacement, and abbc and babc differ in positions 1 and 2. The Edit-Distance table confirms it (rows are prefixes of A = abbc, columns prefixes of B = babc; d[i][j] = min(d[i][j−1] + 1, d[i−1][j] + 1, d[i−1][j−1] + [A[i] ≠ B[j]])):
| "" | b | a | b | c | |
|---|---|---|---|---|---|
| "" | 0 | 1 | 2 | 3 | 4 |
| a | 1 | 1 | 1 | 2 | 3 |
| b | 2 | 1 | 2 | 1 | 2 |
| b | 3 | 2 | 2 | 2 | 2 |
| c | 4 | 3 | 3 | 3 | 2 |
Solution
4.
The course's Load-Balance takes the jobs in the given order (no sorting) and puts each on the machine with the smallest current load (ties to the smallest machine number):
| Job | Length | Loads before | Machine | Loads after |
|---|---|---|---|---|
| 1 | 3 | (0, 0, 0) | 1 | (3, 0, 0) |
| 2 | 1 | (3, 0, 0) | 2 | (3, 1, 0) |
| 3 | 2 | (3, 1, 0) | 3 | (3, 1, 2) |
| 4 | 3 | (3, 1, 2) | 2 | (3, 4, 2) |
The makespan is the largest load, 4. (The optimum is 3: {3}, {3}, {1, 2}. So 4/3 ≤ 2, as the guarantee promises.)
Solution
True. Vertex Cover is a minimization problem, so a 2-approximation returns a feasible cover with ALG ≤ 2 · OPT on every instance. Since OPT ≥ 0, 2 · OPT ≤ 3 · OPT, hence ALG ≤ 3 · OPT: the same algorithm meets the weaker guarantee. For minimization problems, a smaller α is a stronger statement.
Solution
True. Maximum Cut is a maximization problem, so the course's definition flips the inequality: a 1/2-approximation guarantees ALG ≥ (1/2) · OPT. Since (1/2) · OPT ≥ (1/3) · OPT, also ALG ≥ (1/3) · OPT. For maximization problems, a larger α (closer to 1) is the stronger statement, so a 1/2-approximation is automatically a 1/3-approximation, never the other way round.
Problem 3. Buying and selling a stock (PS 4.5)
Solution
This is Problem Set 4, Problem 4.5, verbatim (the official solution notes it is LeetCode 121). The instructor's note on 12-01 is the whole idea: "d[j] = max profit if we have to sell on day j = A[j] − mini<j A[i]", with "track this in O(1)" underlined in red.
Subproblems. For every j ∈ {2, …, n}, let OPT[j] be the maximum profit we can make if we must sell on day j. The answer is the maximum of OPT[j] over all j, because the best pair (i, j) sells on some day j.
Recurrence. If we sell on day j, we should have bought on the cheapest earlier day, so OPT[j] = A[j] − mini<j A[i]. Computed directly, each minimum costs O(j) and the total would be O(n²); instead keep the running minimum of A[1], …, A[j−1] in one variable and update it after each day.
Algorithm.
ALG(A):
min_A = A[1] # cheapest price among days 1..j-1
d = [-inf] * n
for j = 2, ..., n:
d[j] = A[j] - min_A # best profit if we sell on day j
min_A = min(min_A, A[j]) # now covers days 1..j
return max(d)
Correctness. At the start of iteration j, min_A = min(A[1], …, A[j−1]): this holds for j = 2 (min_A = A[1]), and the last line of iteration j extends the minimum to day j, so it holds at the start of iteration j + 1. Hence d[j] = A[j] − mini<j A[i] = OPT[j], the best profit among all pairs that sell on day j. Every feasible pair (i, j) with i < j sells on exactly one day j ≥ 2, so max(d) is the maximum over all feasible pairs.
Running time. The loop makes n − 1 iterations of O(1) work, and max(d) takes O(n) (Max-in-Array), so the total is O(n).
Example. For A = [8, 2, 4, 7, 1, 3]:
| j | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| A[j] | 8 | 2 | 4 | 7 | 1 | 3 |
| min_A before day j | 8 | 2 | 2 | 2 | 1 | |
| d[j] | −∞ | −6 | 2 | 5 | −1 | 2 |
max(d) = 5 (buy at 2 on day 2, sell at 7 on day 4).
Problem 4. A greedy matching is a 1/2-approximation (PS 8.1)
ALG(G):
F = empty set
while G has >= 1 edge e:
add e to F
remove e and all edges incident to either endpoint of e
return F
Prove that this is a 1/2-approximation algorithm.Solution
This is Problem Set 8, Problem 8.1, verbatim. Recall that a matching is a set of edges no two of which share an endpoint, and that for a maximization problem a 1/2-approximation must return a feasible solution with ALG ≥ (1/2) · OPT on every instance. Write M for the output and M* for a maximum matching. The instructor's 12-01 notes rewrite the goal as "WTS |M| ≥ ½|M*|", equivalently |M*| ≤ 2 · |M|, which is the form the proof establishes.
Feasibility and running time. When the algorithm adds e = {u, v} to F, it deletes every remaining edge touching u or v, so no later edge shares an endpoint with e: M is a matching. Each iteration removes at least one edge, so there are at most m iterations, each polynomial; the algorithm runs in polynomial time.
Upper bound on OPT (the assignment). "In our heads (not in ALG)", as the notes put it: for every edge e* ∈ M*, assign e* to some edge of M that shares at least one endpoint with e*. This is well defined: if some e* shared no endpoint with any edge of M, then e* would never have been removed from G (edges are removed only when they touch a chosen edge), so the loop could not have stopped while e* was still there; equivalently, M ∪ {e*} would be a matching and the algorithm should not have returned M.
Counting. Each edge e = {u, v} ∈ M is assigned at most two edges of M*: an edge of M* assigned to e contains u or v, and because M* is a matching, at most one edge of M* contains u and at most one contains v. Every edge of M* is assigned exactly once, so counting over the edges of M gives |M*| ≤ 2 · |M|.
Conclusion. |M| ≥ (1/2) · |M*| on every instance, so ALG is a 1/2-approximation algorithm. ∎
The bound is tight: on the path 1 − 2 − 3 − 4, the algorithm may pick the middle edge {2, 3} first (green), which deletes both other edges and returns one edge, while {1, 2}, {3, 4} is a matching of size 2.
Problem 5. Shortest paths with at most 10 edges
Solution
Idea. The instructor's summary: "Bellman-Ford except we can use ≤ 10 edges per path". The original Bellman-Ford (the version with a full table, not the space-saving Bellman-Ford-2) already solves exactly this subproblem in its column j, so run it for 10 rounds instead of n − 1 and return column 10.
Subproblems. For every v ∈ V and j ∈ {0, 1, …, 10}, OPT[v][j] is the length of a shortest s-v path that uses at most j edges (∞ if there is none). We return OPT[·][10].
Recurrence. Base case: OPT[s][0] = 0 and OPT[v][0] = ∞ for v ≠ s. For j ≥ 1:
OPT[v][j] = min( OPT[v][j−1], min(u, v) ∈ E OPT[u][j−1] + ℓ(u, v) ).
Algorithm.
ALG(G, s):
d = [inf]*(n * 11); d[s][0] = 0
# columns of d range from j = 0 to 10
G^R = reverse of G
for j = 1, ..., 10:
for v in V:
d[v][j] = d[v][j-1]
for u in G^R[v]:
d[v][j] = min(d[v][j], d[u][j-1] + l(u,v))
return d[.][10] # last column of d
Correctness. This is Bellman-Ford's own correctness argument, stopped at j = 10. A shortest s-v path P with at most j edges either has at most j − 1 edges, in which case its length is OPT[v][j−1], or has exactly j edges and ends with some edge (u, v); then the part of P before that edge is an s-u path with at most j − 1 edges, and it must be a shortest one (otherwise replacing it would shorten P), so P has length OPT[u][j−1] + ℓ(u, v). The recurrence takes the minimum over all of these cases, which are exhaustive, so by induction on j every entry d[v][j] equals OPT[v][j]. In particular d[u][10] is the shortest length among paths with at most 10 edges, and it stays ∞ exactly when no such path exists.
Running time. Computing GR takes O(m + n). Each column relaxes every edge once (vertex v scans its in-neighbours, and the in-degrees sum to m), so one column costs O(m) in the course's accounting, exactly as one round of Bellman-Ford. There are 11 = O(1) columns, so the total is O(m). (Bellman-Ford itself is O(mn) only because it computes n − 1 columns.)
Problem 6. Minimizing the heaviest edge of a spanning tree
Solution
The notes call this "MST but we want to minimize maxe∈T w(e) (rather than Σe∈T w(e))", with the aside "≈ Load Balancing": the objective is a maximum, like a makespan, instead of a sum.
Algorithm. Return an ordinary minimum spanning tree: T = Prim(G). (Kruskal or Reverse-Delete work equally well.)
Correctness. Let T be the MST returned, e the heaviest edge of T, T* an optimal solution for the new problem, and e* the heaviest edge of T*. It suffices to show w(e) ≤ w(e*), because then T is at least as good as T*. Suppose for contradiction that w(e) > w(e*).
- Every edge of T* weighs at most w(e*) < w(e), so e ∉ T*.
- T* is a spanning tree and e is not in it, so adding e to T* creates a cycle C.
- Every edge of C other than e lies in T*, so it weighs at most w(e*) < w(e): e is the heaviest edge of C.
- By the cycle property ("for any cycle C in G, the heaviest edge in C is not in the MST of G"), e is not in the MST. But e ∈ T and T is the MST (unique, since the weights are distinct). Contradiction. ∎
Running time. All three MST algorithms in the notes run in O(m²): Prim makes n − 1 iterations of O(m) each, O(mn), and n − 1 ≤ m because G is connected, so O(mn) = O(m²).
Example. On the Problem 1 graph made undirected, the MST from 1(c) is {1, 3}, {3, 4}, {2, 3}, whose heaviest edge weighs 3. No spanning tree can do better: vertex 2 must be connected by one of its edges, which weigh 6, 3 and 8.
Problem 7. Skipping the next B[i] elements
A = [3, 4, 4, 2], B = [2, 3, 4, 5] -> ALG should return 5 (3+2)
A = [1, 2, 3, 4, 5], B = [1, 2, 3, 4, 5] -> ALG should return 7 (2+5)
A = [3, 3, 3, 3], B = [2, 2, 5, 4] -> ALG should return 6 (A[1] + A[4])
Solution
The official solution notes this is LeetCode 2140 and that it is "similar to 0/1 Knapsack": each element is either excluded or included, and including it has a consequence for what follows. Because choosing A[i] restricts the elements after i, the natural subproblems are suffixes.
Subproblems. For all i ∈ {1, …, n}, OPT[i] is the maximum feasible sum using only A[i : n] (the suffix A[i], …, A[n]). We return OPT[1]. For convenience OPT[j] = 0 for every j > n (the empty suffix).
Recurrence. Base case: OPT[n] = max(A[n], 0) (take A[n] unless it is negative). For i = n − 1, …, 1:
OPT[i] = max( OPT[i + 1], A[i] + OPT[i + B[i] + 1] ).
Algorithm.
ALG(A, B):
d = [max(A[n], 0)]*n
for i = n-1, ..., 1:
if i+B[i]+1 <= n:
d[i] = max(d[i+1], A[i] + d[i+B[i]+1])
else: # skipping runs past the end
d[i] = max(d[i+1], A[i])
return d[1]
Correctness. The optimal solution for A[i : n] either excludes A[i] or includes it, and these two cases are exhaustive. If it excludes A[i], it is any feasible subsequence of A[i + 1 : n], so its best value is OPT[i + 1]. If it includes A[i], it must skip A[i + 1], …, A[i + B[i]], and the rest of it is any feasible subsequence of A[i + B[i] + 1 : n] (the restrictions of later elements only point further right), so its best value is A[i] + OPT[i + B[i] + 1], which is just A[i] when i + B[i] + 1 > n. The recurrence takes the better case. OPT[i] depends only on entries with larger indices, so the loop runs from i = n − 1 down to 1, and every entry it reads is already correct.
Running time. n − 1 iterations, each O(1), so O(n).
Example. For A = [3, 4, 4, 2], B = [2, 3, 4, 5], filled right to left:
| i | 4 | 3 | 2 | 1 |
|---|---|---|---|---|
| A[i], B[i] | 2, 5 | 4, 4 | 4, 3 | 3, 2 |
| i + B[i] + 1 | (base) | 8 > n | 6 > n | 4 |
| d[i] | 2 | max(2, 4) = 4 | max(4, 4) = 4 | max(4, 3 + d[4]) = 5 |
So d = [5, 4, 4, 2] and ALG returns 5 = 3 + 2. For the second example the same procedure gives d = [7, 7, 5, 5, 5] and returns 7; for the third, d = [6, 3, 3, 3] and it returns 6.
Problem 8. Greedy independent set and the maximum degree
ALG(G):
S = empty set
while G has >= 1 vertex:
u = any vertex in G
add u to S and remove u (and its neighbors) from G
return S
Is this a 1/∆-approximation algorithm? Prove it, or give a counterexample and explain. (The first word of your answer should be "Yes" or "No".)Solution
Yes. Write S for the output and OPT for a maximum independent set. We must show S is independent and |S| ≥ |OPT|/∆, which the notes write as "WTS |S| ≥ (1/∆)|S*|", equivalently |OPT| ≤ ∆ · |S|.
Feasibility. When u is added to S, all of its neighbours are removed from G, so no vertex added later is adjacent to u: S is an independent set. Each iteration removes at least one vertex, so the algorithm runs in polynomial time.
Upper bound on OPT. For every u ∈ S, let Su be the set of vertices removed from G in the iteration that added u (u itself and its neighbours still present at that time). The sets Su are disjoint, and they cover V: every vertex is removed in some iteration, since the loop runs until G is empty. In particular every v ∈ OPT lies in exactly one Su (the notes: "assign v to the Su that contains v").
Each Su holds at most ∆ vertices of OPT. Su consists of u and at most deg(u) ≤ ∆ neighbours of u. If u ∈ OPT, no neighbour of u is in OPT (OPT is independent), so |OPT ∩ Su| = 1 ≤ ∆. If u ∉ OPT, then OPT ∩ Su contains only neighbours of u, so |OPT ∩ Su| ≤ ∆.
Conclusion.
|OPT| = Σu∈S |OPT ∩ Su| ≤ Σu∈S ∆ = ∆ · |S|,
so |S| ≥ |OPT|/∆ on every instance, and the algorithm is a 1/∆-approximation algorithm. ∎
The ratio cannot be improved: on a star with centre c and ∆ leaves, the algorithm may pick c first, which removes everything and returns |S| = 1, while the ∆ leaves (shaded) form an independent set of size ∆.
Where the 40 points come from
| Problem | Topic | Course chapter (guide chapter) | Where the points come from |
|---|---|---|---|
| 1(a) | Maximum flow value | Ch 6 (Chapter 8) | Ford-Fulkerson, or a flow and a cut of equal value: 7 |
| 1(b) | DFS post-values | Ch 2 (Chapter 3) | Clock ticking at every pre and post, smallest label first |
| 1(c) | Prim edge order | Ch 3 (Chapter 4) | Lightest edge crossing S, in the order chosen |
| 1(d) | LIS array d | Ch 4 (Chapter 5) | d[i] = longest increasing subsequence ending at i |
| 1(e) | 0/1 Knapsack last row | Ch 4 (Chapter 6) | Full table, rows i = 1..n, columns 0..B |
| 2(a) | Fractional Knapsack x | Ch 3 (Chapter 4) | Sort by v/w, fill greedily, list x in index order |
| 2(b) | Edit distance | Ch 4 (Chapter 5) | Two moves, or the DP table |
| 2(c) | Load Balancing makespan | Ch 8 (Chapter 9) | Greedy in the given order, smallest load first |
| 2(d), 2(e) | Approximation ratios | Ch 8 (Chapter 9) | Direction of the inequality for minimization and maximization |
| 3 | Best stock profit (PS 4.5) | Ch 4 (Chapter 5) | Running minimum; d[j] = A[j] − mini<j A[i]; O(n) |
| 4 | Greedy matching (PS 8.1) | Ch 8 (Chapter 9) | Assign each OPT edge to an ALG edge; at most 2 per ALG edge |
| 5 | Shortest paths with ≤ 10 edges | Ch 5 (Chapter 7) | Bellman-Ford's subproblem; 11 columns of O(m) each |
| 6 | Minimum bottleneck spanning tree | Ch 3 (Chapter 4) | Return the MST; contradiction via the cycle property; O(m²) |
| 7 | Sum with skips | Ch 4 (Chapter 6) | Suffix subproblems, include or exclude A[i], fill right to left; O(n) |
| 8 | Greedy independent set | Ch 8 (Chapter 9) | "Yes"; sets Su each hold at most ∆ OPT vertices |
12. Practice final, version A
This is a new full practice final in the exact format of the real one: 40 points, 3 hours, closed-everything, on paper, eight problems worth 5 points each. Problems 1 and 2 have five one-point parts each, answered without explanation and graded without partial credit, like the short homework questions. Problems 3 through 8 are written like problem-set problems and must be answered in the course's recipe: the algorithm (an idea in a sentence or two plus pseudocode), why it is correct, and its running time; for a proof of an approximation ratio, a bound on OPT, a bound on ALG, and the conclusion. As on the real exam, at least two of Problems 3 to 8 are copied word for word from the problem sets. Set a timer for three hours, write every answer on paper inside a box of the size the worksheet gives you, and only then open the solutions.
Problem 1 (five parts, one point each, no explanation)
Solution
[4, 2, 3]. With (i, j) = (1, 7): m = ⌊8/2⌋ = 4 and A[4] = 9 > 5, so j = 3. Then m = ⌊4/2⌋ = 2 and A[2] = 4 < 5, so i = 3. Then m = 3 and A[3] = 7 > 5, so j = 2. Now i > j, the loop stops and the algorithm returns nothing, because 5 is not in A.Solution
d = [0, 1, 1, 2, 2, 3]. Processing 1 sets d[2] = d[3] = 1; processing 2 sets d[4] = d[5] = 2; processing 3 finds 5 already discovered; processing 4 sets d[6] = 3. The green edges below are the edges that discovered each vertex (the BFS tree).Solution
R = [1, 3, 2, 5, 4, 6]. DFS: Explore(1) → Explore(2) → Explore(4) → Explore(6), so post[6] = 5 and post[4] = 6; back in 2, Explore(5) finds 4 and 6 finished, so post[5] = 8 and post[2] = 9; back in 1, Explore(3) finds 5 finished, so post[3] = 11 and post[1] = 12. The post array is [12, 9, 11, 6, 8, 5], and R lists the vertices by decreasing post-value. Check: every edge, including (5, 4), points left to right in R.Solution
{2, 4}, {3, 5}, {1, 4}, {2, 3}, {3, 6}. In increasing weight: 1 {2, 4} added; 2 {3, 5} added; 3 {1, 4} added; 4 {2, 3} added (it joins {1, 2, 4} to {3, 5}); 5 {4, 5} rejected (4 and 5 are already connected through 2 and 3); 6 {1, 2} rejected; 7 {2, 5} rejected; 8 {3, 6} added; 9 {5, 6} rejected. The MST has weight 1 + 2 + 3 + 4 + 8 = 18.Solution
[1, 1, 1, 3, 3, 5]. Entry d[1][j] is the LPS length of the prefix A[1:j]: a, ab and abc give 1; abcb gives 3 (bcb); abcbc gives 3 (bcb or cbc); abcbca starts and ends with a, so d[1][6] = d[2][5] + 2 = 3 + 2 = 5 (acbca).Problem 2 (five parts, one point each, no explanation)
Solution
[∞, 9, 4, 1]. Column 1 is [0, 2, 3, 9] (one edge from 1). In column 2, d[3][2] = min(3, d[2][1] − 2) = 0 and d[4][2] = min(9, d[2][1] + 5, d[3][1] + 1) = min(9, 7, 4) = 4. In column 3, d[4][3] = min(4, d[2][2] + 5, d[3][2] + 1) = min(4, 7, 1) = 1. The full table, rows 1 to 4: [0, 0, 0, 0], [∞, 2, 2, 2], [∞, 3, 0, 0], [∞, 9, 4, 1]. The shortest path to 4 is 1 → 2 → 3 → 4, with 3 edges:Solution
6. A flow of value 6: send 3 along 1 → 2 → 4 → 6, 2 along 1 → 2 → 3 → 5 → 6, and 1 along 1 → 3 → 5 → 6. The cut S = {1, 2, 3} has capacity c(2, 4) + c(3, 5) = 3 + 3 = 6 (the edge (4, 3) enters S and does not count), so by the Flow-Cut Lemma no flow is larger. Ford-Fulkerson with DFS finds the same value through four augmenting paths (Δ = 2, 1, 2, 1). Below, every edge shows flow/capacity and S is shaded:Solution
1, 6, 3. From S = {1} the distances are 2, 9, 10, 15, 18, so point 6 is added. With S = {1, 6} the distances to the closest center are: point 2 → 2, point 3 → min(9, 9) = 9, point 4 → min(10, 8) = 8, point 5 → min(15, 3) = 3, so point 3 is added. The resulting maximum radius is 3 (point 5 to center 6).Solution
False. On ℓ = [1, 1, 1, 1, 1, 1, 3] with m = 3, the six short jobs give every machine load 2, and the last job makes one load 5, so ALG = 5, while OPT = 3 (the long job alone on one machine, three short jobs on each of the other two). 5/3 > 3/2. In general the ratio 2 − 1/m is reached (Problem Set 8.2), and 2 − 1/3 = 5/3.Solution
True. The edges of a matching share no endpoints, so each vertex covers at most one edge of M, and covering all |M| of them needs at least |M| vertices. This is exactly the lower bound |OPT| ≥ |M| in the course's proof that VC-Matching is a 2-approximation.Problem 3. Two-coloring a graph
Solution
This problem is identical to PS 2.4; the model answer follows the official solution.
Algorithm. Run BFS from vertex 1 with c[1] = 0. When a vertex u is processed, give every uncolored neighbor the other color 1 − c[u], and check that no already-colored neighbor has the same color as u.
ALG(G):
c = [inf]*n; c[1] = 0
Q = queue(1)
while |Q| >= 1:
u = dequeue from Q
for v in G[u]:
if c[v] = inf:
c[v] = 1 - c[u]
add v to Q
else if c[v] = c[u]:
return # an edge with equal colors: not bipartite
return c
Correctness. If ALG returns nothing, it found an edge {u, v} with c[v] = c[u]. Starting from c[1] = 0, every color was forced: a vertex's color must differ from the neighbor that discovered it, so in any valid coloring with c[1] = 0 the colors are exactly these (and swapping all colors does not help). An edge with equal forced colors means no valid coloring exists, so G is not bipartite. If ALG returns c, take any edge {u, v} and let u be the endpoint processed first. When u was processed, either v was uncolored and received 1 − c[u], or v was already colored and the check passed, so c[v] ≠ c[u]. Since G is connected, BFS colors every vertex, so c is a valid coloring.
Running time. The same as BFS: every vertex enters Q at most once, and processing u takes O(deg(u)) time, so the total is O(m + n).
Quick checks: on the 4-cycle 1–2–3–4–1 the algorithm returns c = [0, 1, 0, 1]; on a triangle, processing 2 finds its neighbor 3 with the same color 1 and returns nothing.
Problem 4. A 1/2-approximation for 0/1 Knapsack
ALG(v, w, B):
sort the items by non-increasing v[i]/w[i]
S = empty set; W = 0
for i = 1, ..., n:
if W + w[i] > B:
if v[i] > (total value of S): return {i}
return S
add i to S; W += w[i]
return S
Prove that this is a 1/2-approximation algorithm.Solution
Write v(T) for the total value of a set T, renumber the items in the sorted order, and let OPT be the value of an optimal solution. Because this is a maximization problem, we must show that ALG is feasible and ALG ≥ OPT/2.
Feasibility and the easy case. S only ever receives an item that fits, so S is feasible, and {i} is feasible because w[i] ≤ B. If the loop never finds an item that does not fit, ALG returns all n items, which is optimal. Otherwise let k be the first item with W + w[k] > B; at that moment S = {1, …, k − 1}, and ALG returns the better of S and {k}, so ALG = max(v(S), v[k]).
Upper bound on OPT. Every 0/1 solution is also a feasible solution of Fractional Knapsack on the same input (take x[i] = 1 for the chosen items and 0 elsewhere), so OPT ≤ OPTfrac. Fractional-Knapsack, which is optimal (course Section 3.4), processes the items in the same order: it takes items 1, …, k − 1 completely, because they fit, then a fraction x[k] < 1 of item k, which fills the knapsack. So
OPT ≤ OPTfrac = v(S) + x[k] · v[k] ≤ v(S) + v[k].
Bound on ALG. The larger of two numbers is at least their average: ALG = max(v(S), v[k]) ≥ (v(S) + v[k])/2.
Conclusion. ALG ≥ (v(S) + v[k])/2 ≥ OPT/2, and the algorithm runs in polynomial time (O(n log n) for the sort plus O(n) for the loop), so it is a 1/2-approximation algorithm. ∎
Why the comparison with {k} is needed: with v = [2, 100], w = [1, 100], B = 100, item 1 has the larger ratio, item 2 no longer fits, and S = {1} is worth only 2 while OPT = 100; the algorithm returns {2}, worth 100.
Problem 5. Shortest walk through a red edge
Solution
Algorithm. Build a graph G′ with two copies of every vertex: u0 means "at u, no red edge used yet" and u1 means "at u, at least one red edge used". A blue edge stays inside each copy; a red edge always lands in copy 1. Run Dijkstra from s0 and return the distance to t1.
ALG(G, s, t):
G' = graph with vertices u0, u1 for every u in V, no edges
for each edge (u,v) in G:
if (u,v) is blue:
add (u0, v0) and (u1, v1) to G', each of length l(u,v)
else: # red
add (u0, v1) and (u1, v1) to G', each of length l(u,v)
d = Dijkstra(G', s0)
return d[t1]
Correctness. No edge of G′ goes from copy 1 back to copy 0, and the only edges from copy 0 to copy 1 come from red edges. So every s0-t1 path in G′ uses at least one edge built from a red edge, and dropping the subscripts turns it into an s-t walk in G that uses at least one red edge, of the same length. Conversely, take any s-t walk in G with at least one red edge: follow it in copy 0 until its first red edge, cross to copy 1 on that edge, and stay in copy 1 afterwards; this is an s0-t1 walk in G′ of the same length. Shortest lengths therefore agree, and since all lengths are non-negative, Dijkstra correctly computes d[t1] (it stays ∞ when no such walk exists). In the example, the only s0-t1 route is s0 → a1 → t1, of length 2 + 2 = 4.
Running time. G′ has 2n vertices and 2m edges, so building it takes O(m + n) = O(n²) time, and Dijkstra on 2n vertices takes O((2n)²) = O(n²) time. Total: O(n²).
Problem 6. Is this edge in the MST?
Solution
Algorithm. Let e = {u, v}. Keep only the edges lighter than e and check whether u can still reach v; e is in the MST exactly when it cannot.
ALG(G, e):
u, v = endpoints of e
H = (V, {f in E : w(f) < w(e)}) # only the edges lighter than e
d = BFS(H, u)
return d[v] = inf # True iff v is unreachable
Correctness. If v is reachable from u in H, there is a u-v path P made of edges lighter than e, and P + e is a cycle in which e is the heaviest edge. By the cycle property, e is not in the MST, and ALG correctly returns False. If v is not reachable, let S be the set of vertices reachable from u in H, so u ∈ S and v ∉ S. Every edge crossing S has weight greater than w(e), because an edge crossing S that is lighter than e would be in H and would make its other endpoint reachable. Since e crosses S and the weights are distinct, e is the lightest edge crossing S, and by the cut property e is in the MST, so ALG correctly returns True. In the triangle example, for the weight-3 edge the other two edges form a lighter path (False), and for the weight-1 edge H has no edges at all (True).
Running time. Building H is one scan of the edges, O(m + n), and BFS takes O(m + n). Since G is connected, m ≥ n − 1, so the total is O(m).
Problem 7. Cheapest path through a grid
Solution
This is a close variant of PS 4.4 (counting obstacle-free grid paths): the same subproblems and the same "arrive from above or from the left" case split, with min and + A[i][j] in place of a sum of counts.
Subproblems. For all i ∈ {1, …, m} and j ∈ {1, …, n}, let OPT[i][j] be the minimum cost of a right/down path from (1, 1) to (i, j). We return OPT[m][n].
Recurrence. Base cases: OPT[1][1] = A[1][1]; in the first row OPT[1][j] = OPT[1][j − 1] + A[1][j], and in the first column OPT[i][1] = OPT[i − 1][1] + A[i][1], because there is only one path to those cells. For i, j ≥ 2:
OPT[i][j] = A[i][j] + min(OPT[i − 1][j], OPT[i][j − 1]).
Algorithm.
ALG(A):
d = [0] * (m rows, n columns)
d[1][1] = A[1][1]
for j = 2, ..., n: d[1][j] = d[1][j-1] + A[1][j] # first row
for i = 2, ..., m: d[i][1] = d[i-1][1] + A[i][1] # first column
for i = 2, ..., m:
for j = 2, ..., n:
d[i][j] = A[i][j] + min(d[i-1][j], d[i][j-1])
return d[m][n]
Correctness. Every path to (i, j) with i, j ≥ 2 pays A[i][j] and arrives either from (i − 1, j) or from (i, j − 1); these two cases are exhaustive. In the first case the rest of the path is a path to (i − 1, j), which costs at least OPT[i − 1][j], and the cheapest such path extended by one step down is feasible; the second case is symmetric. So OPT[i][j] is A[i][j] plus the cheaper case. The loops fill the table row by row, so both entries a cell depends on are ready. For the example, d = [[1, 4, 5], [2, 7, 6], [6, 8, 7]], and the algorithm returns 7 (path 1 → 3 → 1 → 1 → 1).
Running time. The table has mn entries, each computed in O(1) time, so the total is O(mn).
Problem 8. Cutting the flow with k edges
Solution
This problem is identical to PS 6.2; the model answer follows the official solution.
Algorithm. Find a minimum s-t cut S with Ford-Fulkerson and return any k edges leaving S (all of them, if fewer than k leave S).
ALG(G, s, t, k):
S = Minimum-st-Cut(G, s, t); F = empty list
for (u,v) in E:
if u in S and v not in S:
add (u,v) to F
return F[1:k]
Correctness. By the max-flow min-cut theorem, in any graph the maximum s-t flow value equals the minimum s-t cut capacity, so decreasing the flow value as much as possible is the same as decreasing the minimum cut capacity as much as possible. With unit capacities, removing one edge lowers the capacity of any cut by at most 1, so after removing k edges the minimum cut has capacity at least c(S) − k (and at least 0). Removing k edges leaving the minimum cut S achieves exactly max(c(S) − k, 0), because S itself then has that capacity. So the algorithm's choice is optimal.
Running time. Every capacity is 1, so the maximum flow value is at most n − 1 (at most one unit leaves s along each of its at most n − 1 edges), and Ford-Fulkerson takes O(mv) = O(mn) time; Minimum-st-Cut adds one O(m + n) search of the final residual graph. Scanning E takes O(m). Total: O(mn).
13. Practice final, version B
This is a second full practice final in the exact format of the real one: 40 points in 3 hours, eight problems worth 5 points each, closed-everything, written on paper inside boxes. Problems 1 and 2 have five one-point parts each, answered without explanation and graded without partial credit; every part uses a different algorithm, and together they touch course Chapters 1 through 6 and 8. Problems 3 to 8 are written in the course's official phrasing and graded like problem-set problems. As on the real final, two of them are copied word for word from problem sets (the solutions say which), and one more is a close variant of a problem-set problem. Set a timer for three hours, write every answer on paper first, and only then open the solutions. Version A (Chapter 12) uses different problem-set problems, so the two versions can be taken in either order.
Problem 1 (five parts, one point each, no explanation)
Parts (b), (c) and (e) refer to the directed graph below, in which the number on each edge is its weight (or length).
Solution
5, 8, 9 (and the algorithm returns nothing). Start with (i, j) = (1, 10): m = ⌊11/2⌋ = 5 and A[5] = 16 < 60, so i = 6. Then m = ⌊16/2⌋ = 8 and A[8] = 56 < 60, so i = 9. Then m = ⌊19/2⌋ = 9 and A[9] = 72 > 60, so j = 8. Now i > j and the loop stops.Solution
pre = [1, 2, 10, 3, 5, 4], post = [12, 9, 11, 8, 6, 7]. Explore(1) visits 2 first (smaller label than 3); from 2 the only out-neighbour is 4, from 4 it is 6, from 6 it is 5; the edge (5, 4) leads to an explored vertex, so 5, 6, 4 and 2 finish at times 6, 7, 8, 9. Back at 1, vertex 3 is still unexplored: pre[3] = 10, all its out-neighbours 2, 4, 5 are explored, post[3] = 11, post[1] = 12.Solution
{3, 4}, {5, 6}, {1, 2}, {2, 4}. In decreasing weight order: 9 {3, 4} is on the cycle 3–4–5, removed; 8 {5, 6} is on the cycle 4–6–5, removed; 7 {1, 2} is on the cycle 1–2–3, removed; 6 {2, 4} is on the cycle 2–4–5–3, removed; 5 {4, 6} is now the only edge at 6, kept; 4, 3, 2, 1 are all kept because the remaining five edges form a spanning tree. The edges that remain, {4, 5}, {1, 3}, {2, 3}, {3, 5}, {4, 6} (total weight 15), are exactly the edges Kruskal would pick.Solution
[0, 3, 5, 8, 8, 9]. Row 1 (item 1 only): [0, 0, 0, 4, 4, 4]. Row 2: [0, 3, 3, 4, 7, 7], for example d[2][4] = max(4, 3 + d[1][3]) = 7. Row 3: d[3][2] = max(3, 5 + d[2][0]) = 5, d[3][3] = max(4, 5 + d[2][1]) = 8, d[3][4] = max(7, 5 + d[2][2]) = 8, d[3][5] = max(7, 5 + d[2][3]) = 9 (items 1 and 3).Solution
1, 3, 2, 5, 4, 6. After processing 1: d[2] = 7, d[3] = 2. Add 3: d[2] = min(7, 2 + 3) = 5, d[4] = 11, d[5] = 6. Add 2 (d = 5): d[4] = min(11, 5 + 6) = 11. Add 5 (d = 6): d[4] = min(11, 6 + 1) = 7. Add 4 (d = 7): d[6] = 12. Add 6. Final d = [0, 5, 2, 7, 6, 12].Problem 2 (five parts, one point each, no explanation)
Solution
S = {1, 2, 3}, c(S) = 8. The edges leaving S are (2, 4) with capacity 3, (3, 4) with capacity 1 and (3, 5) with capacity 4, total 8. A flow of value 8 exists (3 units on 1–2–4–6, 1 unit on 1–3–4–6, 4 units on 1–3–5–6), so by the Flow-Cut Lemma both are optimal. In the final residual graph, 1 still reaches 2 and 3 (through the unsaturated edges (1, 2), (1, 3), (2, 3)), but every edge leaving {1, 2, 3} is saturated. Every other s-t cut has capacity at least 10.Solution
[1, 1, 3, 3, 3, 3, 5]. d[1][j] is the LPS length of A[1:j]: a (1), ab (1), aba (3), abac, abacd, abacdb (still 3, for example aba), and the whole string abacdba has abcba, so d[1][7] = d[2][6] + 2 = 3 + 2 = 5.Solution
8. Loads after each job: [2, 0, 0], [2, 4, 0], [2, 4, 3], [7, 4, 3], [7, 4, 4], and the last job (length 4) sees a tie between machines 2 and 3 (both 4), goes to machine 2: [7, 8, 4]. (The optimum is 7, for example {5, 2}, {4, 3}, {4, 1}.)Solution
False. A 2-approximation algorithm must return at most 2 · OPT = 2 · 3 = 6 vertices on that graph.Solution
False. Take edges (s, a), (a, t), (s, t), all of capacity 1: the maximum flow is 2. After adding 1 to every capacity it is 4, an increase of 2. (The minimum cut {s} has two edges, and each gains 1.)Problem 3. Heaviest connected set in a tree
Solution
Subproblems. For every u ∈ V, let Tu be the subtree rooted at u, and let OPT[u] be the maximum weight of a connected set S ⊆ Tu that contains u. We return maxu∈V OPT[u].
Recurrence. If u is a leaf, OPT[u] = w[u]. Otherwise
OPT[u] = w[u] + Σv∈T[u] max(0, OPT[v]).
Algorithm. Children must be finished before their parent, so we process V in reverse topological order (leaves first), as MIS-Tree does in the notes.
ALG(T, w):
d = [0]*n
sort V in reverse topological order # children before parents
for u in V:
d[u] = w[u]
for v in T[u]:
d[u] += max(0, d[v]) # attach T_v's best part, or skip it
return max(d)
Correctness. Why the answer is max OPT[u]: every connected set S has exactly one vertex u closest to the root (if two vertices of S were both closest, the path between them would pass through a vertex of S closer to the root). Then S ⊆ Tu and u ∈ S, so w(S) ≤ OPT[u]; conversely each OPT[u] is the weight of a connected set. Why the recurrence holds: let S be a connected set in Tu containing u. For each child v, the part S ∩ Tv is either empty, or it contains v (the path from any of its vertices to u passes through v) and is itself connected, so its weight is at most OPT[v]. These cases are exhaustive, and the choices for different children are independent, because u together with any connected sets containing some of its children is again connected. So the best choice is to take, for each child v, the optimal set of Tv when OPT[v] > 0 and nothing otherwise, which is the recurrence. On the example: d[4] = 3, d[5] = −4, d[6] = 4, d[2] = 5 + 3 + 0 = 8, d[3] = −1 + 4 = 3, d[1] = −2 + 8 + 3 = 9; with w[1] = −10, d[1] = 1 and max(d) = d[2] = 8.
Running time. A reverse topological order of a tree takes O(n) time (Topological-Sort on n vertices and n − 1 edges, reversed). The loop handles each vertex once and each child once, Σu |T[u]| = n − 1, at O(1) each; max(d) is O(n). Total O(n).
This is a fresh problem in the style of Section 4.6 of the notes (Independent Set in Trees). Unlike MIS, one subproblem per vertex suffices, because the "includes u" requirement already does the work that OPTin does there, as in LIS.
Problem 4. Sorted Load Balancing is a 3/2-approximation
ALG(l, m):
sort the jobs l in non-increasing order
for i = 1, ..., n:
j = machine with smallest current load
assign job i to machine j
Prove that this is a 3/2-approximation algorithm.Solution
This is Problem 8.3 from Problem Set 8, word for word (it was also Problem 1 of the Chapter 8 Day 2/2 worksheet). The proof reuses the analysis of Section 8.2 of the notes with one extra lower bound.
Setup. After sorting, ℓ[1] ≥ ℓ[2] ≥ ⋯ ≥ ℓ[n]. Let T be the makespan of ALG, let i be a machine whose load is T, let k be the last job assigned to i, and let T* be the optimal makespan. The assignment is feasible (every job goes to some machine) and the running time is polynomial (sorting plus n iterations of O(m) each).
Lower bounds on OPT. (1) T* ≥ (1/m) Σj ℓ[j], because the largest load is at least the average load. (2) T* ≥ ℓ[k], because OPT puts job k on some machine. (3) If n ≥ m + 1, then T* ≥ 2 · ℓ[m+1]: among the first m + 1 jobs, OPT must put two on the same machine (pigeonhole), and each of them has length at least ℓ[m+1] because ℓ is sorted.
Bound on ALG. Case 1: k is the only job on machine i. Then T = ℓ[k] ≤ T* by (2). Case 2: machine i had a job before k. Each of the first m jobs is assigned to an empty machine (an empty machine has load 0, the smallest possible, and all lengths are positive), so a job that joins a non-empty machine has index k ≥ m + 1, and therefore ℓ[k] ≤ ℓ[m+1] ≤ T*/2 by (3). When k was assigned, machine i had the smallest load, T − ℓ[k], so at the end every machine has load at least T − ℓ[k], which gives Σj ℓ[j] ≥ m(T − ℓ[k]). Rearranging and using (1):
T ≤ 1m Σj=1n ℓ[j] + ℓ[k] ≤ T* + T*2 = 32 T*.
Conclusion. In both cases T ≤ (3/2) T*, so sorting first turns the 2-approximation of the notes' Section 8.2 into a 3/2-approximation algorithm. ∎
Problem 5. Shortest even walk
Solution
This is Problem 5.3 from Problem Set 5, word for word.
Algorithm. Build a graph G′ that holds two copies of G, copy 0 ("an even number of edges so far") and copy 1 ("odd so far"); every edge of G switches copies. Then run Dijkstra in G′ from s0 and read off t0.
ALG(G, s, t):
G' = graph with no vertices or edges
for u in V(G):
add two vertices u0, u1 to G'
for (u,v) in E(G):
add edges (u0, v1) and (u1, v0) to G', each has length l(u,v)
d = Dijkstra(G', s0)
return d[t0]
Correctness. Every edge of G′ goes from one copy to the other and has the length of the edge of G it came from. So an s0-t0 path in G′ crosses between the copies an even number of times, and dropping the subscripts turns it into an even s-t walk in G of the same length. Conversely, an even s-t walk (u0 = s, u1, …, u2r = t) maps to the sequence s0, (u1)1, (u2)0, …, t0 in G′ of the same length; the walk may repeat vertices of G, and if it repeats a vertex of G′, cutting out the loop gives a path in G′ that is no longer (all lengths are non-negative). So the shortest even s-t walk in G has the same length as the shortest s0-t0 path in G′, which Dijkstra computes correctly because the lengths are non-negative; if no s0-t0 path exists, d[t0] = ∞, as required. Example: with edges s→t (2), s→a (5), a→t (1), t→x (1), x→y (1), y→t (1), the direct edge is odd, and the answer is 5, the walk s, t, x, y, t.
Running time. G′ has 2n vertices and 2m edges and is built in O(m + n) time. Dijkstra (the array version from Section 5.3 of the notes) on 2n vertices takes O((2n)²) = O(n²) time. Since m ≤ n², the total is O(n²).
Problem 6. Vertices on s-t paths in a DAG
Solution
Algorithm. A vertex u lies on an s-t path exactly when s can reach u and u can reach t. Explore from s marks the first set; Explore from t in the reverse graph GR marks the second, because u reaches t in G exactly when t reaches u in GR. Count the vertices marked twice.
ALG(G, s, t):
pre, post, time = [inf]*n, [inf]*n, 1
Explore(G, s)
a = [pre[u] != inf for u in V] # a[u]: s can reach u
G^R = reverse of G
pre, post, time = [inf]*n, [inf]*n, 1
Explore(G^R, t)
b = [pre[u] != inf for u in V] # b[u]: u can reach t
count = 0
for u in V:
if a[u] and b[u]: count += 1
return count
Correctness. Explore(G, s) explores exactly the vertices reachable from s (the basic property of Explore, Section 2.2 of the course notes), so a[u] is true exactly when s reaches u, and likewise b[u] is true exactly when u reaches t. If u lies on an s-t path P, the part of P from s to u shows a[u], and the part from u to t shows b[u], so u is counted. Conversely, if a[u] and b[u], then an s-u path followed by a u-t path is an s-t walk through u; it repeats no vertex, because a repeated vertex would close a directed cycle and G is a DAG. So it is an s-t path through u, and every counted vertex is correct. If s cannot reach t, no vertex has both marks (otherwise s would reach t through it), so the algorithm returns 0, as required. On the example, s = 1 reaches {1, 2, 3, 4, 5, 6, 8}, the vertices that reach 5 are {1, 2, 3, 4, 5, 7, 8}, and the intersection has 6 vertices: 6 is a dead end and 7 is not reachable from 1.
Running time. Each Explore takes O(m + n), building GR takes O(m + n) (one pass over the adjacency lists), and the arrays and the final loop take O(n). Total O(m + n).
This problem is in the style of Problem Set 2 (Problems 2.2 and 2.5 also run a standard search and then make one linear pass). The same algorithm works for any directed graph if "path" is replaced by "walk"; the DAG assumption is what turns the walk into a path.
Problem 7. Vertex-disjoint paths
Solution
This is a close variant of Problem 6.3 from Problem Set 6 (maximum flow with vertex capacities): give every vertex and every edge capacity 1, and the maximum flow value is the answer.
Algorithm. Split every vertex u other than s and t into uin and uout joined by an edge of capacity 1, so that at most one unit of flow can pass through u, and return the value of a maximum flow from s to t.
ALG(G, s, t):
G' = ({s, t}, no edges)
for each u in V \ {s, t}:
add vertices u_in, u_out and edge (u_in, u_out) of capacity 1 to G'
for each edge (u,v) in G with v != s and u != t:
# letting s_out = s and t_in = t
add edge (u_out, v_in) of capacity 1 to G'
f = Ford-Fulkerson(G', s, t)
return |f|
(Edges entering s or leaving t lie on no s-t path, so they are skipped; this also makes (G′, s, t) a flow network in the course's sense.)
Correctness. Two directions. (Answer ≤ |f|.) Given k internally vertex-disjoint s-t paths, send one unit along the image of each path in G′ (s, uin, uout, …, t). An edge (uin, uout) is used by at most one path, because the paths share no internal vertex. An edge (uout, vin) is used by at most one path too, because two paths through the same edge (u, v) would share u or v, and one of them is internal since (s, t) ∉ E. So this is a feasible flow of value k, and k ≤ |f|. (Answer ≥ |f|.) All capacities are integers, so Ford-Fulkerson returns a flow in which every edge carries 0 or 1. Starting at s, follow edges that carry flow and delete them as you go; by conservation the walk can always continue until it reaches t, and it never visits uin twice, because the only edge leaving uin has capacity 1, so at most one unit enters it. Repeating this |f| times gives |f| paths in G′ that use disjoint vertex edges, and merging uin and uout back into u turns them into |f| internally vertex-disjoint s-t paths in G. Hence the answer equals |f|. On the example, the cut {s, a, b, cin} is crossed only by (cin, cout), so the maximum flow is 1; without the split the answer would be 2, the number of edge-disjoint paths.
Running time. G′ has 2n − 2 vertices and at most m + n edges, built in O(m + n) time. The maximum flow value is at most c({s}) ≤ n − 1, the number of edges leaving s. Ford-Fulkerson takes O(m′ · v) = O((m + n) · n) time, and since G is connected, m ≥ n − 1, so this is O(mn). The total is O(mn).
Problem 8. Nearest-point k-center
ALG(d, k):
S = {1}
for i = 1, ..., k-1:
u = point in X \ S whose distance to
its closest point in S is minimized
add u to S
return S
Is this a 2-approximation algorithm? Prove it, or give a counterexample and explain. (The first word of your answer should be "Yes" or "No".)Solution
No. The algorithm differs from the course's Metric-k-Center in one word: it adds the closest point instead of the farthest, so the new centers bunch up next to point 1.
Counterexample. Take n = 3 points on a line at positions 0, 1 and 10, with d equal to the difference of positions, and k = 2:
| d | 1 | 2 | 3 |
|---|---|---|---|
| 1 | 0 | 1 | 10 |
| 2 | 1 | 0 | 9 |
| 3 | 10 | 9 | 0 |
This is a metric, because distances between points on a line satisfy all four properties (for example 10 ≤ 1 + 9).
ALG on it. S starts as {1}. The distances to the closest center are 1 for point 2 and 10 for point 3, so ALG adds point 2 and returns S = {1, 2}. Point 3 joins the cluster of its closest center, 2, at distance 9, so ALG's maximum radius is 9.
OPT on it. S = {1, 3}: point 2 joins center 1 at distance 1, so the maximum radius is 1, and no solution has radius 0 because two centers cannot cover three points at distance 0.
Conclusion. ALG = 9 > 2 · 1 = 2 · OPT, so the algorithm is not a 2-approximation algorithm. Moving point 3 to position M makes ALG = M − 1 while OPT stays 1, so it is not an α-approximation algorithm for any constant α. (The course's farthest-point rule would add point 3 and find the optimum here.)
14. Exam strategy
The final rewards preparation more than inspiration: at least two of its six long problems are problem-set problems you can study in advance, and a quarter of its points are hand traces with a single right answer. This chapter turns that into a plan for the three hours, a table of every problem-set problem with the one idea its official solution rests on, a table for recognising which method a new problem wants, advice drawn from the official solutions on what to write when you are stuck, and a list of checks for the last fifteen minutes.
14.1 The 180-minute budget
The exam has 40 points and 180 minutes, so a point is worth about 4.5 minutes. The ten one-point parts are the cheapest points on the paper: each is a hand trace or a True/False judgement that takes two or three minutes when you know the algorithm, and none of them needs an explanation. The six five-point problems are not equal in difficulty for you: the ones copied from problem sets take much less time than a new problem if you have memorised the official solutions. The plan below therefore works in passes, cheapest points first, and is the same plan the Practice Final chapter recommends (about 25 minutes for Problems 1 and 2 together and about 25 minutes for each of Problems 3–8).
| Pass | Clock | What to do | Points at stake |
|---|---|---|---|
| 0 | 0:00–0:05 | Read all eight problems once. Mark each long problem R (recognised: a problem-set problem or a close variant), P (you can see the pattern) or N (new to you). Do not write solutions yet. | none |
| 1 | 0:05–0:30 | Problems 1 and 2: every trace and every True/False part. Write each answer in exactly the requested format and check it a second way (a cut that matches the flow, d recomputed from the definition). Skip any part that stalls you for more than 4 minutes and come back in pass 4. | 10 |
| 2 | 0:30–1:15 | The R problems, about 15 minutes each: the official solution from memory, in the three-part format, with its running-time sentence. | 10–15 |
| 3 | 1:15–2:45 | The P problems, then the N problems, about 25 minutes each. Start each one with the opening sentence from Section 14.3, then the pseudocode, then the correctness paragraph, then the running time. | 15–20 |
| 4 | 2:45–3:00 | The checks of Section 14.5 on every answer, then any skipped one-point part. | whatever the checks save |
Two rules keep the plan honest. First, never leave a long problem blank to perfect another one: the first two or three points of a problem (a correct idea, a clearly stated subproblem, the right named call) are much cheaper than the last one. Second, write inside the boxes from the first line, because "anything written outside the boxes will be ignored, even if you reference it in a box"; do your scratch work on the back of a page and copy only the final answer into the box.
Check-in 14.1. Classify each problem statement by the method it wants (use the rows of Section 14.3): (a) "The input is a rooted tree where every vertex u has a weight w(u) > 0. Return the largest total weight of a set of vertices, no two of them joined by an edge, in O(n) time." (b) "The input is (G, s, t), where G is directed, ℓ(e) ≥ 0, and some edges are red. Return the length of the shortest s-t walk that uses an even number of red edges, in O(n²) time." (c) "Return the largest number of s-t paths in a directed graph G such that no edge is used by two of the paths." (d) "Consider the following algorithm for Vertex Cover … Is this a 3/2-approximation algorithm? Prove it, or give a counterexample and explain."
Answer
(a) DP on a tree: independent set in trees, two subproblems per vertex, children before parents (Section 6.3). (b) Reduction to shortest paths: two copies of G, red edges switch copies, Dijkstra from s0, return d[t0] (the trick of PS 5.3). (c) Reduction to max flow: capacity 1 on every edge, the maximum s-t flow value is the answer, by Ford-Fulkerson. (d) Prove it or give a counterexample: the first word is "Yes" or "No", and a "No" needs an explicit instance with ALG and OPT computed.14.2 The problem-set bank
Every exam in this course so far has copied problem-set problems word for word. Midterm 1 used PS 2.1 and 3.4, Practice Midterm 1 used PS 1.4 and 2.3, Midterm 2 used PS 4.5 and 5.4, Practice Midterm 2 used PS 4.2 and 5.2, and the Practice Final used PS 4.5 and 8.1: ten copies across five exams, always exactly two per exam, and in every case the official solution says only "This is Problem k.j from Problem Set k; the solution is on Canvas/Pages". The instructor's notes of December 1 promise at least two such problems on the final. There are 35 problems in the seven problem sets, so the hour you spend memorising this table, and then the official solutions behind it, buys more expected points than any other hour of study: a problem you recognise costs 15 minutes and earns full credit, a new one costs 25 minutes and is uncertain. Each PS number links to the section of the guide that works the problem in full. The last column lists only reuse verified against the exam PDFs and the chapter pages (in-class worksheets), plus where this guide's own practice finals use the problem.
| PS | The task in one line | Target | Key idea of the official solution | Already reused |
|---|---|---|---|---|
| 1.1 | Find the repeated element of an array of length n + 1 holding 1..n | O(n) | Return sum(A) − n(n + 1)/2, or mark seen elements in a binary array B (no hashing) | |
| 1.2 | Squares of a sorted array, in sorted order | O(n) | Two pointers at both ends; write the larger square at the back of B and move that pointer | |
| 1.3 | Intersection of A (length m) and B (length n), m ≤ n | O(n log m) | Sort A, then binary-search A for each element of B | |
| 1.4 | Maximise (j − i) · min(A[i], A[j]) (the container problem) | O(n) | Two pointers from (1, n); record the value, move the shorter side inward; no skipped pair can be better | Practice Midterm 1, P2; Ch. 1 worksheet, Day 2 |
| 1.5 | Minimum difference between two elements | O(n log n) | Merge Sort, then the minimum of consecutive differences | |
| 2.1 | Diameter of a connected undirected graph | O(mn) | BFS from every vertex, keep the largest max(d); n runs of O(m) | Midterm 1, P2 |
| 2.2 | In a DAG, two vertices neither of which reaches the other, or nothing | O(m + n) | Topological order T; return the first consecutive pair (T[i], T[i + 1]) that is not an edge | Ch. 2 worksheet, Day 3 |
| 2.3 | Label the connected components of an undirected graph | O(m + n) | A BFS wrapper that restarts at each unlabelled vertex with a new label; each component costs O(a + b) | Practice Midterm 1, P3 |
| 2.4 | Is a connected graph bipartite? Return a coloring c or nothing | O(m + n) | BFS from 1 with c[1] = 0, color new neighbors 1 − c[u], return nothing on an edge with equal colors | This guide: version A, P3 |
| 2.5 | Does a DAG have more than one topological order? | O(m + n) | True if and only if some consecutive pair (T[i], T[i + 1]) of a topological order is not an edge | |
| 3.1 | k distinct elements with the largest sum (Max k-Sum) | O(n log n) | Sort decreasing, return A[1:k]; exchange an included A[j], j > k, for an excluded A[i], i ≤ k | |
| 3.2 | Order jobs to minimise the total waiting time | O(n log n) | Sort non-decreasing; swapping an adjacent pair with A[i] > A[j] lowers the total by A[i] − A[j] | Ch. 3 worksheet, Day 1 |
| 3.3 | Order jobs (p[i], d[i]) to minimise the maximum lateness | O(n log n) | Sort by deadline d; swapping an adjacent inverted pair cannot increase the maximum lateness | |
| 3.4 | New MST after the weight of a tree edge e increases | O(m + n) | Remove e, BFS in T from one endpoint to get the cut S, add the lightest edge crossing S; the cut property keeps every other tree edge | Midterm 1, P3 |
| 3.5 | Fewest dimes, nickels and pennies for t cents | O(1) | Greedy, largest coin first; a case analysis shows OPT has the same number of dimes, then of nickels | |
| 4.1 | Sum of an array, as a DP | O(n) | OPT[i] = OPT[i − 1] + A[i], OPT[1] = A[1] | |
| 4.2 | Longest increasing contiguous subarray | O(n) | OPT[i] = length ending at A[i] = 1 + OPT[i − 1] if A[i] > A[i − 1], else 1; return max(d) | Practice Midterm 2, P2 |
| 4.3 | Cheapest jumps of 1 or 2 from index 0 to n + 1 | O(n) | OPT[i] = min(OPT[i − 2], OPT[i − 1]) + A[i]; return min(d[n − 1], d[n]) | Ch. 4 worksheet, Day 3 |
| 4.4 | Number of right/down paths in an m × n grid with obstacles | O(mn) | OPT[i][j] = OPT[i − 1][j] + OPT[i][j − 1] on free cells, 0 on obstacles; first row and column are 1 until the first obstacle | This guide: version A, P7 (a variant) |
| 4.5 | Best profit A[j] − A[i] with i < j (buy and sell a stock) | O(n) | d[j] = A[j] − (running minimum of A[1..j − 1]); return max(d) | Midterm 2, P2; Practice Final, P3; Ch. 4 worksheet, Day 5 |
| 4.6 | Largest sum with no two adjacent elements | O(n) | OPT[i] = max(OPT[i − 1], A[i] + OPT[i − 2]): exclude or include A[i] | |
| 4.7 | Number of ordered ways to write n as a sum of A's and B's | O(n) | OPT[i] = OPT[i − A] + OPT[i − B] (0 for negative indices), OPT[0] = 1; the last term is A or B | |
| 5.1 | Widest paths from s in a DAG (width = smallest edge width) | O(m + n) | DAG DP: OPT[v] = max over in-neighbors u of min(OPT[u], w(u, v)), OPT[s] = ∞ | Ch. 5 worksheet, Day 1 |
| 5.2 | Shortest s-t path when exactly one edge e = (u, v) is negative | O(n²) | Remove e, Dijkstra from s and from v, return min(d′s[t], d′s[u] + ℓ(e) + d′v[t]) | Practice Midterm 2, P3; Ch. 5 worksheet, Day 3 |
| 5.3 | Shortest s-t walk with an even number of edges | O(n²) | Two copies of G with edges (u0, v1) and (u1, v0); Dijkstra from s0, return d[t0] | This guide: version B, P5 |
| 5.4 | Length of the shortest cycle (negative lengths, no negative cycle) | O(n³) | Floyd-Warshall, then the minimum of d[u][v] + d[v][u] over u ≠ v | Midterm 2, P3 |
| 6.1 | Capacity of a global minimum cut, unit capacities | O(mn²) | Fix s = 1; for every t take the minimum s-t cut and the minimum t-s cut; return the smallest | |
| 6.2 | Remove at most k edges to lower the max flow most (unit capacities) | O(mn) | Find a minimum s-t cut with Ford-Fulkerson and remove k edges leaving it (max-flow min-cut) | This guide: version A, P8 |
| 6.3 | Maximum flow with vertex capacities c(u) | O(mv) | Split u into uin → uout with capacity c(u), edges (uout, vin); run max flow and map back | Ch. 6 worksheet, Day 3 |
| 6.4 | Is there an s-t path (no repeated vertex) through u? | O(m) | Both directions for each edge, a new vertex w with edges (s, w), (t, w), all capacities 1 (vertices too); true if and only if the max u-w flow is 2 | |
| 6.5 | Baseball elimination: can team τ finish with the most wins? | O(n²v) | s → game ij (capacity g[i][j]) → teams i, j → t (capacity W − w[i]); yes if and only if the max flow equals the capacity of {s} | Ch. 6 worksheet, Day 3 (a numeric instance) |
| 8.1 | Prove greedy maximal matching is a 1/2-approximation | (proof) | Assign each e* ∈ M* to an edge of M sharing an endpoint (exists since M is maximal); each edge of M gets at most 2, so |M*| ≤ 2|M| | Practice Final, P4 |
| 8.2 | A Load Balancing instance with ALG/OPT = 2 − 1/m | (instance) | m(m − 1) jobs of length 1, then one of length m: ALG = 2m − 1, OPT = m | Ch. 8 worksheet, Day 2 |
| 8.3 | Prove sorted greedy Load Balancing is a 3/2-approximation | (proof) | If job k is alone, T = ℓ[k] ≤ T*; otherwise k ≥ m + 1, T* ≥ 2ℓ[m + 1] ≥ 2ℓ[k], so T ≤ Σℓ/m + ℓ[k] ≤ (3/2)T* | Ch. 8 worksheet, Day 2; this guide: version B, P4 |
| 8.4 | Decide Dominating Set with a 1.9-approximation for Metric k-Center | polynomial | Distance 1 along edges, 2 otherwise; answer "yes" if and only if the approximation returns radius 1 (a reduction, course Ch. 7 vocabulary) |
Three observations come out of the table. Only PS 4.5 has been reused twice; every other copied problem appeared once. Problem Set 6 (flows and cuts) is the only set never used on an exam, because no exam before the final covered course Chapter 6, and Problem Set 8 has been used once (PS 8.1). Extra context beyond the sources: this makes PS 6.1–6.5 and PS 8.2–8.3 natural candidates for the final, but that is the guide's guess, not an announcement; learn all 35. Several exam problems were close relatives rather than copies: Midterm 2, Problem 5 (one free edge) uses the two-copy graph of PS 5.3, and Midterm 2, Problem 4 (counting lists with sum t) generalises PS 4.7.
Check-in 14.2. Cover the table. For PS 2.1, PS 5.4 and PS 6.2, write the target running time and the key idea of the official solution in one line each.
Answer
PS 2.1, O(mn): run BFS from every vertex and return the largest distance found (n runs of O(m + n) = O(m) each, since G is connected). PS 5.4, O(n³): run Floyd-Warshall and return the minimum of d[u][v] + d[v][u] over all pairs u ≠ v. PS 6.2, O(mn): find a minimum s-t cut S with Ford-Fulkerson and remove any k edges leaving S; by max-flow min-cut, the max flow equals the min cut capacity.14.3 Which pattern is this problem?
A new problem on this exam is almost always an old method in disguise, and its wording and target running time say which one. The table maps the signals to the method and gives the sentence the official solutions open with, so that the first line in the box already commits you to a correct structure. Section 6.6 refines the first two rows into the course's eight DP patterns, and Section 7.6 refines the reduction row.
| Signals in the wording | Method | Opening sentence to write | See |
|---|---|---|---|
| An array, "return the maximum/minimum/number of …", target O(n) or O(n²), choices made element by element | DP on an array (prefixes, suffixes, "ends on A[i]", intervals, a budget) | "For all i ∈ {1, …, n}, let OPT[i] denote …; we will return OPT[n] (or max(OPT))." | 1.6, 6.6 |
| A rooted tree with weights, target O(n) | DP on a tree, children before parents | "For every vertex u, let OPTin[u] and OPTout[u] denote the best value in the subtree rooted at u that includes or excludes u; we fill them in reverse topological order." | 6.3, 6.5 |
| A graph, reachability, components, coloring, a DAG, target O(m + n) | Modify BFS, DFS or Topological-Sort (and scan the result once) | "Let T be a topological ordering of G." or "We run BFS from s, and whenever we process u, we …" | 3.8 |
| "Return a set/order that is optimal", target O(n log n), a natural sorting rule | Greedy with an exchange argument | "Suppose OPT ≠ ALG and the earliest difference occurs when … Let OPT′ be OPT except we replace … with …" | 1.5, 4.8 |
| Spanning trees, "is e in the MST", an edge weight changes | The cut property or the cycle property | "By the cut property, the lightest edge crossing S is in the MST." or "Since e is the heaviest edge in C, e is not in the MST (cycle property)." | 4.2, 4.5 |
| Lengths on edges, "walk/path from s to t" with an extra rule (one free edge, even length, at most k edges, a negative edge), target O(n²), O(mn) or O(n³) | Reduction to shortest paths: a new graph (two copies, a removed edge) or a truncated Bellman-Ford table | "Create a graph G′ with two copies of G (representing …), then run Dijkstra's from s0." | 1.7, 7.7 |
| Disjoint paths, assigning people to items, capacities on vertices, "remove edges to disconnect", target O(mn) or O(mv) | Reduction to max flow, min cut or bipartite matching | "We construct a network G′ as follows … and run Ford-Fulkerson; by the max-flow min-cut theorem, …" | 8.6 |
| "Consider the following algorithm … Prove that this is an α-approximation algorithm." | Approximation proof: a bound on OPT, then ALG against it | "Let M be the output of the algorithm and M* an optimal solution; we want to show |M*| ≤ 2 · |M|." | 1.8, 9.6 |
| "Is this an α-approximation? Prove it, or give a counterexample and explain." | Try a counterexample first on tiny instances (a star, a path, equal jobs); if none exists, prove it | "No. Consider the instance …; ALG returns …, while OPT …, so ALG/OPT = … > α." or "Yes. For every u ∈ S, …" | 9.6, Practice Final 8 |
14.4 What to write when stuck
The course does not publish its rubrics, so this section reads them off the remarks printed in the official solutions. There are only a few, but they are consistent. A wrong idea is capped low even when written up well: on Midterm 2, Problem 5, "A common mistake (received at most 2 points): Call Dijkstra to find the shortest s-t path P in G, then set the length of the heaviest edge in P to 0." A right idea with an incomplete argument loses points: on Midterm 1, Problem 3, "One common mistake is not explaining why every non-e edge is still in the MST." A plausible shortcut that is false is a wrong algorithm: on Midterm 1, Problem 4, "One common mistake was checking if (T[i], T[i + 1]) ∈ E for all i ∈ {1, …, n − 1}", and on Midterm 1, Problem 5, "One common mistake was adding (s + t)/2, instead of just t, to P." The cover page adds a warning about named calls: "You may also call a slightly modified version, but if your modifications are unclear, you might not get full credit." From these, and from the way the official solutions build up their answers, the guide draws the following advice.
- A correct but slower algorithm. Write it, say that it is slower, and give its true running time. The official solution to PS 4.5 does exactly this on its way to the target: "This appears to yield an algorithm that runs in O(n²) time (n subproblems, O(n) time each), but we can implement this in O(n) time by updating mini<j A[i] as j increases." PS 2.1 even says "Brute force is sufficient." A correct slow answer is a right idea that misses the target, not a wrong idea, so by the remarks above it should keep more than the 2 points a wrong idea gets.
- A clearly stated subproblem and recurrence. For a DP, the subproblem definition ("let OPT[i] denote …; we will return …"), the base case and the recurrence with its one-sentence reason are the heart of the answer; the pseudocode only fills the table. If time runs out, these three lines are the part to have written.
- A stated bound on OPT. For an approximation proof, write the bound on OPT that the proof will use (OPT ≥ |M| for any matching M, T* ≥ Σℓ[j]/m, T* ≥ ℓ[k]) and the inequality you are aiming for ("we want to show |M*| ≤ 2 · |M|"). These are the first steps of every official proof, and they show the grader the right structure even if the counting step is missing.
- The correctness sentence that names the reason. Even one sentence ("by the cut property", "because every list summing to i ends on some A[j]", "because R is a topological ordering, no later vertex can reach an earlier one") is the difference between "not explaining" and explaining.
- A clearly described modification. When you modify a named algorithm, say exactly what changes in one sentence, as the Practice Final solution does: "it suffices to run Bellman-Ford until j = 10, and return the d-values at that time."
14.5 Checks before handing in
Spend the last fifteen minutes on these checks, one answer at a time. Each one corresponds to a point that is easy to lose and quick to save.
Before handing in
- Indices start at 1 everywhere; any array that starts at 0 says so in a comment (
d = [0] * (t+1) # start at index 0). - The return value is exactly what the problem asks for: a number, an array, a list of edges, True/False or nothing (Practice Final 7: "return the sum of S, not S itself"), and LIS-style DPs return max(d), not d[n].
- Every base case is stored in the table before the loop that reads it, and the loop runs in the order the recurrence needs (right to left for suffixes).
- The running time is stated in the problem's own symbols (n, m, B, t, k, v), reaches the target, and quotes the course's bound for every named call on the size of the input passed to it.
- Every named call meets its conditions: Dijkstra needs ℓ ≥ 0, Bellman-Ford and Floyd-Warshall need no negative cycle, Topological-Sort and DAG-DP need a DAG, Two-Sum and Binary-Search need a sorted array.
- A "prove it or give a counterexample" answer starts with "Yes" or "No", and a counterexample gives the instance, ALG, OPT and the ratio.
- One-point answers have the requested format and count ("6 numbers", "starting with 0"), with ties broken towards the smallest label.
- Every answer is inside its box; nothing that matters is on scratch paper or in the margin.
15. Summary of the whole guide
This chapter collects every algorithm, running time, recipe and trap of the guide in compact form, in the order of the course chapters, with the course's own example and its answer at the end of each card so that you can test yourself: cover the answer, recompute it, and reread the linked section whenever a line does not mean something to you.
The two-page cheat sheet is the one-page version of this chapter.