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

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

ChapterTopicsCourse chapter and lecture datesOn the final?
1. How a 5-point answer is writtenthe three parts of an answer and the cover-page rules · pseudocode and calling algorithms by name · running-time analysis · loop invariants and induction · exchange argument, cut and cycle property · correctness of a dynamic program · reductions · approximation ratios and counterexamples · one-point questions and True/FalseCh. 0 (Aug 18) and the official solutions of every examYes
2. Array algorithmsMax in Array · Two Sum · Binary Search · Selection Sort · Merge Sort · the container problem · Problem Set 1 · homework-style questions · past exam problemsCh. 1 (Aug 20, 25)Yes
3. Essential graph algorithmsadjacency lists, n and m · BFS · DFS and Explore · edge classification · Find-Cycle · Topological Sort · strongly connected components · Problem Set 2 · homework-style questions · past exam problemsCh. 2 (Aug 27, Sep 1, 3)Yes
4. Greedy algorithmsMax k-Sum and the exchange argument · MST and the cut property · Prim · Kruskal · Reverse-Delete and the cycle property · Select-Intervals · Fractional Knapsack · Problem Set 3 · homework-style questions · past exam problemsCh. 3 (Sep 8, 10, 15)Yes
5. Dynamic programming Ithe DP method on Max in Array · LIS · LPS · Edit Distance · worksheet problems · homework-style questions · past exam problemsCh. 4, Sections 4.1–4.3, 4.5 (Sep 24, 29, Oct 1, 8)Yes
6. Dynamic programming II0/1 Knapsack (Knapsack-DP) · unbounded knapsack and saving space · independent set in trees · the grandchildren version · matching in a tree · the DP patterns · Problem Set 4 · homework-style questions · past exam problemsCh. 4, Sections 4.4, 4.6 (Sep 29, Oct 8, 13)Yes
7. Shortest pathsthe problem and edge relaxation · DAG-DP · Bellman-Ford · Dijkstra · Floyd-Warshall · which algorithm when · Problem Set 5 · homework-style questions · past exam problemsCh. 5 (Oct 20, 22, 27)Yes
8. Flows and cutsflow networks, flows and cuts · Ford-Fulkerson · Minimum-st-Cut and max-flow min-cut · Bipartite-Matching · Bipartite-VC · Problem Set 6 · homework-style questionsCh. 6 (Nov 5, 10, 12)Yes
9. Approximation algorithmswhat an approximation ratio is · Vertex Cover · Load Balancing · Metric k-Center · Maximum Cut · proving or refuting a ratio · Problem Set 8 · homework-style questions · past exam problemsCh. 8 (Nov 17, 19)Yes
10. Just in case: computational complexityP, NP and P vs. NP · reductions · from hardness to approximation · homework-style questionsCh. 7 (first half of Nov 17)No, context only
11. The official Practice Final, workedProblem 1 · Problem 2 · 3. stock (PS 4.5) · 4. greedy matching (PS 8.1) · 5. at most 10 edges · 6. heaviest edge of a spanning tree · 7. skipping B[i] elements · 8. greedy independent set · where the 40 points come fromPractice Final (Dec 1)Practice
12. Practice final, version AProblem 1 · Problem 2 · 3. two-coloring (PS 2.4) · 4. knapsack 1/2-approximation · 5. walk through a red edge · 6. is this edge in the MST? · 7. cheapest grid path · 8. cutting the flow with k edges (PS 6.2)All examined chaptersPractice
13. Practice final, version BProblem 1 · Problem 2 · 3. heaviest connected set in a tree · 4. sorted Load Balancing (PS 8.3) · 5. shortest even walk (PS 5.3) · 6. vertices on s-t paths in a DAG · 7. vertex-disjoint paths · 8. nearest-point k-centerAll examined chaptersPractice
14. Exam strategythe 180-minute budget · the problem-set bank · which pattern is this problem? · what to write when stuck · checks before handing inAll examsYes (how to sit it)
15. Summary of the whole guideevery definition, recurrence, running time and course example in compact form (the cheat sheet is the two-page version)All examined chaptersYes (review)

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

WhenThursday, December 10, 2026, 4:00–7:00 pm, in the usual room, Chapman Hall 211 (Section 1, the 3:30 class). Section 2, the 12:30 class, sits its final on Monday, December 7; you must attend your own section. There is a seating chart.
Format3 hours, on paper, closed-everything: no notes, electronics or communication. Bring pens or pencils and your UNC One Card. 8 problems × 5 points = 40 points. Problems 1–2: five one-point parts each, no explanation, no partial credit. Problems 3–8: problem-set style. The final is 30% of the course grade.
ScopeCourse Chapters 1–8 except 7: arrays, essential graph algorithms, greedy algorithms, dynamic programming, shortest paths, flows and cuts, approximation algorithms. Not examined: course Chapter 7 (computational complexity) and course Chapter 9 (formal methods). Guide chapter number = course chapter + 1 for course Chapters 1–8.

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".

Conventions in force on the exam and throughout this guideThe Practice Final cover page: "Unless the problem states otherwise,
  1. all algorithms refer to the ones described in the lectures/notes,
  2. you should describe your algorithms in pseudocode similar to the examples given in lectures, notes, and problem sets (e.g., no hashing allowed),
  3. array indices start at 1,
  4. the values in any array A should be listed in order from A[1] through A[n],
  5. 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").

What this guide does not contain

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 skillWhat you need to be able to doRunning time as the course states itSection
Max-in-Arraykeep a running maximum; prove it with the invariant m = max(A[1:i])O(n)2.1
Two-Sumrun the two pointers on a sorted array and return (i, j) or nothing; prove both directionsO(n)2.2
Binary-Searchlist the midpoints m it tests; say why the range halvesO(log n)2.3
Selection-Sortwrite A after each roundO(n²)2.4
Merge-Sortlist the comparisons of a merge; write the recurrence T(n) = 2T(n/2) + O(n)O(n log n)2.5
BFSfill d (∞ if unreachable) and the BFS tree; modify it (2-coloring, component labels)O(m + n)3.2
DFSfill pre and post with smallest-label ties; classify every edgeO(m + n)3.3
Exploremark every vertex reachable from u (the recursive half of DFS)part of DFS's O(m + n)3.3
Find-Cyclereturn a cycle from a back edge, or nothing; state the two directions of its proofO(m + n)3.5
Topological-Sortorder a DAG by decreasing post; use the order to solve DAG problemsO(m + n)3.6
Primlist the edges in the order chosen; justify each by the cut propertyO(mn) = O(m²)4.3
Kruskallist the edges kept in increasing weight, skipping those that close a cycleO(m log m) + m · O(n) = O(m²)4.4
Reverse-Deletelist the edges deleted in decreasing weight; justify by the cycle propertyO(m log m) + m · O(m) = O(m²)4.5
Select-Intervalssort by end time and pick greedily; write the exchange argumentO(n log n)4.6
Fractional-Knapsacksort by v[i]/w[i], fill greedily, report x in item orderO(n log n)4.7
LISfill d (LIS ending at A[i]) and return max(d), not d[n]O(n²)5.2
LPSfill the interval table from the diagonal up and return d[1][n]O(n²)5.3
Edit-Distancefill the (m + 1) × (n + 1) table with insert, delete and replaceO(mn)5.4
Knapsack-DPfill rows i = 1..n, columns 0..B, and give the last rowO(nB)6.1
DAG-DPcompute shortest (or longest, or widest) paths in topological order using GRO(m + n)7.2
Bellman-Fordfill the table d[v][j] column by column; stop early at j = kO(mn)7.3
Dijkstralist the order vertices join S and the final d; check ℓ ≥ 0 firstO(n²)7.4
Floyd-Warshallupdate the n × n table once per intermediate vertex rO(n³)7.5
Ford-Fulkersonaugment along residual paths, give the flow value; build networks for new problemsO(mv), v = max flow value8.2
Minimum-st-Cutread S off the last residual graph; quote max flow = min cutO(mv)8.3
Bipartite-Matchingbuild the s, L, R, t network and read the matching off fO(mn)8.4
Bipartite-VCturn a minimum cut S into the cover (L \ S) ∪ (R ∩ S)O(mn)8.5
Vertex-Cover approximationtake both endpoints of a remaining edge; prove |S| = 2|M| ≤ 2 · OPTpolynomial ("an analysis is not even necessary")9.2
Load-Balancing approximationassign jobs in order to the least-loaded machine; prove T ≤ 2T*polynomial9.3
Metric k-Center approximationstart with S = {1}, add the farthest point k − 1 times; prove radius ≤ 2r*polynomial9.4
Maximum Cut approximationmove single vertices while the cut grows; prove ALG ≥ OPT/2at most w(E) iterations, not polynomial in general9.5
Skill: prove an approximation ratiofeasibility, a bound on OPT, assign each OPT element to an ALG element (Practice Final 4 = PS 8.1)none needed1.8, 9.6
Skill: prove it or give a counterexamplefirst word Yes or No; a counterexample names the instance, ALG, OPT and the ratio (Practice Final 8)none needed1.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 dateCourse chapter and dayCore ideas in one lineIn this guide
08-18 (Tue)Ch. 0, Day 1/1Course plan; greedy rules for selecting intervals and their counterexamples; a first knapsack tableCh 1
08-20 (Thu)Ch. 1, Day 1/2The answer template; Max in Array, primitive operations and O-notation, proof by induction; Two Sum2.1, 2.2
08-25 (Tue)Ch. 1, Day 2/2Two Sum correctness; Binary Search; Selection Sort; Merge Sort and T(n) = 2T(n/2) + O(n); the container problem2.3–2.6
08-27 (Thu)Ch. 2, Day 1/3Graph representations, adjacency lists by default; BFS and its O(m + n) analysis3.1, 3.2
09-01 (Tue)Ch. 2, Day 2/3BFS parent pointers; DFS, Explore, pre and post; edge types; Find-Cycle3.3–3.5
09-03 (Thu)Ch. 2, Day 3/3Topological sort by decreasing post; DAG problems via the topological order (PS 2.2); strongly connected components3.6, 3.7
09-08 (Tue)Ch. 3, Day 1/3Max k-Sum and the exchange argument; waiting times (PS 3.2); MSTs, the cut property, Prim4.1–4.3
09-10 (Thu)Ch. 3, Day 2/3Kruskal; the cycle property and Reverse-Delete; selecting compatible intervals; fractional knapsack4.4–4.7
09-15 (Tue)Ch. 3, Day 3/3Midterm 1 format; Kruskal with union-find (a tangent, not examined); exchange proof for fractional knapsack; proof of the cycle property4.4, 4.5, 4.7
09-17 (Thu)Practice Midterm 1In-class practice exam on Ch. 1–3 (no worksheet)2.9, 3.10, 4.10
Tue Sep 22Midterm 1 (no lecture file)Exam on Ch. 1–3, 65 minutes2.9, 3.10, 4.10
09-24 (Thu)Ch. 4, Day 1/5The 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/5LIS parent pointers; LPS on intervals; 0/1 Knapsack5.2, 5.3, 6.1
10-01 (Thu)Ch. 4, Day 3/5Minimum-cost jumps (PS 4.3); bottom-up versus top-down (Fibonacci); Edit Distance5.4, 6.7
Tue Oct 6No class (well-being day)
10-08 (Thu)Ch. 4, Day 4/5The DP patterns; Edit Distance recap; independent set in trees6.3, 6.4, 6.6
10-13 (Tue)Ch. 4, Day 5/5Saving space; buying and selling a stock (PS 4.5); the Alice-and-Bob game; matching in a tree6.2, 6.5, 6.7
Thu Oct 15No class (fall break)
10-20 (Tue)Ch. 5, Day 1/3Single-source shortest paths; DAG DP, longest and widest paths (PS 5.1); Bellman-Ford7.1–7.3
10-22 (Thu)Ch. 5, Day 2/3Bellman-Ford-2 (space saving); Dijkstra; heaps (O(m log n), a tangent)7.3, 7.4
10-27 (Tue)Ch. 5, Day 3/3Midterm 2 format; Floyd-Warshall; one negative edge (PS 5.2); shortest walk under a cost budget7.5, 7.7
10-29 (Thu)Practice Midterm 2In-class practice exam on Ch. 4–5 (no worksheet)5.7, 6.9, 7.9
Tue Nov 3Midterm 2 (no lecture file)Exam on Ch. 4–5, 65 minutes5.7, 6.9, 7.9
11-05 (Thu)Ch. 6, Day 1/3Flow networks; why greedy augmenting fails; residual graphs and Ford-Fulkerson; minimum cuts introduced8.1, 8.2
11-10 (Tue)Ch. 6, Day 2/3Minimum s-t cut and the max-flow min-cut theorem; reductions; bipartite matching and vertex cover8.3–8.5
11-12 (Thu)Ch. 6, Day 3/3Vertex 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/2P, NP and reductions (not examined); α-approximations; Vertex Cover; greedy Load BalancingCh 10, 9.1–9.3
11-19 (Thu)Ch. 8, Day 2/2Load Balancing: sorted 3/2 (PS 8.3) and the tight instance (PS 8.2); Metric k-Center; Maximum Cut by local search9.3–9.5, 9.7
11-24 (Tue)Ch. 9, Day 1/1Formal methods: specifications, Dafny and Lean (not examined)Not covered
Thu Nov 26No class (Thanksgiving recess)
12-01 (Tue)Practice Final Exam (last class)Final exam format; the Practice Final walked throughCh 11
Thu Dec 10Final exam, 4:00–7:00 pmCh. 1–8 except 7, 3 hoursAll

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.

DayRead and doTime
1 (Fri Dec 4)Chapter 1; Chapter 8 (flows and cuts) with every check-in, ending with Problem Set 61.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 bottom3.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 cannot5 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 shaky5 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 to3 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; sleep3 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.

Key points

The recipe

Writing a Problem 3–8 answer
  1. 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.
  2. 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.
  3. 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.

Writing the algorithm but not why it worksPseudocode alone is not an answer. The request is "describe …, explain why it's correct, and analyze its running time", and each of the three clauses is graded. Even when correctness feels obvious, write the one sentence that names the reason ("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").
How this is testedProblems 3 through 8 of the final are all in this format, and at least two of them are identical to problem-set problems. The guide works every problem-set problem in its chapter in exactly this three-part layout so that you can reproduce the official solutions from memory. The Practice Final (Chapter 11) shows the mix: one array DP, one approximation proof, one modified Bellman-Ford, one MST argument, one new DP and one "Yes/No, prove it" approximation question.

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.

Key points

The recipe

Pseudocode checklist
  1. Name the procedure and its inputs exactly as the problem names them: ALG(G, s, t), ALG(A, B).
  2. Initialise every array with its size and starting value, and every set as a binary array.
  3. Prefer one named call plus a short loop over a long hand-written procedure.
  4. Keep the indexing of the problem: A[1] is the first element; loops run for i = 1, ..., n.
  5. End with return of 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.

AlgorithmWhat it returnsRunning time (notes)Guide
Max-in-Arraythe largest element of AO(n)Ch 2
Two-Sumindices (i, j), i < j, with A[i] + A[j] = t in a sorted array, or nothingO(n)Ch 2
Binary-Searchan index k with A[k] = t in a sorted array, or nothingO(log n)Ch 2
Selection-SortA sorted in increasing orderO(n²)Ch 2
Merge-SortA sorted in non-decreasing orderO(n log n)Ch 2
BFSarray d of distances (number of edges) from s; ∞ if unreachableO(m + n)Ch 3
DFSarrays pre and post (and so the DFS tree and edge classes)O(m + n)Ch 3
Exploreexplores every not-yet-explored vertex reachable from u (sets pre and post)part of DFS's O(m + n)Ch 3
Find-Cyclea directed cycle, or nothingO(m + n)Ch 3
Topological-Sorta topological ordering of a DAGO(m + n)Ch 3
Primthe MST (as a list F of edges)O(mn) = O(m²)Ch 4
Kruskalthe MSTO(m log m) + m · O(n) = O(m²)Ch 4
Reverse-Deletethe MSTO(m log m) + m · O(m) = O(m²)Ch 4
Select-Intervalsa maximum list of compatible intervalsO(n log n)Ch 4
Fractional-Knapsackarray x of fractions, at most one not in {0, 1}O(n log n)Ch 4
LISlength of a longest increasing subsequenceO(n²)Ch 5
LPSlength of a longest palindromic subsequenceO(n²)Ch 5
Edit-Distanceedit distance from A (length m) to B (length n)O(mn)Ch 5
Knapsack-DPmaximum value of a 0/1 knapsack with budget BO(nB)Ch 6
DAG-DPshortest-path distances from s in a DAGO(m + n)Ch 7
Bellman-Forddistances from s; no negative cycleO(mn)Ch 7
Dijkstradistances from s; all lengths non-negativeO(n²)Ch 7
Floyd-Warshalln × n array of all-pairs distances; no negative cycleO(n³)Ch 7
Ford-Fulkersona maximum s-t flowO(mv), v = max flow valueCh 8
Minimum-st-Cuta minimum s-t cut S (reachable from s in the last residual graph)O(mv)Ch 8
Bipartite-Matchinga maximum matching of a bipartite graphO(mn)Ch 8
Bipartite-VCa minimum vertex cover of a bipartite graphO(mn)Ch 8
Vertex-Cover approximationa vertex cover of size at most 2 · OPTpolynomialCh 9
Load-Balancing approximationan assignment with makespan at most 2 · OPT (in fact (2 − 1/m) · OPT)polynomialCh 9
Metric k-Center approximationk centers with maximum radius at most 2 · OPTpolynomialCh 9
Maximum Cut approximationa cut of weight at least OPT/2 (local search)at most w(E) iterationsCh 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ⁿ".

Calling Dijkstra where it does not applyA named algorithm comes with its conditions: Dijkstra needs non-negative lengths, Bellman-Ford and Floyd-Warshall need no negative cycle, DAG-DP and Topological-Sort need a DAG, Two-Sum and Binary-Search need a sorted array, Prim, Kruskal and Reverse-Delete need a connected undirected graph with distinct weights. Calling one outside its conditions is a wrong algorithm. Problem Set 5.2 exists precisely because a single negative edge rules out a direct call to Dijkstra.

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)
AnswerReplace 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.

Key points

The recipe

Counting a running time
  1. List the steps of the algorithm in order: preprocessing (sorting, building a new graph, a named call), the main loop(s), the final scan.
  2. 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).
  3. 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).
  4. Add the pieces and keep the largest: O(n log n) + O(n) = O(n log n).
  5. 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 structureCountBoundCourse example
one loop i = 2, …, n with O(1) bodyn − 1 iterations × O(1)O(n)Max-in-Array, most 1-D DPs
while i < j, and j − i drops by 1at most n − 1 iterationsO(n)Two-Sum, PS 1.2, PS 1.4
while the range halveslength ≤ n/2k after k roundsO(log n)Binary-Search
loop i = 1..n, inner j = i+1..nn rounds × O(n)O(n²)Selection-Sort, LIS
u ∈ V, then v ∈ G[u]Σ (1 + out-deg(u)) = n + mO(m + n)BFS, DFS, DAG-DP
two recursive calls on halves + linear mergeT(n) = 2T(n/2) + O(n)O(n log n)Merge-Sort
table with n(B + 1) entries, O(1) eachentries × time per entryO(nB)Knapsack-DP
n − 1 rounds, each relaxing m edges(n − 1) · mO(mn)Bellman-Ford
Charging n per vertex for adjacency lists"For each vertex, scan its neighbours, which takes O(n)" gives O(n²), which is a correct upper bound but misses an O(m + n) target. The notes make exactly this point about BFS: processing u "only requires O(out-deg(u)) time, and Σu∈V out-deg(u) = m, so the overall running time is O(m + n)." The same sum gives O(m) for a loop over all edges.
How this is testedEvery Problem 3–8 has a target bound in its statement, and the running-time sentence is worth roughly a point. The target is also the strongest hint about the method: O(m + n) suggests BFS, DFS, Topological-Sort or DAG-DP; O(n log n) suggests sorting first; O(n²) on a graph suggests Dijkstra; O(mn) suggests Bellman-Ford or Bipartite-Matching; O(n³) suggests Floyd-Warshall; O(nB) or O(nt) suggests a two-dimensional or budget-indexed DP.

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)
AnswerCreating 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.

Key points

The recipe

Loop invariant proof
  1. Claim. "For all i ∈ {…}, at the end of iteration i, [precise statement]."
  2. Base case. Check the claim for the first iteration directly.
  3. Inductive step. Assume the claim at the end of iteration i − 1; show what iteration i does keeps it true.
  4. 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 iA[i]m at the endmax(A[1:i])
startA[1] = 333
2133
3444
4144
5555

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."

Proving only one direction"The algorithm returns a pair that sums to t" proves only that the output is valid. The other half, "if some pair sums to t the algorithm does not stop before finding one", is where the invariant is needed, and it is the half graders check. The same applies to any "return X or nothing" problem.
How this is testedArray problems with two pointers (Two-Sum, Problem Set 1.2 and 1.4, the Practice Midterm 1 container problem) are argued this way, and so are the "return a vertex or nothing" graph problems of Chapter 3. The hand-trace version appears in Problems 1 and 2: "Suppose we run the two-pointer algorithm for Two Sum on A = [2, 3, 5, 6], t = 5. What does the algorithm return?" (Midterm 1; answer (1, 2)).

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.

i2345
A[i]92117
m
Answerm = 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.

Key points

The recipe

Exchange argument
  1. Let ALG be the greedy solution and OPT an optimal solution, both listed in the greedy order. If they agree everywhere, ALG is optimal.
  2. 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).
  3. Build OPT′ = OPT with OPT[i] replaced by ALG[i]. Show OPT′ is feasible and its value is no worse than OPT's.
  4. 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.

[1,10][9,12][11,20]

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.

Swapping without checking feasibilityThe exchange is only valid if OPT′ is still a feasible solution. In the interval-stabbing proof, the whole content is the sentence "every later interval [a, b] satisfies t ≤ b, so if [a, b] contains t*, it must also contain t". Writing "swap t* for t, which is no worse" without that sentence leaves the proof empty.
How this is testedGreedy design problems (Midterm 1, Problem 5; Practice Midterm 1, Problem 5) are proved by exchange; MST variants (Problem Set 3.4, Practice Final, Problem 6) cite the cut or cycle property. One-point traces from Chapter 4 (the order of Prim's edges, the Fractional Knapsack array x) test the same algorithms by hand.

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.

AnswerSorted, 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.

Key points

The recipe

A DP answer
  1. Subproblems. Define OPT[i] (or OPT[i][j]) in one sentence, naming the smaller input, and say which entry is returned.
  2. 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 …."
  3. Algorithm. Pseudocode that is the recurrence with OPT replaced by d, filled in a valid order, ending with the return.
  4. 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)."

i01234
termsbased[0]d[1] + d[0]d[2] + d[0] + d[1]d[3] + d[1] + d[2]
d[i]11247

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.

Recurrence without the "why"A formula alone is half an answer. In the notes' own words, the answer to "Why does the recurrence hold?" "suffices as a proof that the algorithm is correct", and it is the only correctness the grader will find in a DP solution. One sentence naming the cases ("either excludes A[i] or includes it") is enough; no sentence at all costs points.
How this is testedAt least one of Problems 3–8 is a DP: Problem Set 4.5 appeared on both Midterm 2 and the Practice Final, and the Practice Final's Problem 7 is a new DP "similar to 0/1 Knapsack". The one-point traces (the LIS array d, the last row of the Knapsack or Edit Distance table, the first row of LPS) test the same recurrences by hand.

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.

j12345
A[j]53614
d[j]−∞
Answerd = [−∞, −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.

Key points

The recipe

A reduction answer
  1. Build. Describe the new input in one sentence and in pseudocode (vertices, edges, lengths or capacities).
  2. Call. One line calling the known algorithm by name; check its conditions (non-negative lengths for Dijkstra, a DAG for DAG-DP).
  3. Translate. Return the entry or object that answers the original question (d[t0], the flow on original edges).
  4. 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."
  5. 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.

251111satxy

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.

One direction of the correspondence"Every path in G′ from s0 to t0 is an even walk in G" shows only that Dijkstra's answer is achievable. Without "conversely, every even walk is such a path" the answer might be too large, because the best even walk could have no counterpart. The official solution writes both sentences; so should you.
How this is testedExpect at least one Problem 3–8 that is solved by building a graph and calling a shortest-path or flow algorithm. Questions to ask: does a condition on the walk (parity, one free edge, at most 10 edges) suggest copies or layers? Does a vertex limit suggest splitting vertices? Does "distance to t" suggest GR? Chapter 7 and Chapter 8 work every such problem from the problem sets.

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.

Answerd1 = 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.

Key points

The recipe

Proving "ALG is an α-approximation"
  1. Feasibility. One sentence: the output is a valid solution (a cover, a matching, an assignment).
  2. Bound on OPT. A structural fact any solution must satisfy: "each vertex in OPT covers at most one edge in M, so |OPT| ≥ |M|".
  3. Bound on ALG. Express ALG's value in the same terms: "|S| = 2 · |M|".
  4. 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 1Machine 2Machine 3Makespan
ALG after the six 1s2222
ALG after the 35225
OPT3 (the long job)1 + 1 + 11 + 1 + 13

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.

51234 51234

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 α.

A counterexample whose ratio is exactly αAn instance where ALG is exactly twice OPT does not refute a 2-approximation, because the definition allows ALG ≤ 2 · OPT. Make the ratio strictly larger (for minimization) or strictly smaller (for maximization) than α, and say so with the numbers.
How this is testedThe Practice Final has two such problems: "Prove that this is a 1/2-approximation algorithm" (Problem 4, identical to Problem Set 8.1) and "Is this a 1/Δ-approximation algorithm? Prove it, or give a counterexample and explain" (Problem 8, answer Yes). Problems 1 and 2 add one-point makespan traces and True/False questions about ratios (Section 1.9). Chapter 9 proves every ratio in the course.

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.

job1234
ℓ2341
machine
AnswerMachines 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.

Key points

The recipe

Answering a one-point part
  1. Identify the algorithm and the exact array or value asked for ("the last row of d", "post-values starting with post[1]").
  2. Write the trace small in the margin of the exam page (only the box is graded).
  3. Check the answer by a second method or a sanity bound.
  4. 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).

623811234
PartQuestionAnswerHow to check
1(a)max s-t flow value7flow 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 → babc2insert b at the front (babbc), then delete one of the two adjacent b's
2(c)greedy makespan, [3, 1, 2, 3], m = 34loads 3, 1, 2, then the last 3 goes to the load-1 machine
2(d)a 2-approx for Vertex Cover is a 3-approxTrueALG ≤ 2 · OPT ≤ 3 · OPT
2(e)a 1/2-approx for Max Cut is a 1/3-approxTrueALG ≥ OPT/2 ≥ OPT/3

The solution figure shows Prim's three edges from 1(c) highlighted.

623811234

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".

Right trace, wrong formatWith no partial credit, an answer that lists post-values starting from the root instead of from post[1], writes directed edges with braces, gives 6 numbers when 5 were asked for (the Knapsack row starts at column 0), or forgets "none" scores zero even if the trace was right. Reread the question's format clause ("Your answer should be 5 numbers, starting with 0") before writing in the box.
How this is testedThe announced list for Problems 1–2 is DFS post-values, Prim's edge order, the LIS array d, the last row of the 0/1 Knapsack table, the Fractional Knapsack array x, the Edit Distance value, the max flow value and the Load Balancing makespan, plus True/False. Each chapter of this guide has a "Homework-style one-point questions" section that works one of each by hand.

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

Exercises

1.1. Midterm 1, Problem 3: G is connected and undirected with distinct weights, T is its MST, and the weight of a tree edge e increases. A student writes: "Remove e from T, run BFS from one endpoint of e in T to find the cut S, and add the lightest edge crossing S. This is correct by the cut property. Time O(m + n)." What will the grader object to, and what sentence fixes it?
SolutionThe 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."
1.2. Practice Final, Problem 6: the input is a connected undirected graph G with distinct weights w(e) > 0. Return a spanning tree T such that maxe∈T w(e) is minimized. Describe an O(m²)-time algorithm, explain why it is correct, and analyze its running time. Write the answer in the three-part format.
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²)).

1.3. Give the running time of Kruskal's algorithm as the notes analyze it, with each step's cost, and explain why the result is written O(m²).
SolutionSorting 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.
1.4. One-point trace: run the two-pointer Two-Sum algorithm on A = [1, 2, 4, 7, 11] with t = 9. What does it return?
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).
1.5. One-point trace: run the optimal greedy algorithm for Fractional Knapsack on v = [6, 4, 3], w = [3, 4, 1], B = 5. What are the values in x, starting with x[1]?
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.
1.6. One-point trace: run the 2-approximation algorithm for Load Balancing on job lengths [2, 2, 3, 1, 4] with m = 2 machines, breaking ties toward the smaller machine label. What is the makespan? What is the optimal makespan?
SolutionALG: 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.
1.7. "Is the algorithm that assigns every job to machine 1 a 2-approximation for Load Balancing? Prove it, or give a counterexample and explain." A student answers: "No. Take m = 2 and ℓ = [1, 1]. ALG puts both jobs on machine 1, makespan 2; OPT = 1. So it is not a 2-approximation." What is wrong, and what is a correct answer?
SolutionThe 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).
1.8. True or False, and correct it if false. (a) The O(nB)-time DP for 0/1 Knapsack is a polynomial-time algorithm. (b) If a 1/2-approximation algorithm for Maximum Matching runs on a graph whose maximum matching has 10 edges, it returns at least 5 edges. (c) Dijkstra's algorithm may be called on any directed graph with no negative cycle. (d) For a connected graph, O(m + n) = O(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.

Conventions from the course notes

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.

Key points

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)23456
A[i]A[1] = 38612104
m after388121212

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.

  1. 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.
  2. Base case, i = 2. In iteration 2 the algorithm sets m = max(A[1], A[2]) = max(A[1:2]).
  3. 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.

Big-O, the course's informal recipe

"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).

Counting exact operations is not what is gradedNo exam answer in this course asks for 6n + 3 or 4n − 1. What earns the running-time point is the sentence "the loop makes at most n iterations, each takes O(1) time, so the total is O(n)", plus the cost of anything done before the loop (a sort, an array allocation).
How this is testedMax-in-Array itself is too easy to be an exam problem, but it may be called by name inside a larger algorithm ("let m = Max-in-Array(A)", O(n)). The induction it teaches is the model for every "explain why it's correct" in Problems 3–8 that involves a loop: state what is true after iteration i, check the first iteration, show one iteration preserves it, and read off the answer at the last iteration.

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.

i2345
A[i]92117
m after
Answerm 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.

Key points

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:

IterationijA[i] + A[j]Compared with t = 10Action
1171 + 11 = 12too largej = 6
2161 + 10 = 11too largej = 5
3151 + 7 = 8too smalli = 2
4253 + 7 = 10equalreturn (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 \ j234
15 (step 3: found)6 (step 2: > 5, cross out column 3)8 (step 1: > 5, cross out column 4)
2911
312

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):

  1. 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.
  2. 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.
  3. 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.
  4. 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].
  5. 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].
  6. 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)."

Return indices, 1-based, smaller firstFor A = [1, 3, 4, 7], t = 10 the answer is (2, 4), not (3, 7) and not (1, 3). The homework's answer format was "i, j" with the smaller index first, or the string "nothing".
How this is testedTwo-Sum traces appeared as Problem 1(a) on both Practice Midterm 1 and Midterm 1, and as three homework questions; expect one on the final's Problem 1 or 2. In Problems 3–8, "O(n) on a sorted array" or "find a pair with a property" is the cue for two pointers; you may call Two-Sum by name, or write a modified version with a different moving rule (Section 2.6 and PS 1.2 are examples). For a design answer, always write the invariant "A[i:j] still contains a solution" and the reason the discarded index cannot be part of one.

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.

Iteration123
(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.

Key points

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):

tIterationijm = ⌊(i + j)/2⌋A[m]Action
8116344 < 8, so i = 4
824658return 5; trace "3, 5"
2116344 > 2, so j = 2
2212111 < 2, so i = 2
2322233 > 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".

  1. If the algorithm returns some m, then A[m] = t, so the answer is correct.
  2. 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.
  3. 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).

The loop runs while i ≤ j, and m rounds downWith while i < j, the call Binary-Search([5], 5) never enters the loop and wrongly returns nothing. With m rounded up, every trace answer changes: on A = [1, 3, 4, 5, 8, 9] the first m would be 4, not 3. The homework and the exam grade the exact sequence.
How this is testedHomework 1 asked for traces (the sequence of m values) on arrays of 6, 50 and 60 elements, so a trace on the final is likely; see Section 2.8 for the long ones. In design problems Binary-Search is the O(log n) building block: "sort the smaller array, then binary search once for each element of the bigger one" is PS 1.3's O(n log m) pattern. Call it by name: "if Binary-Search(A, b) returns an index".

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.

Iteration1234
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.

Key points

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 iA[i:n] beforeSmallest, at index mSwapA after round i
1[3, 1, 4, 2]1, m = 2A[1] ↔ A[2][1, 3, 4, 2]
2[3, 4, 2]2, m = 4A[2] ↔ A[4][1, 2, 4, 3]
3[4, 3]3, m = 4A[3] ↔ A[4][1, 2, 3, 4]
4[4]4, m = 4none (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.

  1. Base case, round 1. The algorithm finds the smallest element in A and swaps it with A[1], so A[1] = min(A).
  2. 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.

"After iteration k" means after the swap of round kHomework questions ask for a slice such as A[2:4] or A[10:15] after iteration k. Positions 1 through k are then the k smallest values in order; every later position holds whatever the swaps left there, which is usually not sorted. Track the swaps; do not guess.
How this is testedHomework 1 had four Selection-Sort questions (Section 2.8); a one-point "what is A after iteration 2?" fits Problem 1 or 2 of the final. In design problems you will rarely want Selection-Sort, because Merge-Sort is faster; a target of O(n²) usually comes from something else (an O(n) loop run n times).

Check-in 2.4. Write A after each iteration of Selection-Sort on A = [6, 3, 8, 1, 5].

iA[1]A[2]A[3]A[4]A[5]
1
2
3
4
5
Answeri = 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.

Key points

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):

split [4, 8, 1, 3, 2, 6, 5, 7] [4, 8, 1, 3] [2, 6, 5, 7] [4, 8] [1, 3] [2, 6] [5, 7] [4] [8] [1] [3] [2] [6] [5] [7] merge [4, 8] [1, 3] [2, 6] [5, 7] [1, 3, 4, 8] [2, 5, 6, 7] [1, 2, 3, 4, 5, 6, 7, 8]

The last merge in detail, with AL = [1, 3, 4, 8] and AR = [2, 5, 6, 7] (k = 4, n − k = 4):

StepijCompare AL[i], AR[j]AppendB after
1111, 21[1]
2213, 22[1, 2]
3223, 53[1, 2, 3]
4324, 54[1, 2, 3, 4]
5428, 55[1, 2, 3, 4, 5]
6438, 66[1, 2, 3, 4, 5, 6]
7448, 77[1, 2, 3, 4, 5, 6, 7]
after loop45none (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.

  1. Base case, n = 1. "Any array of length 1 is sorted", and the algorithm returns it.
  2. Inductive step, n ≥ 2. The inductive hypothesis (on the shorter lengths k and n − k) implies that AL and AR are both sorted.
  3. 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.
  4. 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:

  1. Base case, n = 1: k · 1 · (log 1 + 1) = k ≥ T(1).
  2. Inductive step: T(n) ≤ 2 · kn2(log n2 + 1) + cn = kn((log n − 1) + 1) + cn = kn log n + cn.
  3. Since c ≤ k, this is at most kn log n + kn = kn(log n + 1), which is the claim for n.
  4. 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.

Comparisons stop when a half runs outIn a merge trace, the pairs compared end the moment one pointer passes the end of its half. Homework 1 asked for the second through sixth compared pairs of a merge; listing a seventh pair, or comparing the leftover elements with each other, loses the point. Also write the AL element first if the question asks for that order.
How this is testedA target of O(n log n) on an unsorted array almost always means "Merge-Sort first, then one O(n) pass" (PS 1.5, and Midterm 1, Problem 5, which sorted intervals). Write 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.

AnswerThe 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.

AnswerT(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.

Key points

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) · minBest so farMove
1(1, 6)1, 25 · 1 = 55 at (1, 6)1 ≤ 2: i = 2
2(2, 6)3, 24 · 2 = 88 at (2, 6)3 > 2: j = 5
3(2, 5)3, 23 · 2 = 68 at (2, 6)3 > 2: j = 4
4(2, 4)3, 52 · 3 = 68 at (2, 6)3 ≤ 5: i = 3
5(3, 4)2, 51 · 2 = 28 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)."

Move the shorter wall, never the taller oneMoving the taller wall can discard the optimum: on A = [1, 8, 6, 2, 5, 4, 8, 3, 7] the best pair is (2, 9) with value 7 · 7 = 49, and a rule that decremented j at (1, 9) would never see it. The correctness sentence must name the shorter wall and say why every pair it still forms is worse.
How this is testedThis exact problem was Problem 2 of Practice Midterm 1, and its official solution was the single line "This is Problem 1.4 from Problem Set 1". The final promises at least two problems identical to problem-set problems, so have this answer ready word for word (the model answer is under PS 1.4 below). The lecture labels it LeetCode 42, while the official solution says LeetCode 11; the problem is the same.

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.

Iteration12345
(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

PS 1.1. The input is an array A of length n + 1; every element of {1, 2, …, n} is in A and one element appears in A twice. Describe an O(n)-time algorithm that returns the repeated element, explain why it's correct, and analyze its running time.
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

PS 1.2. The input is an array A of n distinct integers sorted in increasing order. Our goal is to return an array B such that B contains the squares of the elements of A, and B is sorted in non-decreasing order. Describe an O(n)-time algorithm for this problem, explain why it's correct, and analyze its running time. Example: If A = [−1, 0, 1, 2], the algorithm should return B = [0, 1, 1, 4].
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]²WriteB after
(1, 4, 4)1, 4B[4] = 4, j = 3[0, 0, 0, 4]
(1, 3, 3)1, 1B[3] = 1, i = 2 (tie: ≥ holds)[0, 0, 1, 4]
(2, 3, 2)0, 1B[2] = 1, j = 2[0, 1, 1, 4]
(2, 2, 1)0, 0B[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

PS 1.3. The input is (A, B), where A is an array of m distinct, positive integers, B is an array of n distinct, positive integers, and m ≤ n. Our goal is to return a list C (in any order) of the intersection of A and B. Describe an O(n log m)-time algorithm for this problem and analyze its running time.
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

PS 1.4. 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.
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

PS 1.5. The input is an array A of n distinct integers. Our goal is to return the minimum difference among every pair of elements in A. Describe an O(n log n)-time algorithm for this problem, explain why it's correct, and analyze its running time. Example: If A = [5, 1, 7, 10], ALG should return 2. (ALG should always return a positive integer.)
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:

Pair123456
Compared9, 1618, 1618, 3373, 3373, 5873, 64
Appended91618335864

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)

Practice Midterm 1, Problem 1(a). Suppose we run the two-pointer algorithm for Two Sum on A = [1, 3, 4, 7], t = 10. What does the algorithm return? (Do not explain; 1 point, no partial credit.)
Solution(2, 4). (1, 4): 1 + 7 = 8 < 10, so i = 2; (2, 4): 3 + 7 = 10, return.

Midterm 1, Problem 1(a)

Midterm 1, Problem 1(a). Suppose we run the two-pointer algorithm for Two Sum on A = [2, 3, 5, 6], t = 5. What does the algorithm return? (Do not explain; 1 point, no partial credit.)
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

Practice Midterm 1, Problem 2. 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.
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).

What to noticeAll three problems are two-pointer problems, and the 5-point one was copied from the problem set without a single word changed. Expect the final to do the same with at least two of its six long problems, so the five PS 1 statements above are worth rereading the night before.

Before moving on

Exercises

2.1. Express in Big-O form: (a) 6n + 3; (b) n(n + 1)/2; (c) 7n³ + 9n² + 5n + 12; (d) 12; (e) m log m + n log m, where m ≤ n.
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).
2.2. Run Two-Sum on A = [1, 2, 4, 7, 11, 15] with t = 18. List each (i, j) examined and the returned value.
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).
2.3. Run Binary-Search on A = [2, 4, 7, 10, 13, 19, 21, 26, 30, 35, 40] with t = 5. What is the trace, and what is returned?
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.
2.4. Write A after each iteration of Selection-Sort on A = [4, 9, 2, 7, 1, 8].
Solution
iSwapA after
1A[1] = 4 ↔ A[5] = 1[1, 9, 2, 7, 4, 8]
2A[2] = 9 ↔ A[3] = 2[1, 2, 9, 7, 4, 8]
3A[3] = 9 ↔ A[5] = 4[1, 2, 4, 7, 9, 8]
4none (7 is the minimum of A[4:6])[1, 2, 4, 7, 9, 8]
5A[5] = 9 ↔ A[6] = 8[1, 2, 4, 7, 8, 9]
6none[1, 2, 4, 7, 8, 9]
2.5. Merge Sort is about to merge AL = [2, 7, 9, 12] and AR = [3, 4, 10, 15]. List the pairs compared (AL element first). How many comparisons are made?
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].
2.6. A classmate writes Binary-Search with while i < j: instead of while i <= j:. Give an input on which the modified algorithm is wrong, and explain.
SolutionA = [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.
2.7. A student's correctness argument for Two-Sum reads: "The algorithm only returns (i, j) when A[i] + A[j] = t, so it is correct." What will the grader object to?
SolutionIt 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.
2.8. Suppose A is sorted in decreasing order (A[1] > A[2] > ⋯ > A[n]). How must Two-Sum change, and why?
SolutionKeep (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).
2.9. 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 indices (i, j, k) such that i < j < k and A[i] + A[j] + A[k] = t (or nothing if no such triple exists). Describe an O(n²)-time algorithm for this problem, explain why it's correct, and analyze its running time. Example: if A = [1, 2, 4, 7, 11] and t = 13, the algorithm may return (2, 3, 4).
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.

Key points

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".

Scanning G[u] is not free"Is (u, v) an edge?" costs O(out-deg(u)) in the adjacency-list format the exam uses, not O(1), and hashing is not allowed (the cover page says "e.g., no hashing allowed"). A loop that tests (T[i], T[i + 1]) ∈ E for every i is still O(m + n), but only because each list is scanned at most once; say so in the running-time paragraph.
How this is testedNever directly, but every graph running-time analysis on the exam ends with the sentence "processing u takes O(out-deg(u)) time, and Σu out-deg(u) = m, so the total is O(m + n)". Write it out each time.

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.

AnswerG = [[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".

Key points

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]].

12345678
StepDequeue uScan G[u]Newly setQueue after
0(start)d[1] = 0[1]
112, 4d[2] = 1, d[4] = 1[2, 4]
223, 5, 6d[3] = d[5] = d[6] = 2[4, 3, 5, 6]
345, 7d[7] = 2 (5 already seen)[3, 5, 6, 7]
436none[5, 6, 7]
557none[6, 7]
668d[8] = 3[7, 8]
77(empty)none[8]
885none[ ]

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).

12345678

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].

The worksheet graph.1234
Its BFS tree.1234

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".

Write ∞ for unreachable verticesBFS from s leaves d[v] = ∞ for every v that s cannot reach, and the answer must list it: Homework 2 accepted "[0, 1, 2, 1, inf]" for G = [[2, 4], [], [1, 2], [3], []] from vertex 1. Do not write 0, −1 or leave the entry out.
How this is testedProblem 1 asks "Suppose we run BFS on the graph above starting at vertex 1. What are the values in the d array?" (Midterm 1 and Practice Midterm 1, part b). In design problems BFS is called by name: "run BFS from every vertex" (PS 2.1), "run BFS from R[1] and check that no entry of d is ∞" (Midterm 1, Problem 4), or a slightly modified BFS that writes a label or a color instead of a distance (PS 2.3, PS 2.4).

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.

123456
v123456
d[v]
Answerd = [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. 123456

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.

Key points

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.

1234
tEventWhyCall stack after
1pre[1] = 1DFS starts at vertex 11
2pre[2] = 2first entry of G[1] = [2, 3] is unvisited1, 2
3pre[3] = 3first entry of G[2] = [3, 4] is unvisited1, 2, 3
4post[3] = 4G[3] is empty1, 2
5pre[4] = 5next entry of G[2] is 4, unvisited1, 2, 4
6post[4] = 6G[4] = [1, 3]: both already visited1, 2
7post[2] = 7G[2] exhausted1
8post[1] = 8remaining 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).

1234

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.

1543267
tEventWhyCall stack after
1pre[1] = 1DFS starts at 11
2pre[2] = 2G[1] = [2, 3, 5]: 2 unvisited1, 2
3pre[3] = 3G[2] = [3, 4]: 3 unvisited1, 2, 3
4post[3] = 4G[3] empty1, 2
5pre[4] = 5next in G[2]: 4 unvisited1, 2, 4
6post[4] = 6G[4] = [1, 3]: both visited1, 2
7post[2] = 7G[2] exhausted1
8pre[5] = 8back in G[1]: 3 visited, 5 unvisited1, 5
9post[5] = 9G[5] = [4]: visited1
10post[1] = 10G[1] exhausted(empty)
11pre[6] = 11DFS loop: 2, 3, 4, 5 visited; 6 is not6
12pre[7] = 12G[6] = [2, 3, 7]: 2, 3 visited, 7 unvisited6, 7
13post[7] = 13G[7] empty6
14post[6] = 14G[6] exhausted(empty)
v1234567
pre123581112
post1074691413

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).

1543267

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].

The clock keeps running across restartsWhen the first tree is finished, DFS continues its loop at the smallest unvisited label, and that vertex gets pre value (last post) + 1, not 1. On Homework 2's example G = [[2, 4], [], [1, 2], [3], []], vertex 5 is unreachable from 1 and receives pre[5] = 9, post[5] = 10. A second common slip is advancing the clock only on pre stamps; it ticks on post stamps too, so the largest post value is always 2n.
How this is testedThis is the final's Problem 1 trace. The Practice Final asks "Suppose we run DFS on the graph above starting at s = 1. (Ignore the label t.) As usual, break ties in favor of the vertex with the smallest label. What are the post-values (starting with post[1])?", and both midterm-1 exams asked for the post array of a five-vertex graph. Keep the call-stack table above in your head: write pre values on the way down, post values on the way back up, and check at the end that the 2n numbers 1, …, 2n each appear once.

Check-in 3.3. Run DFS on G = [[2, 4], [3], [1], [3, 5], [2], [5]] (drawn below) and fill in pre and post.

123456
v123456
pre
post
Answerpre = [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.

Key points

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 patternMeaning in T
tree or forwardpre[u] < pre[v] < post[v] < post[u]v is a descendant of u
backpre[v] < pre[u] < post[u] < post[v]v is an ancestor of u (or v = u)
crosspre[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]:

EdgeIntervals [pre, post] of u and vType
(1, 2), (2, 3), (2, 4), (1, 5), (6, 7)Explore(v) called from utree
(1, 3)[1, 10] contains [3, 4], not a tree edgeforward
(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.

Directed edges are written in the arrow's directionThe exam reminds you: "Recall that we use parentheses to specify directed edges." A back edge from 4 up to 1 is (4, 1), not (1, 4) and not {1, 4}. When an exam asks to "list the back edges", write "none" if there are none; an empty box earns nothing.
How this is testedParts d and e of Problem 1 on both midterm-1 exams: "List the back edges in any order, or write 'none'" and "List the cross edges in any order". Homework 2 asked "How many back edges are there?" on a 40-vertex graph. Back edges also drive Find-Cycle (next section): a graph is a DAG exactly when DFS finds no back edge.

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).

AnswerTree: (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. 123456

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.

Key points

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)."

Prove both directionsShowing only "a back edge gives a cycle" proves that the output is correct when there is one, but not that the algorithm finds a cycle whenever one exists. A full correctness paragraph for any "return X or nothing" algorithm has two parts: what is returned is valid, and if nothing is returned then nothing valid exists. Midterm 1's Problem 4 has the same shape: its official solution proves that a returned R[1] is valid and then proves that if nothing is returned, no vertex can reach everything.
How this is testedFind-Cycle may be called by name. Its most common use on the exam is as a yes/no test: "G is a DAG if and only if Find-Cycle(G) returns nothing", for example to check that an input is acyclic before calling Topological-Sort. A one-point part may ask you to list the back edges.

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.

Answerpre = [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.

Key points

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]].

4231
tEventR after
1pre[1] = 1 (DFS starts at 1)[ ]
2post[1] = 2 (G[1] empty)[1]
3pre[2] = 3 (restart at 2)[1]
4post[2] = 4 (1 is visited)[2, 1]
5pre[3] = 5 (restart at 3)[2, 1]
6post[3] = 6[3, 2, 1]
7pre[4] = 7 (restart at 4)[3, 2, 1]
8post[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)."

Decreasing post, not increasing preThe worksheet for Day 3/3, Problem 1: "True or False? For any DAG G, if we run DFS on G and sort the vertices by increasing pre-value, the result is always a topological order." False. Counterexample G = [[2], [], [2]]: "the pre-values are [1, 2, 5], so sorting the vertices by increasing pre-values yields [1, 2, 3], which is not a topological ordering because (3, 2) points from right to left." Decreasing post (post = [4, 3, 6]) gives [3, 1, 2], which is valid.
123
How this is testedThe lecture's hint (09-03): "Whenever input is a DAG, topo sort is usually helpful." Every DAG problem on the problem sets and the midterm-1 exams starts with "Let T be a topological ordering of V" and then looks at T[1] or at the consecutive pairs (T[i], T[i + 1]): PS 2.2, PS 2.5, Midterm 1 Problem 4 and Practice Midterm 1 Problem 4. Topological-Sort may be called by name; in Chapter 7 it is the first line of DAG-DP.

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.

v12345
post
R
Answerpre = [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.

Key points

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]].

G.12345
GR.12345
PhaseWorkResult
DFS on GRpre1 = 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 = 10post = [6, 4, 5, 8, 10]
Orderdecreasing post5, 4, 1, 3, 2
u = 5BFS in G from 5 reaches only 5 (G[5] empty)c[5] = 1
u = 4BFS in G from 4: 5 is labelled, so only 4c[4] = 2
u = 1BFS in G from 1 reaches 2, 3 (4 and 5 labelled)c[1] = c[2] = c[3] = 3
u = 3, 2already labelled, skippedc = [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].

DFS on the reverse, BFS on the originalSwapping the two graphs, or running BFS in decreasing post order of a DFS on G itself, starts from a source component and floods everything downstream into one label. In the lecture example, BFS in G from vertex 1 first would label all five vertices 1. The vertex with the largest post value in G (not GR) lies in a source SCC, which is useful for other things (Exercise 3.8) but not for labelling.
How this is testedThe worksheet asked for the output c on a five-vertex graph, a natural one-point question. The ideas also appear in design problems: "u and v are in the same SCC exactly when v is reachable from u in G and in GR" (Exercise 3.7), and "a DAG is a graph whose SCCs are single vertices". Because SCC is not on the list of callable algorithms, describe it in two lines if you need it.

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.

AnswerGR = [[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

PS 2.1. The input is a connected, undirected graph G. For any two vertices u, v, let d(u, v) denote the distance from u to v (i.e., the length of the shortest u-v path). The diameter D of G is the maximum distance in G, i.e., D = maxu,v d(u, v). Describe an O(mn)-time algorithm that returns D, briefly explain why it's correct, and analyze its running time.
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

PS 2.2. The input is a DAG G. Our goal is to return a pair of vertices (s, t) such that s cannot reach t and t cannot reach s (or nothing, if no such pair exists). Describe an O(m + n)-time algorithm for this problem, explain why it's correct, and analyze its running time.
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

PS 2.3. The input is an undirected graph G. Our goal is to return an array c of integers such that for every two vertices u and v, u and v are in the same connected component if and only if c[u] = c[v]. (Intuitively, we want to label each vertex with a "connected component number.") Describe an O(m + n)-time algorithm for this problem and analyze its running time.
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

PS 2.4. The input is a connected, undirected graph G. We say that G is bipartite if there exists an array c such that c[u] ∈ {0, 1} for every u ∈ V, and for every {u, v} ∈ E, c[u] ≠ c[v]. (Equivalently, G is bipartite if we can color every vertex either red or blue such that every edge has differently colored endpoints.) Describe an O(m + n)-time algorithm that determines if G is bipartite (in which case it should return a valid c; otherwise, it should return nothing), explain why it's correct, and analyze its running time.
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?

PS 2.5. The input is a DAG G. Describe an O(m + n)-time algorithm that returns True if G has multiple topological orders and False if G has just one topological order, explain why it's correct, and analyze its running time.
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].

v1234
pre1423
post8576

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).

From homework to the examThe exam versions are the small ones: a five-vertex picture, "What are the values in the d array?", "What are the values in the post array?", "List the back edges". Write the arrays in the order A[1] through A[n] with commas, as the cover page requires, and use "∞" (or "inf") for unreachable vertices.

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.

v12345
pre
post
Answerpre = [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], []].

12345
Midterm 1, 1(b). Suppose we run Breadth-First Search (BFS) on the graph above starting at vertex 1. What are the values in the "d" array?
Solution[0, 1, 2, 1, 2]. Vertex 1 discovers 2 and 4 (d = 1); 2 discovers 3 (d = 2); 4 discovers 5 (d = 2).
Midterm 1, 1(c). For all of the remaining subproblems, suppose we run Depth-First Search (DFS) on the graph above (exploring vertex 1 first). What are the values in the "post" array?
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].
Midterm 1, 1(d). List the back edges in any order, or write "none" if there are none. (Recall that we use parentheses to specify directed edges.)
Solutionnone. No edge points to an ancestor; consistently, the graph is a DAG.
Midterm 1, 1(e). List the cross edges in any order, or write "none" if there are none.
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. 12345

Midterm 1, Problem 2 (= PS 2.1)

Midterm 1, Problem 2. The input is a connected, undirected graph G. For any two vertices u, v, let d(u, v) denote the distance from u to v (i.e., the length of the shortest u-v path). The diameter of G is the maximum distance in G, i.e., D = maxu,v d(u, v). Describe an O(mn)-time algorithm that returns D, briefly explain why it's correct, and analyze its running time.
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

Midterm 1, Problem 4. (Recall that a vertex s can "reach" a vertex v if there exists a path from s to v, and any single vertex is a path to itself.) The input is a DAG G. Our goal is to return a vertex that can reach every vertex in G, or nothing (if no such vertex exists). Describe an O(m + n)-time algorithm for this problem, explain why it's correct, and analyze its running time. Example: If G = [[2, 3], [ ], [2]] (in adjacency list format), then ALG should return 1. If G = [[2], [ ], [2]], then ALG should return nothing.
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]].

12345
Practice Midterm 1, 1(b). Suppose we run Breadth-First Search (BFS) on the graph above starting at vertex 1. What are the values in the "d" array?
Solutiond = [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).
Practice Midterm 1, 1(c). For all of the remaining subproblems, suppose we run Depth-First Search (DFS) on the graph above (exploring vertex 1 first). What are the values in the "post" array?
Solutionpost = [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].
Practice Midterm 1, 1(d). List the back edges in any order, or write "none" if there are none. (Recall that we use parentheses to specify directed edges.)
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. 12345
Practice Midterm 1, 1(e). List the cross edges in any order, or write "none" if there are none.
Solutionnone. 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)

Practice Midterm 1, Problem 3. The input is an undirected graph G. Our goal is to return an array c of integers such that for every two vertices u and v, u and v are in the same connected component if and only if c[u] = c[v]. (Intuitively, we want to label each vertex with a "connected component number.") Describe an O(m + n)-time algorithm for this problem and analyze its running time.
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

Practice Midterm 1, Problem 4. The input is a DAG G. Our goal is to return a path (i.e., a list of vertices) in G that contains every vertex exactly once (or nothing, if no such path exists). Describe an O(m + n)-time algorithm for this problem, explain why it's correct, and analyze its running time. Example: If G = [[2, 3], [], [2]] (in adjacency list format), then the algorithm should return [1, 3, 2].
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], []].

623811234
Practice Final, 1(b). Suppose we run DFS on the graph above starting at s = 1. (Ignore the label t.) As usual, break ties in favor of the vertex with the smallest label. What are the post-values (starting with post[1])?
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. 623811234
What to noticeEvery five-point problem above is solved by one named call (BFS, Topological-Sort) followed by a linear scan, and every correctness paragraph has the same two halves: what is returned is valid; if nothing is returned, nothing valid exists. Every one-point part is a trace you can do in two minutes with the call-stack table of Section 3.3.

Before moving on

Exercises

3.1. Run BFS from vertex 1 on G = [[3], [1, 4], [2], [5], []]. What are the values in the d array?
Solutiond = [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).
3.2. Run DFS on G = [[2, 3], [4], [2, 5], [1], [], [3, 5]], breaking ties in favor of the smallest label. What are the values in the post array?
Solutionpost = [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.
3.3. For the DFS of Exercise 3.2, list the back edges and the cross edges (write "none" if there are none).
SolutionBack: (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.
3.4. What list R does Topological-Sort return on the DAG G = [[3], [1, 4], [4], [], [1, 2]]?
SolutionR = [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.
3.5. True or False? For any DAG G, if we run DFS on G and sort the vertices by increasing post-value, the result is a topological ordering. (If False, give an explicit counterexample.)
SolutionFalse. 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].
3.6. A student proves Find-Cycle correct by writing: "If (u, v) is a back edge, the tree path from v to u plus (u, v) is a cycle, so the algorithm is correct." What will the grader object to?
SolutionThe 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.
3.7. The input is (G, s), where G is a directed graph and s ∈ V. Our goal is to return the list of all vertices v such that s can reach v and v can reach s (the strongly connected component of s). Describe an O(m + n)-time algorithm for this problem, explain why it's correct, and analyze its running time.
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).

3.8. The input is a directed graph G (not necessarily a DAG). Our goal is to return a vertex that can reach every vertex in G, or nothing if no such vertex exists. Describe an O(m + n)-time algorithm for this problem, explain why it's correct, and analyze its running time.
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.

Key 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].

StepAReturnedSum
input[4, 5, 1, 7, 2]
sort decreasing[7, 5, 4, 2, 1][7, 5, 4]16
SolutionElementsSumWhat happened
OPT (a hypothetical rival){7, 4, 2}13excludes A[2] = 5 (i = 2 ≤ k) and includes A[4] = 2 (j = 4 > k)
OPT′ = OPT − A[4] + A[2]{7, 5, 4}16still 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).

"OPT′ is better" is not a proofThe grader looks for three explicit things: what was exchanged for what (A[j] out, A[i] in), why the new solution is still feasible (it still has k elements), and the inequality that makes it better (A[i] > A[j] because of the sort order). A proof that says "swapping in a bigger element helps" without these is the kind of answer that loses a point or two.
How this is testedMax k-Sum is Problem 3.1 of Problem Set 3, so its statement could appear word for word in Problems 3–8. More often the same three-step argument is reused on an ordering problem: sort by the right key, then show that two adjacent items in the wrong order can be swapped without making things worse (PS 3.2, PS 3.3 and Practice Midterm 1's Problem 5, all worked in Section 4.8 and Section 4.10).

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.

AnswerSorted, 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.

Key points

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.

174568329123456 174568329123456

Statement

Cut PropertyFor any cut S in G, the lightest edge crossing S is in the MST of G.

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.

Pick f on the cycle, not anywhere on the cutThe worksheet of September 8 asks why the following proof is wrong: "Since e is the lightest edge crossing S, and T must contain some edge f ≠ e crossing S, we can exchange f for e." The official answer: exchanging f for e might give a set of edges that is not connected. With S = {1}, vertex 1 joined to 2, 3, 4 by edges of weight 1, 2, 3, and an edge {2, 3} of weight 4, the lightest crossing edge is e = {1, 2}. If T contains {1, 4} and we take f = {1, 4}, then T + e − f leaves vertex 4 isolated. The fix, written in red in the lecture notes, is "Notice T + e contains a cycle C", and f is chosen on C.
12341234
How this is testedThe Cut Property is the justification sentence in every MST design problem: "e is the lightest edge crossing the cut S, so by the Cut Property e is in the MST." Problem 3.4 (Midterm 1's Problem 3) uses it twice, once to keep the old edges and once to add the new one; Practice Final Problem 6 uses its twin, the Cycle Property (Section 4.5).

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}.

AnswerS = {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.

Key points

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.

543211234

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:

RoundS beforeEdges crossing SChosenF 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}]
543211234

A second, longer trace on the worksheet graph of Section 4.2 shows how the candidate list grows and shrinks:

RoundS beforeEdges 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.

List the edges in the order Prim chooses themA Prim trace asks for the order of choice, and that order is not sorted by weight: the worksheet graph gives weights 1, 4, 2, 7, 3. Students who sort the MST edges by weight are really writing Kruskal's order and lose the point. Write each edge as {i, j} with i < j, the format Homework 3 required, and remember that the cover page breaks ties in favour of the smallest label (with distinct weights, ties in weight do not occur).
How this is testedPractice Final Problem 1(c): "Suppose we run Prim's algorithm on the graph above starting at s = 1 ... List the edges chosen by the algorithm in the order in which they are chosen" (worked in Section 4.10). Homework 3 asked for the second, third, tenth or last edge Prim adds. In design problems, "run Prim's" is a legal one-line call with its O(m²) running time and its correctness.

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.

132946758123456
Round12345
Edge
Weight
AnswerRounds 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. 132946758123456

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.

Key points

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.

716542839125436

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
#EdgewCan u already reach v in F?ActionComponents of (V, F) after
1{1, 4}1nokeep{1, 4}, {2}, {3}, {5}, {6}
2{2, 5}2nokeep{1, 4}, {2, 5}, {3}, {6}
3{5, 6}3nokeep{1, 4}, {2, 5, 6}, {3}
4{3, 4}4nokeep{1, 3, 4}, {2, 5, 6}
5{2, 3}5nokeep{1, 2, 3, 4, 5, 6}
6{2, 4}6yes (2–3–4)rejectunchanged
7{1, 2}7yes (1–4–3–2)rejectunchanged
8{2, 6}8yes (2–5–6)rejectunchanged
9{3, 6}9yes (3–2–5–6)rejectunchanged
716542839125436

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.

The cycle test runs on F, not on GThe question is whether u can reach v using the edges already kept. In G the endpoints of every edge can trivially reach each other (through the edge itself), so a test on G would reject everything. Running it on F is also what makes each test cost O(n) rather than O(m + n): the forest has at most n − 1 edges.
How this is testedA one-point part can ask for the order in which Kruskal adds edges (increasing weight, rejected edges omitted) or for the k-th edge it adds. In design problems, Kruskal's rule "the kept edges so far form a forest, and each new edge is the lightest one leaving its component" is the template for modified MST problems, and its correctness paragraph is the model for "why is this edge safe to add".

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}
w123456789
Action
Answerkeep, 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.

Key points

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.)

4568123109152346

Algorithm

First the property, which the notes state and prove before the algorithm.

Cycle PropertyFor any cycle C in G, the heaviest edge in C is not in the MST of G.

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
#EdgewIs G − e connected?Action
1{1, 4}10yes: 1–2–3–4delete
2{5, 6}9yes: 5–2–3–6delete
3{2, 3}8no: it is now the only link between {1, 2, 5} and {3, 4, 6}keep
4{1, 5}6yes: 1–2–5delete
5{2, 5}5no: 5 has no other edge leftkeep
6{1, 2}4no: 1 has no other edge leftkeep
7{4, 6}3yes: 4–3–6delete
8{3, 6}2nokeep
9{3, 4}1nokeep
4568123109152346

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²).

In the Cycle Property proof, e must cross the cutThe worksheet of September 15 asks why this proof is wrong: "Since f is the heaviest edge in C, and T cannot contain every edge in C, T must exclude some edge e ≠ f in C. We can exchange f for e." The official counterexample: G is the square 1, 2, 3, 4 with the diagonal {1, 3}; C is the triangle 1, 2, 3 with heaviest edge f = {1, 2}; T might be {1, 2}, {1, 4}, {3, 4}. If e = {1, 3}, then T − f + e contains the cycle 1, 3, 4, so it is not a spanning tree. The lecture called the correct choice "the 'right' f": an edge of C that crosses the cut created by removing the heavy edge from T.
1234
AlgorithmOrderRuleJustified byRunning time
Primgrows from vertex 1add the lightest edge crossing SCut PropertyO(mn) = O(m²)
Kruskalincreasing weightadd e if F + e is acyclicCut PropertyO(m log m) + m · O(n) = O(m²)
Reverse-Deletedecreasing weightremove e if G − e is connectedCycle PropertyO(m log m) + m · O(m) = O(m²)
How this is testedThe Cycle Property is the tool for showing an edge is not in the MST, which is half of many MST design problems: Practice Final Problem 6 (Section 4.10) is proved with it, and deciding whether a given edge is in the MST (Exercise 4.9) uses both properties. A Reverse-Delete trace asks for the deleted edges in order or for the remaining tree.

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.

AnswerCycle 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.

Key points

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}.

1: 9:00–10:302: 9:00–9:153: 9:30–10:054: 10:00–12:005: 10:15–11:45

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:

[1,10][9,12][11,20] [1, 10][2, 3][4, 5] [1,3][2,5] ×3[4,7][6,9][8,11][10,13] ×3[12,14]

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:

[1, 3][2, 5][4, 7][6, 8][3, 9][8, 10][9, 12]
StepInterval eLast chosen ends atStarts after it?ActionS after
1[1, 3](S empty)yesadd[1, 3]
2[2, 5]3no (2 ≤ 3)skip[1, 3]
3[4, 7]3yes (4 > 3)add[1, 3], [4, 7]
4[6, 8]7noskipsame
5[3, 9]7noskipsame
6[8, 10]7yes (8 > 7)add[1, 3], [4, 7], [8, 10]
7[9, 12]10no (9 ≤ 10)skip[1, 3], [4, 7], [8, 10]
[1, 3][2, 5][4, 7][6, 8][3, 9][8, 10][9, 12]

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).

Endpoints are includedIntervals in this course are closed: [6, 8] and [8, 10] share the number 8 and conflict. The test for adding e = [s, t] is s > (end of the last chosen interval), never s ≥. Homework 3 Q3 tests exactly this: in A = [[3, 5], [1, 2], [2, 4]], the interval [2, 4] conflicts with [1, 2], so the second interval chosen is [3, 5], not [2, 4].
How this is testedHomework 3 asked for the first, fifth and last interval chosen on a 60-interval instance (Section 4.9). In design problems the sort-by-end-time pattern reappears whenever the problem involves intervals: Midterm 1's Problem 5 (fewest points hitting every interval, Section 4.10) uses the same sort and the same "walk along until the first difference" exchange.

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.

[5, 9][1, 4][3, 6][7, 8][10, 11][2, 12]
Sorted by end
Add / skip
AnswerSorted: [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. [5, 9][1, 4][3, 6][7, 8][10, 11][2, 12]

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.

Key points

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]:

OrderItem iv[i]w[i]v[i]/w[i]Capacity beforex[i]Value addedCapacity after
121117116
21450.86141
33240.511/40.50

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.

The greedy ratio rule fails when items cannot be splitThe September 10 worksheet's Problem 3 asks for a counterexample to the same rule for 0/1 Knapsack. The official one: v = [4, 4, 7], w = [5, 5, 6], B = 10. The best ratio is item 3's 7/6, so the rule takes item 3 (weight 6), and neither other item fits in the remaining 4, for value 7. The optimal 0/1 solution takes items 1 and 2 for value 8. (Fractionally, the rule would add 4/5 of item 1 for a total value of 10.2, which is why the fractional problem is different.)

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).

Report x in item order, and sort by ratio, not by valuePractice Final Problem 2(a) asks for "the values in x (starting with x[1])". The sort reorders items only inside the algorithm; the answer lists x[1], x[2], …, x[n] for the original items. Two other ways to lose the point: sorting by v[i] alone (the most valuable item is not necessarily first; item 1 above has the largest value and goes second), and forgetting that the last item taken is usually fractional.
How this is testedPractice Final Problem 2(a) asked for the whole x array; Homework 3 asked for the optimal value as a decimal "a.bc", with the digits after c ignored (so 835.1666… is entered as 835.16, truncated, not rounded). In design problems, "call Fractional-Knapsack" is a legal subroutine, and the ε-exchange is the model for any proof that shifts a small amount from a worse option to a better one.

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.

i123
v[i]/w[i]
x[i]
AnswerRatios [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

PS 3.1. 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 exactly k distinct integers in A whose sum is as large as possible. Describe an O(n log n)-time algorithm for this problem, explain why it's correct, and analyze its running time.
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

PS 3.2. The input is an array A of n distinct, positive integers. Each integer is the processing time of a job. For any ordering of the jobs, the waiting time of job j is the sum of processing times of jobs before j in the ordering. Our goal is return an ordering of the jobs such that the sum of waiting times is minimized. Describe an O(n log n)-time algorithm for this problem, explain why it's correct, and analyze its running time. Example: If A = [5, 1, 2], then one ordering is [5, 1, 2], and the sum of waiting times is 0 + 5 + 6 = 11. But the algorithm should return [1, 2, 5] because the sum of waiting times in this order is 0 + 1 + 3 = 4.
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

PS 3.3. The input is an array A of n pairs, where the i-th pair consists of positive integers (p[i], d[i]). For any index i, we let C[i] = Σj=1i p[j] and H[i] = C[i] − d[i]. Our goal is to order the pairs such that H* = maxi=1n H[i] is minimized. (Intuitively, each pair represents a job with a processing time and a deadline, C[i] is the completion time of job i, and we want to minimize the maximum lateness.) Describe an O(n log n)-time algorithm that returns an optimal ordering, explain why it's correct, and analyze its running time. Example: If A = [(3, 4), (5, 1), (1, 3)] (in that order), then C = [3, 8, 9] and H = [−1, 7, 6], so H* = 7. It'd be better to swap the first and last pairs in A, because that leads to C = [1, 6, 9] and H = [−2, 5, 5], so H* = 5.
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

PS 3.4. The input is (G, T, e) where G is a connected, undirected graph with distinct edge weights, T is the MST of G, and e is an edge in T. Suppose w(e), the weight of e, increases. (Assume that all edge weights are still distinct.) Describe an O(m + n)-time algorithm that returns the MST of this new graph (i.e., G after increasing w(e)), explain why it's correct, and analyze its running time.
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

PS 3.5. Suppose there are an unlimited number of dimes (10 cents each), nickels (5 cents), and pennies (1 cent). We are a given a positive integer t, and we want to select the fewest number of coins such that their total value is exactly t cents. Describe an O(1)-time greedy algorithm for this problem and explain why it's correct. The algorithm should return a list [a, b, c], where a is the number of dimes, b is the number of nickels, and c is the number of pennies chosen by the algorithm. Example: If t = 17, the algorithm should return [1, 1, 2].
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.

What the Problem Set 3 solutions have in commonEach is a sort (or a fixed priority order) plus an exchange argument written in the three steps of Section 4.1. PS 3.1 exchanges one element, PS 3.2 and PS 3.3 exchange two adjacent jobs, PS 3.4 exchanges along a cut using the Cut Property, and PS 3.5 exchanges several small coins for one large coin. On the exam, name the exchange explicitly and state the inequality that makes it an improvement.

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:

RoundS beforeEdges crossing SChosen
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:

Choice123456789
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:

OrderItemvwv/wCapacity beforexValue added
115242380.67331242
218124524.8301124
3161931019.3251193
4102401318.46151240
5142171218.0821/636.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.

Doing these fastFor Prim, write the candidate list once and update it, rather than rescanning the whole graph each round. For intervals, keep only the "last end" number in your head. For knapsack, compute ratios only until the capacity runs out, and keep fractions exact (217/6) until the last step. The final's versions are smaller (four vertices, three items), so the danger is carelessness, not size.

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)

Midterm 1, Problem 3. The input is (G, T, e) where G is a connected, undirected graph with distinct edge weights, T is the MST of G, and e is an edge in T. Suppose w(e), the weight of e, increases. (Assume that all edge weights are still distinct.) Describe an O(m + n)-time algorithm that returns the MST of this new graph (i.e., G after increasing w(e)), explain why it's correct, and analyze its running time.
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

Midterm 1, Problem 5. (Recall that an "interval" is an array [s, t] of two positive integers such that s < t.) The input is an array A of n intervals. Our goal is to return a list P of (possibly non-integer) numbers such that (1) for every interval [s, t] in A, there exists at least one number p in P such that s ≤ p ≤ t, and (2) the length of P is minimized. Describe an O(n log n)-time algorithm that solves this problem, explain why it's correct, and analyze its running time. Example: If A = [[1, 10], [4, 5], [2, 3]], then one optimal solution is P = [5, 2.5].
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

Practice Midterm 1, Problem 5. The input is an array A of n elements, where each element A[i] consists of a pair of positive integers (w[i], p[i]). The "value" of an ordering of A is Σi=1n w[i]Ci, where Ci is the sum of all p[j] over j ∈ {1, …, i} in the ordering. Our goal is to order A such that the value is minimized. Describe an O(n log n)-time algorithm that returns an optimal ordering, explain why it's correct, and analyze its running time. Example: If A = [(3, 4), (5, 1), (3, 2)], then the value of A (in the original order) is 3 · 4 + 5 · (4 + 1) + 3 · (4 + 1 + 2) = 58. If we swap the first and last elements of A, the value becomes 3 · 2 + 5 · (2 + 1) + 3 · (2 + 1 + 4) = 42.
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

Practice Final, Problem 1(c). Suppose we run Prim's algorithm on the graph above starting at s = 1. (Pretend that every edge is undirected, and ignore the label t.) List the edges chosen by the algorithm in the order in which they are chosen. (The exam's graph is a directed flow network with edges (1, 2):6, (1, 3):2, (2, 3):3, (2, 4):8, (3, 4):1; it is drawn here with the arrows removed.) 623811234
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. 623811234

Practice Final, Problem 2(a). Fractional Knapsack

Practice Final, Problem 2(a). Suppose we run the optimal greedy algorithm for Fractional Knapsack on v = [3, 4, 5], w = [2, 2, 1], B = 4. What are the values in x (starting with x[1])?
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

Practice Final, Problem 6. The input is a connected, undirected graph G where every edge e has a distinct weight w(e) > 0. (In other words, G is an input to the MST problem, but our goal will be different.) Our goal is to return a spanning tree T such that maxe∈T w(e) is minimized. Describe an O(m²)-time algorithm for this problem, explain why it's correct, and analyze its running time.
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

Exercises

4.1. State the three steps of the exchange argument as the lecture numbered them, then state the Cut Property and the Cycle Property and name the algorithms each one justifies.
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.
4.2. Run Prim's algorithm from vertex 1 on the graph below and list the edges in the order chosen. (No explanation.) 425138612345
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. 425138612345
4.3. Run Kruskal's algorithm on the same graph and list the edges in the order added. (No explanation.)
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.
4.4. Run Reverse-Delete on the worksheet graph of Section 4.2 and list the deleted edges in the order deleted. (No explanation.)
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.
4.5. Run Select-Intervals on A = [[1, 4], [3, 5], [1, 6], [5, 7], [3, 9], [5, 9], [6, 10], [8, 11], [8, 12], [2, 14], [12, 16]], which is already sorted by end time. Which intervals are chosen? (No explanation.)
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.
4.6. Suppose we run the optimal greedy algorithm for Fractional Knapsack on v = [10, 6, 9], w = [4, 3, 6], B = 8. What are the values in x (starting with x[1])? (No explanation.)
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.
4.7. True or false? Answer each and correct the false ones. (a) If all edge weights are distinct, the lightest edge of G is in the MST. (b) If all edge weights are distinct, the heaviest edge of G is never in the MST. (c) Prim's and Kruskal's algorithms always list the MST edges in the same order.
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}.
4.8. On Midterm 1's Problem 3 (PS 3.4), a student writes: "Remove e from T, run BFS from one endpoint to find the two sides S and V − S, and add the lightest edge crossing S. By the Cut Property that edge is in the new MST, so the algorithm is correct. O(m + n)." What will the grader object to?
SolutionThe 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).
4.9. The input is (G, e), where G is a connected, undirected graph with distinct edge weights and e = {u, v} is an edge of G. Describe an O(m + n)-time algorithm that decides whether e is in the MST of G, explain why it's correct, and analyze its running time.
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.

Key points
The four steps, in the course's words
  1. Subproblems: "Which subproblems will we solve? What will we return?"
  2. 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.)"
  3. 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."
  4. 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

Recurrence for Max in ArrayBase case OPT[1] = A[1]. For all i ≥ 2, OPT[i] = max(OPT[i−1], A[i]).

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]
i12345
A[i]31415
d[i]33445

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.

Defining OPT vaguely"OPT[i] = the best answer so far" earns little credit. The subproblem sentence must say which smaller input the subproblem is about (A[1:i]? A[i:n]? A[i:j]? must A[i] be used?), which quantity is optimized, for which range of indices, and which entry is returned. Everything else in the answer refers back to that sentence.
How this is testedMax in Array itself is never the exam question; the format is. Every DP design problem on Midterm 2 and on the Practice Final (Problems 3 to 8 style) is graded on the four steps, and the subproblem sentence and the base cases are where points are lost. Practise writing the sentence "For all i ∈ …, let OPT[i] denote …; we will return …" until it is automatic.

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.

i12345
A[i]29491
d[i]
Answerd = [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.

Key points
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

Subproblems for LIS (the LIS trick)"For all i ∈ [n], let OPT[i] denote the length of the LIS of A that must end on A[i]. Since the LIS of A must end somewhere, we will return max(OPT)."

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

Recurrence for LISBase case OPT[1] = 1. For every i ≥ 2,

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:

iA[i]candidates j (A[j] < A[i]) with d[j]d[i]a subsequence achieving d[i]
15none1[5]
22none1[2]
35j = 2 (1)2[2, 5]
46j = 1, 2, 3 (1, 1, 2)3[2, 5, 6]
53j = 2 (1)2[2, 3]
67j = 1, …, 5 (1, 1, 2, 3, 2)4[2, 5, 6, 7]
74j = 2, 5 (1, 2)3[2, 3, 4]
86j = 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].

Return max(d), not d[n]With the LIS trick, d[n] is the best subsequence that ends on the last element, which is usually not the best overall. For the lecture's A = [5, 1, 2, 7, 4, 6, 3], d[n] = 3 but the answer is 4. The lecture crossed out "we will return OPT[n]" and wrote "max(OPT)" beside it. Any time the subproblem is forced to use A[i], the final answer is a maximum (or minimum) over all i.
How this is testedProblem 1 of the final can ask "Suppose we run the O(n²)-time DP for LIS on A = …. What are the values in d?" (Practice Final 1d, Midterm 2 1c, Practice Midterm 2 1c). The answer is n numbers with no explanation and no partial credit. A fast way to check each entry: d[i] is the length of the longest increasing subsequence that ends exactly on A[i], which for short arrays you can see by eye. In Problems 3 to 8, "call LIS" is allowed by name, and the LIS trick is the pattern behind half of Problem Set 4 (Chapter 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.

i12345678
A[i]38492576
d[i]
Answerd = [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.

Answerp[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.

Key points

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

Subproblems for LPSFor all i and all j ∈ {i, …, n}, let OPT[i][j] denote the length of an LPS in A[i:j]. We will return OPT[1][n]. In the notes: "We can visualize the DP table as an n × n square, but we are only concerned with the values in the upper-right triangle."

The lecture later listed this as Pattern 4: "OPT[i][j] = OPT given A[i:j]", used by LPS.

Recurrence

Recurrence for LPSBase case OPT[i][i] = 1. For i < j:

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 \ j1: a2: c3: b4: c5: b6: d7: a
1: a1113335
2: c0113333
3: b0011333
4: c0001111
5: b0000111
6: d0000011
7: a0000001

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.)

Filling the LPS table from the topRow 1 needs row 2, which needs row 3, and so on; the top-right cell is the last one that can be computed. If an exam asks for "the values in the first row of d," you still have to build the table from the bottom row up. Also remember that the course's d is initialized to zeros: the Day 2 worksheet answer for abaca lists Row 2 as [0, 1, 1, 1, 3], with the zero below the diagonal included.
How this is testedMidterm 2 (1e) and Practice Midterm 2 (1e) asked: "Suppose we run the O(n²)-time DP for Longest Palindromic Subsequence on A = …. What are the values in the first row of d? (Your answer should be 4 numbers.)" A useful check: the first row entry in column j is OPT[1][j], the LPS length of the prefix A[1:j], which for a short string you can see directly. For abab: a → 1, ab → 1, aba → 3, abab → 3, so the first row is [1, 1, 3, 3].

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 \ j1: b2: b3: a4: b
1: b
2: b
3: a
4: b
AnswerRow 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.

Key points

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

Subproblems for Edit Distance"For all i ∈ {0, 1, …, m} and j ∈ {0, 1, …, n}, let OPT[i][j] denote the edit distance from A[1:i] to B[1:j]. We will return OPT[m][n]."

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:

  1. star → wat, then insert e at the end: OPT[i][j−1] + 1.
  2. sta → wate, then delete r: OPT[i−1][j] + 1.
  3. 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."
Recurrence for Edit DistanceBase cases OPT[0][j] = j and OPT[i][0] = i. For i ≥ 1 and j ≥ 1,

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""water
""012345
s112345
t222234
a332334
r443343

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."

The last row is row m and starts with mMidterm 2 asked for "the values in the last row of d" for A = abca and B = baa, and the answer had 4 numbers: [4, 3, 2, 2]. The last row is row m (the full string A), and its first entry is the base case d[m][0] = m. Leaving out that first number, or forgetting that row 0 exists, loses the point. Also keep the direction straight: rows are A (the string being edited), columns are B.
How this is testedProblem 2 of the Practice Final asked "What is the Edit Distance from abbc to babc?" (answer 2), and both Midterm 2 and its practice exam asked for the last row of d. Draw the whole table: write the strings along the edges with the empty prefix first, write row 0 and column 0, then apply "min of the three neighbors, +1 except +0 on the diagonal when the letters match." Check the final value by exhibiting an actual sequence of moves of that length. A second check: the last row's entry in column j is ED(A, B[1:j]), the cost of turning all of A into the first j letters of B. In Problems 3 to 8, the Pattern 6 subproblem "OPT[i][j] for (A[1:i], B[1:j])" is the model for any two-sequence problem, such as the shuffle problem in Section 5.7.

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""ba
""
a
b
AnswerRows "", 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""pea
""
a
p
e
AnswerRows "", 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

Day 1, Problem 1. The input is an array A of n integers. Describe an O(n)-time DP algorithm (i.e., subproblems, recurrence) that returns the sum of A.
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

Day 1, Problem 3. The input is an array A of n positive integers. Our goal is return the length of the longest increasing contiguous subsequence (i.e., subarray) in A. Describe an O(n)-time DP algorithm (i.e., subproblems, recurrence, etc.) for this problem, explain why it's correct, and analyze its running time. Example: If A = [3, 1, 2, 4, 2, 5], the algorithm should return 3, which is the length of the contiguous subsequence [1, 2, 4].
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

Day 2, Problem 1. After we run the DP for LPS on "abaca", what are the values in d?
Solution
i \ j1: a2: b3: a4: c5: a
1: a11333
2: b01113
3: a00113
4: c00011
5: a00001

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

Day 3, Problem 2. Describe an O(n)-time DP algorithm that returns F(n), the n-th Fibonacci number.
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

Day 3, Problem 3. After we run the Edit Distance DP on A = "star" and B = "water", what are the values in d?
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

Day 4, Problem 1. 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]).
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.

From homework to examThe exam versions of these questions ask for the whole array d (LIS), the first row of d (LPS) or the last row of d (Edit Distance) on inputs of 4 to 6 elements. Write the full table every time; checking each entry against its meaning (LIS ending here, LPS of this prefix, distance from all of A to this prefix of B) catches arithmetic slips.

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

Midterm 2, 1(c). Suppose we run the O(n²)-time DP (dynamic program) for Longest Increasing Subsequence (LIS) on A = [2, 3, 2, 4, 6, 5]. What are the values in d? (Your answer should be 6 numbers.)
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

Midterm 2, 1(d). Suppose we run the O(mn)-time DP for Edit Distance on A = abca and B = baa. What are the values in the last row of d? (Your answer should be 4 numbers.)
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

Midterm 2, 1(e). Suppose we run the O(n²)-time DP for Longest Palindromic Subsequence on A = abab. What are the values in the first row of d? (Your answer should be 4 numbers.)
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

Practice Midterm 2, 1(c). Suppose we run the O(n²)-time DP (dynamic program) for Longest Increasing Subsequence (LIS) on A = [5, 1, 7, 8, 2, 3]. What are the values in d? (Your answer should be 6 numbers.)
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

Practice Midterm 2, 1(d). Suppose we run the O(mn)-time DP for Edit Distance on A = abbc and B = bab. What are the values in the last row of d? (Your answer should be 4 numbers.)
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

Practice Midterm 2, 1(e). Suppose we run the O(n²)-time DP for Longest Palindromic Subsequence on A = abcb. What are the values in the first row of d? (Your answer should be 4 numbers.)
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

Practice Final, 2(b). What is the Edit Distance from abbc to babc?
Solution2. 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

Practice Midterm 2, Problem 4. The input is three strings (A, B, C), where A has length m, B has length n, and C has length m + n. Our goal is to return True if C is a shuffle of A and B (i.e., A and B are disjoint subsequences of C) and False otherwise. In other words, we want to determine if we can "merge" A and B to create C. Describe an O(mn)-time DP algorithm for this problem (i.e., subproblem, recurrence, pseudocode), explain why it's correct, and analyze its running time. Example: Suppose A = art and B = bat. If C ∈ {arbtat, baartt}, then the algorithm should return True; if C ∈ {rtabat, aabrtt}, then the algorithm should return False.
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.)

What to noticeSix of the seven one-point parts are "what are the values in d (or in one row of d)," with 4 to 6 numbers expected, and the seventh asks for a single edit distance. The arrays are small enough to fill in two minutes, and each answer can be checked against the meaning of the entries. The design problem shows how Pattern 6 transfers: once you can write the edit-distance subproblem sentence, the shuffle subproblem is the same sentence with a different quantity.

Before moving on

Exercises

5.1. State the four steps of a DP answer in the course's format, and say where the correctness argument goes.
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.
5.2. Suppose we run the O(n²)-time DP for LIS on A = [1, 5, 2, 6, 3, 7]. What are the values in d, and what is returned?
Solutiond = [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).
5.3. Suppose we run the O(n²)-time DP for LPS on A = banana. What are the values in the first row of d, and what is returned?
Solution
i \ j1: b2: a3: n4: a5: n6: a
1: b111335
2: a011335
3: n001133
4: a000113
5: n000011
6: a000001
The first row is [1, 1, 1, 3, 3, 5] and the algorithm returns 5 (anana). Key cells: d[2][6] = d[3][5] + 2 = 3 + 2 = 5 (a = a), and d[1][6] = max(d[2][6], d[1][5]) = max(5, 3) = 5 (b ≠ a).
5.4. Suppose we run the O(mn)-time DP for Edit Distance on A = tide and B = diet. What are the values in the last row of d, and what is the edit distance?
Solution
A \ B""diet
""01234
t11233
i22123
d32223
e43323
The last row is [4, 3, 3, 2, 3] and the edit distance is 3, for example tide → dide (replace t with d) → die (delete the second d) → diet (insert t).
5.5. What is the Edit Distance from horse to ros? Give the value and a sequence of moves of that length.
Solution3. 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).
5.6. A student's LIS solution defines OPT[i] as the length of the LIS ending on A[i], gives the correct recurrence, and then writes "return d[n]". What will the grader object to, and on which input does the algorithm fail?
SolutionThe 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.
5.7. True or false, and correct the statement if it is false: (a) The LPS table can be filled row by row starting with row 1. (b) In the edit-distance DP, if A[i] = B[j] then OPT[i][j] = OPT[i−1][j−1]. (c) The LIS DP runs in O(n) time because each d[i] is set once.
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²).
5.8. The input is an array A of n positive integers. Our goal is to return the largest possible sum of an increasing subsequence of A. Describe an O(n²)-time algorithm for this problem, explain why it's correct, and analyze its running time. Example: if A = [4, 6, 1, 3, 8, 4, 6], the algorithm should return 18 (4 + 6 + 8).
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".

5.9. The input is a string A of length n. Our goal is to return the minimum number of characters that must be deleted from A so that the remaining string is a palindrome. Describe an O(n²)-time algorithm, explain why it's correct, and analyze its running time. Example: for A = abcda the answer is 2.
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²).

5.10. The input is two strings A and B of lengths m and n. Our goal is to return the length of a longest common subsequence of A and B (a string that is a subsequence of both). Describe an O(mn)-time DP algorithm (subproblems, recurrence, algorithm, running time), explain why it's correct, and analyze its running time. Example: for A = abcb and B = bacb, the answer is 3 (acb or bcb).
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.

Key points

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

0/1 Knapsack recurrenceBase cases: OPT[1][j] = 0 for all j < w[1], and OPT[1][j] = v[1] for all j ≥ w[1] (the lecture adds OPT[i][0] = 0 for every i). For i ≥ 2:

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) \ j012345
1 (4, 3)000444
2 (2, 1)022466
3 (3, 2)023567
4 (5, 2)0257810

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.

  1. 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].
  2. 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]].
  3. 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).

Reading the current row instead of the row aboveIn the "include" option the remaining capacity must be filled from items 1, …, i − 1, so the term is v[i] + OPT[i−1][j − w[i]]. Writing v[i] + OPT[i][j − w[i]] allows item i to be used again and silently computes the unbounded knapsack. On a one-point trace this changes the last row; on a design problem it makes the recurrence wrong. Also do not forget the "item does not fit" case: when w[i] > j the index j − w[i] is negative.
How this is testedProblem 1 of the final has a one-point part of the form "Suppose we run the O(nB)-time DP for 0/1 Knapsack on v = …, w = …, B = …. What are the values in the last row of d? (Your answer should be B + 1 numbers, starting with 0.)" (Practice Final, Problem 1e, worked in Section 6.9). Homework 4 asked "What does the algorithm return?" (Section 6.8). Fill the whole table on scratch paper row by row; each row takes under a minute. In Problems 3–8, Knapsack-DP may be called by name, and Practice Final Problem 7 was announced as "similar to 0/1 Knapsack": the include/exclude split is the reusable idea.

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) \ j012345
1 (3, 2)
2 (5, 3)
3 (4, 2)
4 (2, 1)
AnswerRow 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.

Key points

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) \ j012345678910
1 (5, 5)000005555510
2 (7, 6)000005777710

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].

Sweeping the single array left to right for 0/1 KnapsackIn the one-array version, the direction is the whole difference between the two problems. Right to left (j = B, …, w[i]) is 0/1 Knapsack; left to right is Unbounded Knapsack. If you use this version on the exam, say the direction and why.
How this is testedA design problem may be a knapsack with a twist (unlimited copies, an exact-sum requirement, counting instead of maximizing); name the change in the recurrence relative to Knapsack-DP and argue the case split again. Midterm 2 Problem 4 (Section 6.9) is an "unbounded" counting problem in disguise.

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) \ j01234567
1 (3, 2)
2 (4, 3)
3 (5, 4)
AnswerRow 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.

Key points

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.

1w=32w=23w=24w=55w=46w=1 1w=32w=23w=24w=55w=46w=1

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

Independent set in treesIf u is a leaf: OPTin[u] = w(u) and OPTout[u] = 0. Otherwise

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.

1w=22w=53w=34w=35w=16w=29w=310w=512w=113w=27w=38w=211w=2
Vertex uw(u)Children T[u]OPTin[u]OPTout[u]
5, 7, 8, 9, 11, 12, 13 (leaves)1, 3, 2, 3, 2, 1, 2nonew(u)0
627, 82 + 0 + 0 = 2max(3, 0) + max(2, 0) = 5
105115 + 0 = 5max(2, 0) = 2
255, 65 + 0 + 5 = 10max(1, 0) + max(2, 5) = 6
339, 103 + 0 + 2 = 5max(3, 0) + max(5, 2) = 8
4312, 133 + 0 + 0 = 3max(1, 0) + max(2, 0) = 3
1 (root)22, 3, 42 + 6 + 8 + 3 = 19max(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.

1w=22w=53w=34w=35w=16w=29w=310w=512w=113w=27w=38w=211w=2

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.

  1. 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).
  2. 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]).
  3. 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.

Processing vertices in the wrong orderIf you loop over u = 1, 2, …, n or in BFS order, the parent is processed before its children and reads din[v] = dout[v] = 0. Say in your pseudocode which order you use ("reverse topological order", "decreasing post values of a DFS from the root", or "reverse BFS order") and why it puts children first.
How this is testedMIS-Tree is the course's template for every dynamic program on a tree. A design problem on a tree (vertex cover, matching, subtree sums, a coloring rule) is answered by naming one or two subproblems per vertex "in Tu", writing the leaf case, combining children with a sum, and reusing this running-time sentence. The Day 4 worksheet asked, as a one-line question, "In terms of OPTin and/or OPTout, what should the MIS DP algorithm return?" (answer max(OPTin[1], OPTout[1])); a one-point part could equally ask for the pair at the root.

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.

1w=62w=43w=34w=25w=56w=47w=18w=3
u87654321
OPTin[u]
OPTout[u]
AnswerLeaves 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). 1w=62w=43w=34w=25w=56w=47w=18w=3

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.

Key points

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.

Which version to write on the examBoth are correct and both are O(n). The two-array version (Section 6.3) is the one in the notes and extends more easily to other problems (vertex cover, matching), so prefer it unless the problem fixes the subproblem for you.

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.

AnswerLeaves: 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.

Key points

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.

13141222123458679

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]."

Matching in treesLeaf: OPTout[u] = OPT[u] = 0. Otherwise

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 uChildren (edge weight)OPTout[u]OPT[u]
4, 6, 7, 9none00
56 (2), 7 (2)0 + 0 = 0max(0, 2 + 0 + 0 − 0, 2 + 0 + 0 − 0) = 2
89 (2)0max(0, 2 + 0 + 0 − 0) = 2
24 (1), 5 (4)0 + 2 = 2max(2, 1 + 0 + 2 − 0, 4 + 0 + 2 − 2) = 4
38 (1)2max(2, 1 + 0 + 2 − 2) = 2
12 (1), 3 (3)4 + 2 = 6max(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.

13141222123458679

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).

Forgetting that a matched child loses its own edgesWhen u is matched to v, the term for T(v) is OPTout[v], not OPT[v]: v already has its partner. Using OPT[v] can count two edges at v. Likewise the root's answer is OPT[1], not OPTout[1].

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.

34526123456
u456231
OPTout[u]
OPT[u]
AnswerLeaves 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. 34526123456

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.

Key points

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.

#InputSubproblem (notes' wording)Course examplesFill 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), Fibonaccii = 1 … n · OPT[n]
2A∀ 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
4A∀ i ∈ [n] ∀ j ∈ [i, n]: OPT[i][j] = OPT given A[i : j]LPSbottom 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 Knapsackrow 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]
7T, a rooted tree with vertex set V∀ u ∈ V: OPT[u] = OPT given TuMIS with grandchildren (Section 6.4), OPT[u] in tree matchingchildren first · OPT[root]
8T∀ u ∈ V: OPT[u] = OPT given Tu that somehow involves uOPTin, OPTout for MIS; OPTout in tree matchingchildren 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.

  1. 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.
  2. 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.
  3. 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.
  4. 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).
  5. Write the pseudocode with the fill order that makes every needed value available (left to right, right to left, bottom row up, children first).
  6. 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:

i12345678
A[i]415231012
S[i]28242318161332
OPT[i]18141015141332

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.

Returning OPT[n] under the LIS trickWith Pattern 3 the best solution may end anywhere, so the answer is max(OPT) (or min); OPT[n] is only the best solution that ends at A[n]. Conversely, with Patterns 1 and 2 return OPT[n] or OPT[1]. Say which one in the subproblem sentence.
How this is testedEvery multi-point dynamic-programming problem on Midterm 2, Practice Midterm 2 and the Practice Final was one of these patterns with a two- or three-way case split: the stock problem (Pattern 3), contiguous LIS (Pattern 3), counting lists (Pattern 1 on targets), the shuffle (Pattern 6) and skip-the-next-B[i] (Pattern 2). Sections 6.7 and 6.9 work them all.

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.

i123456
A[i]391284
S[i]
OPT[i]
AnswerS = [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

PS 4.1. The input is an array A of n positive integers. Our goal is return the sum of all elements in A. Describe an O(n)-time DP algorithm (i.e., subproblem, recurrence, etc.) for this problem, explain why it's correct, and analyze its running time.
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

PS 4.2. The input is an array A of n positive integers. Our goal is return the length of the longest increasing contiguous subsequence (i.e., subarray) in A. Describe an O(n)-time DP algorithm (i.e., subproblem, recurrence, etc.) for this problem, explain why it's correct, and analyze its running time. Example: If A = [3, 1, 2, 4, 2, 5], the algorithm should return 3, which is the length of the contiguous subsequence [1, 2, 4].
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

PS 4.3. The input is an array A of n positive integers. We start at index 0 (i.e., one unit left of A), and in each step, we are allowed to jump from index i to either i + 1 or i + 2. When we land on A[i], we pay a cost of A[i]. Our goal is to land on index n + 1 (i.e., one unit right of A) while minimizing the total cost. Describe an O(n)-time algorithm that returns the minimum cost, explain why it's correct, and analyze its running time. Example: If A = [1, 10, 1], the algorithm should return 2.
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

PS 4.4. The input is an m × n array A of 0s and 1s, where A[i][j] = 1 represents an obstacle at (i, j) and A[i][j] = 0 represents no obstacle at (i, j). We start at (1, 1), we want to end at (m, n), and we are finding a path that moves right or down (but not diagonally) at each step, but we are not allowed to bump into any obstacles. You should assume A[1][1] = 0. Describe an O(mn)-time algorithm that returns the number of such paths, explain why it's correct, and analyze its running time. Example: If A = [[0, 0, 0], [0, 1, 0], [0, 0, 0]], then the algorithm should return 2. If A = [[0, 1], [0, 0]], then the algorithm should return 1.
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

PS 4.5. The input is an array A of n positive integers. The story is that we want to buy a stock on day i by spending A[i], sell the stock on day j and receive A[j], and we want to maximize our profit A[j] − A[i]. More specifically, the algorithm should return the maximum possible value of A[j] − A[i] over all pairs of indices (i, j) such that i < j. Describe an O(n)-time algorithm for this problem, explain why it's correct, and analyze its running time. Example: If A = [8, 2, 4, 7, 1, 3], the algorithm should return 5 (7 − 2).
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

PS 4.6. The input is an array A of n positive integers. Our goal is to find a subsequence S of A whose sum is as large as possible. However, for all i ∈ {2, …, n}, if S contains A[i], S is not allowed to contain A[i−1]. Describe an O(n)-time algorithm that returns the maximum possible sum, explain why it's correct, and analyze its running time. Example: If A = [1, 1, 1], then ALG should return 2. If A = [3, 8, 3, 1, 12], then ALG should return 20.
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

PS 4.7. The input is three integers (A, B, n) such that A ≥ 1, B ≥ 1, and n ≥ 0. Our goal is to return the number of ways to add any number of A's and B's such that the total is n. For example, if (A, B, n) = (1, 2, 4), then ALG should return 5, because we can add 1's and 2's to reach 4 in 5 different ways: 1+1+1+1, 2+1+1, 1+2+1, 1+1+2, 2+2. Note that A + B is considered different from B + A, so if (A, B, n) = (1, 1, 1), then ALG should return 2. Describe an O(n)-time algorithm that solves this problem, explain why it's correct, and analyze its running time. Hint: If n = 0, then ALG should return 1. And as usual, you can start an array at index 0, as long as it's clear in the algorithm.
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.

What Problem Set 4 tells you about the finalAll seven problems have a one- or two-index table and a recurrence that reads one to three earlier entries. Four use the "last element in or out" split (4.1, 4.4, 4.6, 4.7) and three the LIS trick (4.2, 4.3, 4.5). If one of them appears on the final, the official solution above is the model answer; write it with the same subproblem sentence.

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) \ j01234
1 (3, 2)00333
2 (1, 1)01344
3 (2, 4)01344

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

Practice Final, Problem 1e. Suppose we run the O(nB)-time DP for 0/1 Knapsack on v = [3, 4, 2], w = [2, 2, 1], B = 4. What are the values in the last row of d? (Your answer should be 5 numbers, starting with 0.)
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

Practice Final, Problem 3. The input is an array A of n positive integers. The story is that we want to buy a stock on day i by spending A[i], sell the stock on day j and receive A[j], and we want to maximize our profit A[j] − A[i]. More specifically, the algorithm should return the maximum possible value of A[j] − A[i] over all pairs of indices (i, j) such that i < j. Describe an O(n)-time algorithm for this problem, explain why it's correct, and analyze its running time. Example: If A = [8, 2, 4, 7, 1, 3], the algorithm should return 5.
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

Practice Final, Problem 7. The input is (A, B), where A and B are both arrays of n integers. Our goal is to find a subsequence S of A such that the sum of the elements in S is maximized. However, if A[i] ∈ S, then S cannot contain A[i + 1], A[i + 2], …, A[i + B[i]]. (If i + B[i] > n, then S cannot contain anything after A[i].) In other words, if A[i] ∈ S, then S needs to skip the next B[i] elements in A. Describe an O(n)-time algorithm for this problem, explain why it's correct, and analyze its running time. The algorithm should return the sum of S, not S itself. Examples: 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

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

Midterm 2, Problem 2. The input is an array A of n positive integers. The story is that we want to buy a stock on day i by spending A[i], sell the stock on a later day j and receive A[j], and we want to maximize our profit A[j] − A[i]. More specifically, the algorithm should return the maximum possible value of A[j] − A[i] over all pairs of indices (i, j) such that i < j. Describe an O(n)-time algorithm for this problem, explain why it's correct, and analyze its running time. Example: If A = [8, 2, 7, 1, 3], the algorithm should return 5 (7 − 2).
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

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. Our goal is to return the number of lists whose sum is exactly t, where every number in each list must be in A. Describe an O(nt)-time algorithm for this problem, explain why it's correct, and analyze its running time. Example: If A = [1, 3, 2] and t = 4, ALG should return 7 because there are 7 valid lists: [1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [2, 1, 1], [1, 3], [3, 1], and [2, 2].
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

Practice Midterm 2, Problem 2. The input is an array A of n positive integers. Our goal is return the length of the longest increasing contiguous subsequence (i.e., subarray) in A. Describe an O(n)-time DP algorithm (i.e., subproblem, recurrence, etc.) for this problem, explain why it's correct, and analyze its running time. Example: If A = [3, 1, 2, 4, 2, 5], the algorithm should return 3, which is the length of the contiguous subsequence [1, 2, 4].
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?

Practice Midterm 2, Problem 4. The input is three strings (A, B, C), where A has length m, B has length n, and C has length m + n. Our goal is to return True if C is a shuffle of A and B (i.e., A and B are disjoint subsequences of C) and False otherwise. In other words, we want to determine if we can "merge" A and B to create C. Describe an O(mn)-time DP algorithm for this problem (i.e., subproblem, recurrence, pseudocode), explain why it's correct, and analyze its running time. Example: Suppose A = art and B = bat. If C ∈ {arbtat, baartt}, then the algorithm should return True; if C ∈ {rtabat, aabrtt}, then the algorithm should return False.
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 \ j01: b2: a3: t
0TFFF
1: aTFFF
2: rTTFF
3: tFTTT

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.

What to noticeEvery problem above was answered by the same three moves: choose the pattern (3 for the stock and contiguous problems, 2 for skipping ahead, 1 on the targets for counting lists, 6 for two strings), split on the last element, and count subproblems times time per subproblem. Three of the six design problems were Problem Set 4 verbatim, and the others were close relatives of course algorithms (0/1 Knapsack, PS 4.7, Edit Distance), which the official solutions say explicitly.

Before moving on

Exercises

6.1. Suppose we run the O(nB)-time DP for 0/1 Knapsack on v = [2, 6, 3, 5], w = [1, 4, 2, 3], B = 6. What are the values in the last row of d, and which items does an optimal solution take?
SolutionRows: [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.
6.2. For the tree below, compute OPTin and OPTout at every vertex and the weight of a maximum independent set. Then give the minimum weight of a vertex cover of the same tree. 1w=52w=73w=24w=35w=26w=47w=6
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}.

1w=52w=73w=24w=35w=26w=47w=6

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.)

6.3. What does Unbounded-Knapsack return on v = [3, 5], w = [2, 3], B = 7? Give both rows.
SolutionRow 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.
6.4. Run the Practice Final Problem 7 algorithm on A = [5, 1, 4, 6, 2], B = [1, 3, 0, 1, 0]. Give d and the returned value.
Solutiond[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]).
6.5. Give a counterexample showing that the greedy algorithm "repeatedly pick the item with the largest v[i]/w[i] that still fits" is not optimal for 0/1 Knapsack, and give the knapsack table's answer for it.
SolutionThe 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).
6.6. (Vertex cover in a tree.) A vertex cover of a graph is a set C of vertices such that every edge has at least one endpoint in C. The input is (T, w), a tree rooted at vertex 1 with children lists T[u] and positive weights w[u]. Describe an O(n)-time algorithm that returns the minimum weight of a vertex cover, explain why it's correct, and analyze its running time.
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).

6.7. A student answers the independent-set problem with the subproblem "OPT[u] = weight of the MIS in Tu" and the recurrence OPT[u] = max(w[u], Σv ∈ T[u] OPT[v]). What will the grader object to? Give a tree on which it fails.
SolutionThe "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.
6.8. (Exact-capacity knapsack, Pattern 5.) The input is (w, B): an array w of n positive integers and a positive integer B. Describe an O(nB)-time algorithm that returns True if some subset of the items has total weight exactly B and False otherwise, explain why it's correct, and analyze its running time. Then run it on w = [3, 5, 2], B = 7.
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.

Key points

Problem

Single-Source Shortest Path (SSSP)In the notes' words: "The input is (G, s), where G is a directed graph and every edge e has some (possibly non-positive) integer length ℓ(e), and s is a 'source' vertex in G. Our goal is to return the shortest paths from s to every vertex v ∈ V." The algorithms "only return an array d such that d[v] is the distance from s to v. But as usual, we can maintain parent pointers and trace them at the end to construct the shortest paths themselves."
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.

1−31123

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.

Key points

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

DAG DP recurrenceThe base case is OPT[s] = 0. For all v ≠ s,

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:

103−2−4−751342
StepvIn-neighbors (GR[v])Candidates d[u] + ℓ(u, v)d[v]d = [d[1], d[2], d[3], d[4]]
0initialization[0, ∞, ∞, ∞]
11nonenone (d[1] stays 0)0[0, ∞, ∞, ∞]
2310 + 10 = 1010[0, ∞, 10, ∞]
341, 30 + (−4) = −4; 10 + 3 = 13−4[0, ∞, 10, −4]
421, 3, 40 + 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:

103−2−4−751342

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)."

Do not scan the whole graph for in-neighborsWriting "for each u in V: if v in G[u]" inside the loop over v looks innocent, but it costs Ω(n) or more per vertex and the total is no longer O(m + n). Always say "GR = reverse of G" and loop over GR[v]; the grader looks for it.

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.

How this is testedA Problem 1 or 2 part can ask for the final d on a small DAG (Homework 5, Question 1 is exactly that), and a design problem can hide a DAG: grids where you move only right or down, prerequisites, "jump forward" sequences. The pattern is always the same: define OPT[v] per vertex, write a min or max over in-neighbors, process in topological order with GR, O(m + n).

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.

v12345
d[v]
Answerd = [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.

Key points

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

Bellman-Ford subproblems"For all v ∈ V and j ∈ {0, 1, …, n − 1}, let OPT[v][j] denote the length of the shortest s-v walk that contains at most j edges. Since G has no negative cycles, every shortest walk has at most n − 1 edges, so we will return OPT[·][n − 1] (i.e., the last column of the DP table)."

Recurrence

Bellman-Ford recurrenceBase cases OPT[s][0] = 0 and OPT[v][0] = ∞ for all v ≠ s. For j ≥ 1,

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:

54−32−11423
v \ j0123
10000
2∞422
3∞∞31
4∞555

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:

54−32−11423

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
"d after round j" is not "column j"The Day 2 worksheet asked: "True or False? For every j ∈ {1, …, n − 1}, at the end of iteration j in Bellman-Ford-2, d is equal to column j of the output of Bellman-Ford." The official answer is False in general, true for j = n − 1 (so both versions return the same thing) and for j = 0. The official example: the path 1 → 2 → 3 with s = 1 and all lengths 1. After iteration 1 of Bellman-Ford-2, d = [0, 1, 2], but column 1 of the table is [0, 1, ∞]: relaxing (1, 2) first lowers d[2], and relaxing (2, 3) in the same round already uses the new value. "Intuitively, Bellman-Ford-2 updates d-values 'more quickly' than Bellman-Ford does, because it overwrites old values rather than saving them." The lecture's own example (edges (1, 2) of length 5, (1, 3) of length 2, (2, 3) of length −4) gives column 1 = [0, 5, 2] but d = [0, 5, 1] after round 1. If a question limits the number of edges, use the table version and compute column j only from column j − 1.
52−4123

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."

1111s123

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.

How this is testedMidterm 2 and the Practice Midterm 2 each asked "Suppose we run Bellman-Ford on the graph above. What are the final values in d?" as a one-point part, and Homework 5 asked for single entries of the final d. Fill the table column by column (or reason about the shortest paths directly when the graph is small) and list d[1] through d[n]. In a design problem, "at most k edges" or a budget on a positive integer resource means a Bellman-Ford table with that quantity as the second index.

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 \ j0123
1
2
3
4
AnswerColumn 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?

AnswerAfter 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).

Key points

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:

3101423112345
StepChosen u (d[u])S after the stepRelaxationsd = [d[1], …, d[5]]
0∅initialization[0, ∞, ∞, ∞, ∞]
11 (0){1}d[2] = 0 + 3 = 3; d[4] = 0 + 10 = 10[0, 3, ∞, 10, ∞]
22 (3){1, 2}d[3] = 3 + 1 = 4; d[4] = min(10, 3 + 4) = 7[0, 3, 4, 7, ∞]
33 (4){1, 2, 3}d[4] = min(7, 4 + 2) = 6; d[5] = 4 + 3 = 7[0, 3, 4, 6, 7]
44 (6){1, 2, 3, 4}d[5] = min(7, 6 + 1) = 7[0, 3, 4, 6, 7]
55 (7)Vno 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:

3101423112345

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.

Theorem and official proof (induction)Let δ(u) denote the distance from s to u. "We will show by induction that when u gets added to S, d[u] = δ(u). (The proof also shows that this value of d[u] does not change later in the algorithm.)"
  1. Base case. The first vertex added is u = s, and d[s] = 0 = δ(s).
  2. 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.
  3. 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.
  4. 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).
  5. 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*).
  6. 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:

510−711234
StepChosen u (d[u])Relaxationsd = [d[1], d[2], d[3], d[4]]
11 (0)d[2] = 5; d[3] = 10[0, 5, 10, ∞]
22 (5)d[4] = 5 + 1 = 6[0, 5, 10, 6]
34 (6)no edges leave 4[0, 5, 10, 6]
43 (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.

"No negative cycle" is not enough for DijkstraBellman-Ford needs only that there is no negative cycle; Dijkstra needs every edge to be nonnegative. The graph above has no cycle at all and Dijkstra still returns a wrong value. If a design problem has negative lengths, either use Bellman-Ford or DAG DP, or remove the negative edges and argue about them separately (PS 5.2).

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)."

11121234

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.

How this is testedMidterm 2 and the Practice Midterm 2 both asked "Suppose we run Dijkstra's algorithm on the graph above. What are the final values in d?" (with the minus signs ignored), and Homework 5 asked for entries of d. Keep a row of d-values and a set S; at each step take the smallest d outside S (smallest label on ties), relax only its outgoing edges, and write the row again. In design problems Dijkstra is the workhorse whenever lengths are nonnegative: call it by name, often on a modified graph (two copies of every vertex for parity or for one free edge, Sections 7.7 and 7.9), and quote O(n²).

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 vertexd = [d[1], d[2], d[3], d[4]]
Step 1
Step 2
Step 3
Step 4
AnswerStep 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.

AnswerBase 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.

Key points

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

Floyd-Warshall subproblems"For all u, v ∈ V and r ∈ {0, 1, …, n}, let OPT[u][v][r] denote the length of the shortest walk from u to v with vertices [r] available as intermediate vertices. (Recall that V = [n] = {1, …, n}.) We will return OPT[·][·][n]." An intermediate vertex is any vertex of the walk other than its two endpoints.

Recurrence

Floyd-Warshall recurrenceFor r = 0 no intermediate vertex is allowed, so OPT[u][v][0] = 0 if u = v, ℓ(u, v) if (u, v) ∈ E, and ∞ otherwise. For r ≥ 1,

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:

215−7101243

Each block below is one table; row u, column v holds d[u][v]; entries that changed from the previous table are bold.

u \ v123412341234
r = 0r = 1r = 2
10∞∞10∞∞10∞∞1
220∞∞20∞320∞3
3∞−70∞∞−70∞−5−70−4
4∞5100∞510075100
u \ v12341234
r = 3r = 4 (returned)
10∞∞104111
220∞320133
3−5−70−4−5−70−4
45310053100

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.

Index r means "vertices 1 to r may be in the middle," not "r edges"A common slip is to describe OPT[u][v][r] as "shortest walk with at most r edges"; that is the Day 3 worksheet's subproblem and leads to an O(mn²) algorithm. Another is to forget the diagonal: d[u][u][0] = 0, not ∞ (unless you are deliberately looking for cycles, as in PS 5.4's alternative solution).
How this is testedA design problem can call Floyd-Warshall by name and then read the answer off its table (PS 5.4, reused as Midterm 2's Problem 3), or reuse its one-line update idea (Practice Midterm 2, Problem 5: adding one edge to an existing table in O(n²)). When computing table r by hand, look only at row r and column r of the previous table: a cell (u, v) can change only if both d[u][r] and d[r][v] are finite.

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 = 0123
102∞
2∞03
3−4∞0
r = 1123
1
2
3
AnswerTable 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.

Key points

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 inputOutputRunning timeTechnique
BFS (§2.1)all lengths equal and positived from sO(m + n)search
DAG-DP (§5.1)a DAG; any lengths, negative allowedd from s (also longest, widest)O(m + n)DP over topological order
Bellman-Ford (§5.2)any directed graph with no negative cycled from s; column k = at most k edgesO(mn); O(mk) for k columnsDP on (vertex, number of edges)
Dijkstra (§5.3)all lengths ≥ 0d from sO(n²) with arrays; O(m log n) with a heapgreedy
Floyd-Warshall (§5.4)no negative cycleall-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

PS 5.1. The input is (G, s), where G is a DAG, every edge e has a "width" w(e) > 0, and s is a vertex in G. For this problem, we define the "width" of any path P to be the minimum edge width in P. Our goal is to find paths from s whose widths are maximized. More specifically, the algorithm should return an array d such that for every vertex v, d[v] is the width of the widest path from s to v. Describe an O(m + n)-time algorithm for this problem, explain why it's correct, and analyze its running time.
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.

421353121123456

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

PS 5.2. The input is (G, e, s, t) where G is a directed graph, all edge lengths are non-negative except e has length ℓ(e) < 0, and s, t ∈ V. Assume that G does not have a negative cycle. Describe an O(n²)-time algorithm that returns the length of the shortest path from s to t, explain why it's correct, and analyze its running time.
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

PS 5.3. The input is (G, s, t), where G is a directed graph, each edge e has a length ℓ(e) ≥ 0, and s, t ∈ V. A walk is even if it contains an even number of edges. Describe an O(n²)-time algorithm that returns the length of the shortest even walk from s to t (or ∞ if no such walk exists), explain why it's correct, and analyze its running time.
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.

251111satxy 225511111111s₀s₁a₀a₁t₀t₁x₀x₁y₀y₁d = 0d = ∞d = 5d = 3d = 7d = ∞d = 5d = 2d = 6d = 4copy 0 = switch OFF(even edges so far)copy 1 = switch ON(odd edges so far)
StepEdge crossedEdges so farPosition in G′Distance
0start0s00
1s → t (2)1t12
2t → x (1)2x03
3x → y (1)3y14
4y → t (1)4t05

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

PS 5.4. The input is a directed graph G with (possibly negative) edge lengths, but no negative cycle. Our goal is to return the length of the shortest-length cycle in G. (Recall that a cycle is not allowed to repeat vertices except the first and last, and the length of a cycle is the sum of the lengths of the edges in the cycle. Assume that G does not contain any edge pointing from a vertex to itself, but two vertices can form a cycle by pointing to each other.) Describe an O(n³)-time algorithm that solves this problem, explain why it's correct, and analyze its running time. (If G does not contain a cycle, ALG should return ∞.)
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

Worksheet for Day 3, Problem 3. The input is (G, s, t, B) where G is a directed graph, every edge e has some length ℓ(e) (possibly negative) and some positive integer cost c(e), s, t ∈ V, and B is a positive integer. (Note that G might have a negative cycle.) Describe an O(mB)-time algorithm that returns the length of a shortest s-t walk, among all walks whose total cost is at most B, or ∞ if no such walk exists.
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 \ j0123
10000
2∞444
3∞∞22
4∞∞75

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.

How to answer these fastDecode the adjacency lists into an edge list first and draw the graph. For DAG-DP, write a topological order; for Bellman-Ford, fill the table column by column (n − 1 columns) or, on a tiny graph, check every simple path; for Dijkstra, keep the d-row and the set S. On the exam the answer is the whole array d[1], …, d[n], in that order, with ∞ for unreachable vertices.

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)

Midterm 2, 1(a). Suppose we run Dijkstra's algorithm on the graph above. (For this subproblem, pretend that the minus signs next to the edge lengths do not exist, so for example, the length of (2, 4) is 3.) What are the final values in d? 423−38−4512345
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.
Midterm 2, 1(b). Suppose we run Bellman-Ford on the graph above. What are the final values in d?
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). 423−38−4512345

Midterm 2, Problem 3 (identical to PS 5.4)

Midterm 2, Problem 3. The input is a directed graph G with (possibly negative) edge lengths, but no negative cycle. Our goal is to return the length of the shortest-length cycle in G. (Recall that a cycle is not allowed to repeat vertices except the first and last, and the length of a cycle is the sum of the lengths of the edges in the cycle. Assume that G does not contain any edge pointing from a vertex to itself, but two vertices can form a cycle by pointing to each other.) Describe an O(n³)-time algorithm that solves this problem, explain why it's correct, and analyze its running time. (If G does not contain a cycle, ALG should return ∞.)
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

Midterm 2, Problem 5. The input is (G, s, t), where G is a directed graph, each edge e has a length ℓ(e) > 0, and s and t are two different vertices in G. We want to return the distance from s to t, but we can set the length of a single edge (of our choice) to 0. Describe an O(n²)-time algorithm for this problem, explain why it's correct, and analyze its running time. Examples: If G is just a single edge (s, t), then ALG should return 0. If G is just a path (s, u, t) with two edges, then ALG should return min(ℓ(s, u), ℓ(u, t)).
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.

1110sat 1110sat

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)

Practice Midterm 2, 1(a). Suppose we run Dijkstra's algorithm on the graph above. (For this subproblem, pretend that the minus signs next to the edge lengths do not exist, so for example, the length of (2, 3) is 2.) What are the final values in d? 26−2−43−1112345
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.
Practice Midterm 2, 1(b). Suppose we run Bellman-Ford on the graph above. What are the final values in d?
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). 26−2−43−1112345

Practice Midterm 2, Problem 3 (identical to PS 5.2)

Practice Midterm 2, Problem 3. The input is (G, e, s, t) where G is a directed graph, all edge lengths are non-negative except e has length ℓ(e) < 0, and s, t ∈ V. Assume that G does not have a negative cycle. Describe an O(n²)-time algorithm that returns the length of the shortest path from s to t, explain why it's correct, and analyze its running time.
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

Practice Midterm 2, Problem 5. The input is (G, d, e, w), where G is a directed graph, every edge e has a (possibly negative) length ℓ(e), G has no negative cycles, d is the output of Floyd-Warshall on G, and e = (a, b) (where a, b ∈ V) is a directed edge not in G with length w ≥ 0. Consider the graph G′, defined as G with the addition of e. Our goal is to return d′, the output of Floyd-Warshall on G′. Describe an O(n²)-time algorithm for this problem, explain why it's correct, and analyze its running time.
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

Practice Final, Problem 5. The input is (G, s), where G is a directed graph, every edge e has a length ℓ(e), and s ∈ V; assume that G has no negative cycles. Our goal is to return an array d such that for every vertex u, d[u] is the length of a shortest path, among all paths that have at most 10 edges, from s to u. If every path from s to u has more than 10 edges, then d[u] should be ∞. Describe an O(m)-time algorithm for this problem, explain why it's correct, and analyze its running time.
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.

What to noticeEvery shortest-path design problem so far is one of four moves: call a named algorithm and read its output (PS 5.4); split on whether one special edge is used (PS 5.2, Practice Midterm 2 Problem 5); add copies of every vertex to track a small state (PS 5.3, Midterm 2 Problem 5); or change the second index of the Bellman-Ford table (Practice Final Problem 5, the Day 3 budget problem). In every one, the correctness paragraph is "the optimal path either … or …, and the algorithm considers both," and the running time is the named algorithm's time plus the cost of building the new graph.

Before moving on

Exercises

7.1. State the DAG-DP recurrence with its base case, say in what order the vertices are processed and why that order makes every needed value available, and give the running time with its justification.
SolutionOPT[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).
7.2. Run DAG-DP from s = 1 on the DAG with edges (1, 2) of length 3, (1, 3) of length 1, (3, 2) of length −2, (2, 4) of length 4, (3, 4) of length 7, (2, 5) of length 2, (4, 5) of length −5. Give a topological order and the final d.
SolutionOrder 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].
7.3. For the same DAG, what are the longest-path values from 1, and what changes in the pseudocode? Why would the same change fail on a graph with a cycle?
SolutionReplace 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).
7.4. Fill in the Bellman-Ford table for s = 1 on the graph with edges (1, 2) of length 6, (1, 3) of length 7, (3, 2) of length −3, (2, 4) of length −1, (3, 4) of length 2, and give the final d.
Solutionn = 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].
7.5. Explain why column n − 1 of the Bellman-Ford table equals the true distances when there is no negative cycle, and say what goes wrong when there is one.
SolutionOPT[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.
7.6. Run Dijkstra from s = 1 on the graph with edges (1, 2) of length 4, (1, 3) of length 1, (3, 2) of length 2, (2, 4) of length 5, (3, 4) of length 8, (2, 5) of length 1. Give the order in which vertices enter S and the final d.
SolutionStart [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].
7.7. A student writes: "Dijkstra's algorithm is correct whenever the graph has no negative cycle, because then shortest paths are well defined." What will the grader object to? Give a counterexample.
SolutionDijkstra 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.
7.8. Three vertices with edges (1, 2) of length 3, (2, 3) of length −1, (1, 3) of length 5, (3, 1) of length 2. Write Floyd-Warshall's tables for r = 0, 1, 2, 3 (rows u = 1, 2, 3).
Solutionr = 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.
7.9. (Design.) The input is (G, s), where G is a directed graph with nonnegative edge lengths and s ∈ V. Describe an O(n²)-time algorithm that returns the length of the shortest cycle that passes through s, or ∞ if there is none, explain why it is correct, and analyze its running time.
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.

7.10. (Design.) The input is (G, s, t), where G is a directed graph with ℓ(e) ≥ 0 for every edge and s, t ∈ V. Describe an O(n²)-time algorithm that returns the length of the shortest s→t walk whose number of edges is a multiple of 3 (or ∞ if none exists), explain why it is correct, and analyze its running time.
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.

Key points

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:

31281351512345

The Flow-Cut Lemma

Flow-Cut LemmaFor any feasible flow f and s-t cut S, |f| = fout(S) − fin(S) ≤ c(S).

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.

  1. For s, the net outflow fout(s) − fin(s) equals |f|, because no edges enter s, so fin(s) = 0.
  2. 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).
  3. So |f| = Σu ∈ S (fout(u) − fin(u)). Expand each term into "flow on edges leaving u minus flow on edges entering u".
  4. 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.
  5. 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.

c(S) counts only edges leaving SIn the main example, S = {1, 3} has edges 1 → 2 (3), 3 → 4 (3) and 3 → 5 (5) leaving it, so c(S) = 11. The edge 2 → 3 crosses the boundary too, but it enters S, so it does not count toward the capacity, even though it appears with a minus sign in fout(S) − fin(S). Mixing the two formulas is the most common arithmetic error in this chapter.
How this is testedThe definitions feed every flow question: Problem 1–2 parts ask for a maximum flow value or a minimum cut and you check your answer by exhibiting a flow and a cut with the same number; True/False parts test the lemma ("if some s-t cut has capacity 10, every flow has value at most 10"). In Problems 3–8 the lemma is the tool for "why is it correct": you show your flow value equals some cut's capacity, or that a better solution would give a flow larger than a cut.

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.

5/62/22/33/81/11234
AnswerEvery 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)
Answerc({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.

Key points

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:

111111234

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.

1/10/11/10/11/11234

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:

111111234

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.

1/11/10/11/11/11234

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:

31281351512345

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:

3511235312312345

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.

36111251311412345

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.

3666213115412345
IterationPath P in GfEdge typesResidual capacities on PΔP|f| after
11 → 2 → 3 → 4 → 5F F F F3, 8, 3, 1533
21 → 3 → 2 → 4 → 5F B F F12, 3, 1, 1214
31 → 3 → 5F F11, 559
Edge of G(1, 2)(1, 3)(2, 3)(2, 4)(3, 4)(3, 5)(4, 5)
c(e)312813515
f after iteration 13030303
f after iteration 23121304
f after iteration 33621354

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.

3/36/122/81/13/35/54/1512345

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.

  1. 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*.
  2. 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*.
  3. 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.

Search Gf, not G, and subtract on backward edgesTwo slips cost points on traces. First, running greedy on G (as in the lecture's Idea 1) and reporting a flow that is not maximum; the answer must come from paths in the residual graph. Second, when P uses a backward edge v → u, the flow on the original edge (u, v) decreases by ΔP; adding it instead creates flow on an edge that was full and breaks conservation.
How this is testedA Problem 1–2 part gives a small network and asks for the value of a maximum s-t flow (Practice Final 1a; answer 7, worked in Section 8.7). Do not run the algorithm slowly on the exam: guess a good flow by eye, then find a cut with the same capacity; the Flow-Cut Lemma certifies the number. In Problems 3–8 you "call Ford-Fulkerson" by name with its O(mv) running time, and the work is in building the network and bounding v.

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).

132121234
Edge (c)(1, 2) (1)(1, 3) (3)(2, 3) (2)(2, 4) (1)(3, 4) (2)
f(e)
forward
backward
Answerf = 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).

AnswerPaths: 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". 1/12/30/21/12/21234

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.

Key points

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).

NetworkMax flow valueS reachable from s at the endEdges leaving Sc(S)
Greedy counterexample (all capacities 1)2{1}1 → 2, 1 → 32
Main example (Worksheet Day 1)9{1, 2, 3}2 → 4, 3 → 4, 3 → 59
Lecture 11-10 example3{1, 3}1 → 2, 3 → 43
Practice Final 1a7{1, 3}1 → 2, 3 → 47

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. ∎

Max-Flow Min-Cut TheoremIn every flow network (G, s, t), the value of a maximum s-t flow is equal to the capacity of 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).

A saturated edge is not necessarily a cut edgeIn the main example the edge 1 → 2 carries 3/3, but it does not leave S = {1, 2, 3}; the only minimum cut is {1, 2, 3} (every other cut containing 1 and not 5 has capacity 11 or more). The minimum cut is defined by reachability in Gf, and "all edges leaving S are saturated" is a consequence, not a recipe.
How this is testedOne-point parts can ask for a minimum cut (list the vertices of S) or its capacity, which is always the max flow value. In Problems 3–8, "Minimum-st-Cut" may be called by name; PS 6.1 and PS 6.2 below are the model answers, and their justification is always the Max-Flow Min-Cut Theorem ("minimizing the max flow is the same as minimizing the min cut").

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.

Key points

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}.

123456

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:

11166666111s123456t

Ford-Fulkerson with DFS (s first tries 1, then 2, then 3; ties toward the smallest label) runs three iterations:

IterationAugmenting path in G′fΔMatching after the iteration
1s → 1 → 4 → t1{1, 4}
2s → 2 → 4 → 1 → 5 → t (4 → 1 is a backward edge)1{2, 4}, {1, 5}
3s → 3 → 6 → t1{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:

1/11/11/10/61/61/60/61/61/11/11/1s123456t 123456

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. ∎

The reduction format (notes, Remark after Section 6.3)Given an instance X of problem A: (1) convert X to an instance Y of another problem B; (2) optimally solve Y to obtain a solution S′; (3) convert S′ to a solution S for X; (4) show that S is optimal for X because S′ is optimal for Y. The lecture: "Reduction from A to B: how to solve A using an ALG for B." Step (4) usually splits into "S is feasible" and "a better solution for X would give a better solution for Y".

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".

Bound v before writing O(mv)On a problem that asks for O(mn), writing "Ford-Fulkerson runs in O(mv)" and stopping loses the running-time point. You must say why v ≤ n (here: the cut {s} has capacity |L|), and then O(mv) = O(mn). The same step appears in every application of the chapter.
How this is testedProblems 3–8 that describe an assignment ("each child receives at most 2 gifts", "each project takes at most k students") are bipartite matching with modified capacities; the answer is the Section 8.4 network with one or two capacities changed, then "call Ford-Fulkerson", then the three-part correctness proof above. A one-point part could ask for the size of a maximum matching.

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.

1234
AnswerPath 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?

AnswerEach 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.

Key points

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}).

123456

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}.

1/10/11/11/60/60/61/60/61/11/10/1s123456t

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.

123456

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.

(L \ S) ∪ (R ∩ S), not the other way aroundLeft vertices go into the cover when they are outside S (their s-edge is cut); right vertices go in when they are inside S (their t-edge is cut). Swapping the two returns, in the example, {1, 2} ∪ {5, 6}, which misses the edge {3, 4} entirely. Derive it from "the cover is the set of vertices whose capacity-1 edge is cut" rather than memorizing it.
How this is testedExpect a True/False on matching versus vertex cover (Check-in 8.8 is the worksheet version) and, in Problems 3–8, the reduction-proof format: feasibility by contradiction with the capacity-n edges, the size equality, and optimality by converting a better solution back into a cheaper cut.

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.

123
AnswerFalse. 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

PS 6.1. The input is a directed graph G, where every edge has capacity 1. Describe an O(mn²)-time algorithm that returns the capacity of a minimum cut (not equal to V or ∅) in G, explain why it's correct, and analyze its running time.
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

PS 6.2. The input is an instance (G, s, t) of Maximum Flow where c(e) = 1 for every edge e, and an integer k ≤ m. Our goal is to decrease the maximum s-t flow value in G by as much as possible by removing at most k edges from G. Give an O(mn)-time algorithm that returns a list of edges we should remove, explain why it's correct, and analyze its running time.
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)

PS 6.3. The input is an instance of maximum flow (G, s, t) (where G is directed), except in addition to edge capacities, every vertex u ∈ V \ {s, t} also has a capacity c(u) > 0. Our goal is to return a maximum s-t flow that is feasible in the usual sense, and for every u ∈ V \ {s, t}, the total amount of flow entering u must be at most c(u). Describe an O(mv)-time algorithm for this problem (where v is the value of the optimal flow), explain why it's correct, and analyze its running time.
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:

in G: in G′: ──c(e)──▸ (u) ──▸ ──c(e)──▸ (u_in) ──c(u)──▸ (u_out) ──▸ cap c(u)
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

PS 6.4. The input is (G, s, t, u), where G is a connected, undirected graph and s, t, u are three distinct vertices in G. Our goal is to determine (i.e., return True/False) if G has an s-t path (i.e., no vertices repeated) that passes through u. Describe an O(m)-time algorithm for this problem, explain why it's correct, and analyze its running time. Hint: Set the capacity of each vertex to be 1 and find a flow from u. (You may use the algorithm from Problem 6.3, which finds a maximum flow that satisfies both vertex and edge capacities.)
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

PS 6.5. The input is (w, g, τ), where w is an array of n integers and w[i] is the number of wins that team i has already won, g is an n × n array and g[i][j] is the number of games remaining between teams i and j, and τ ∈ {1, …, n} is a team. (Every game always results in a win for one team and a loss for the other.) Our goal is to determine if it is possible for τ to end with the most number of wins (possibly tied) among all n teams. Describe an O(n²v)-time algorithm that solves this problem, where v is the total number of remaining games, explain why it's correct, and analyze its running time.
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.

161∞∞∞∞∞∞134s1,21,32,3123t

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.

161∞∞∞∞∞∞134s1,21,32,3123t

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.

623811234

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).

6/61/20/36/81/11234

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).

45234253123456 3/44/50/23/34/42/25/52/3123456
The by-hand method for Type 1Guess a flow greedily (fill obvious paths first), then look for the cut that "explains" why you cannot push more: usually the set of vertices you can still reach. If the numbers match, write the number. If they do not, there is an augmenting path through a backward edge; look for one.

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.

1532432233123456

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

Exercises

8.1. Run Ford-Fulkerson (DFS, ties toward the smallest label) on the network below with s = 1, t = 5. List each augmenting path with its Δ, give the maximum flow value, and give the minimum cut S reachable from 1 at the end with its capacity. 243312412345
Solution
IterationPathTypesResidual capacitiesΔ|f|
11 → 2 → 3 → 4 → 5F F F F2, 3, 1, 411
21 → 2 → 3 → 5F F F1, 2, 212
31 → 3 → 2 → 4 → 5F B F F4, 2, 3, 324
41 → 3 → 5F F2, 115

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).

2/23/40/32/31/12/23/412345
8.2. In network X of Section 8.7 (s = 1, t = 6), after the first augmentation along 1 → 2 → 4 → 6 with Δ = 3, which s-t path does DFS find next (ties toward the smallest label), and what is its Δ?
SolutionThe 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.)
8.3. For the bipartite graph below (L = {1, 2, 3, 4}, R = {5, 6, 7, 8}), give the size of a maximum matching and a minimum vertex cover, and check the cover against the formula (L \ S) ∪ (R ∩ S) of Bipartite-VC. 12345678
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}.

12345678
8.4. True or False; correct each false statement. (a) Ford-Fulkerson runs in O(m + n) time. (b) When Ford-Fulkerson stops, its residual graph has no s-t path. (c) Every edge with f(e) = c(e) in a maximum flow leaves every minimum cut. (d) The capacity of every minimum s-t cut equals the maximum flow value.
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.
8.5. A student computes the capacity of the cut S = {1, 3} in the main example as 3 + 3 + 5 + 8 = 19. What will the grader object to, and what is the right value?
SolutionThe 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.
8.6. The input is (G, s, t), where G is a directed graph and s, t are distinct vertices. Two s-t paths are edge-disjoint if they share no edge. Describe an O(mn)-time algorithm that returns the maximum number of edge-disjoint s-t paths in G, explain why it's correct, and analyze its running time.
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).

8.7. Students L and projects R form a bipartite graph: an edge {i, j} means student i would accept project j. Project j can take at most k[j] students, and each student does at most one project. Describe an O(mn)-time algorithm that assigns as many students as possible, explain why it's correct, and analyze its running time.
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).

8.8. The lecture's baseball example: w = [92, 91, 91, 90], τ = 4, and five games are left, one between every pair of teams except teams 1 and 4. Can team 4 end with the most wins (possibly tied)? Give the PS 6.5 network's g*, the capacities of the edges into t, and the maximum flow value.
SolutionNo. 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.
8.9. The notes give the L-to-R edges of the matching network capacity n and remark that any positive integer works for matching "but this one will be useful in the next section". Explain why capacity 1 would be enough for Bipartite-Matching but could break Bipartite-VC, using the graph with a single edge {1, 2}, L = {1}, R = {2}.
SolutionFor 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.

Key points

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

Definition (course notes, Chapter 8)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. For a minimisation problem, an α-approximation algorithm (for some α ≥ 1) satisfies, on every instance X,

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 satisfies

OPT(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:

ProblemTypeBound on OPT used in the notesWhy every solution obeys it
Vertex Covermin|OPT| ≥ |M| for the matching M the algorithm buildseach vertex covers at most one edge of a matching
Load BalancingminT* ≥ Σ ℓ[j] / m and T* ≥ ℓ[k] for every job kthe maximum load is at least the average load; every job sits on some machine
Metric k-Centermintwo points in one optimal cluster are within 2r* of each othertriangle inequality through the cluster's center
Maximum CutmaxOPT ≤ w(E)a cut cannot contain more than all the edges
Flipping the inequality for maximisationFor a maximisation problem the factor is below 1 and the guarantee is a lower bound on ALG: "1/2-approximation" means ALG ≥ OPT/2, never ALG ≤ OPT/2. Equivalently, you prove OPT ≤ 2 · ALG. Writing "ALG ≤ 12 OPT" in a proof for Maximum Cut or Maximum Matching states the opposite of what you want.
How this is testedProblems 1 and 2 of the final use one-point arithmetic questions on the definition (Homework 8, Q3: "OPT has size 30; what is the largest possible |S|?" Answer 60. "ALG returns 30; what is the smallest possible |S*|?" Answer 15) and True/False questions like Practice Final 2d and 2e. Problems 3 to 8 use the definition as the target of a proof: "Prove that this is a 1/2-approximation algorithm" or "Is this a 1/Δ-approximation algorithm? Prove it, or give a counterexample" (Section 9.6).

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.

Key points

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.

1234567

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.

Greedy by degree (4 vertices). 1234567
Optimal cover (3 vertices). 1234567

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).

StepEdges left before the stepEdge pickedS 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}
4nonestop{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.

1234567

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):

  1. Let M be the set of edges the algorithm "focuses on". Each iteration adds exactly two new vertices, so |S| = 2 · |M|.
  2. 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}.
  3. 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).

"OPT ≥ |M|" needs M to be a matchingThe bound |OPT| ≥ |M| holds only because the edges of M are pairwise disjoint. For an arbitrary set of edges it is false (the three edges of a star share the center, and one vertex covers all of them). When you reproduce the proof, say explicitly why M is a matching.
How this is tested"Name and prove a 2-approximation for Vertex Cover" is a direct exam question; the counting argument (one vertex of OPT per edge of M) is also the model for Problem Set 8.1 / Practice Final Problem 4 (Section 9.6) and Practice Final Problem 8. The True/False question "Any 2-approximation algorithm for Vertex Cover is also a 3-approximation algorithm" (Practice Final 2d) is answered in Section 9.1.

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.

123456
AnswerPicked {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. 123456

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.

Key points

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 beforeMachine chosenLoads after
15[0, 0, 0]1 (tie, smallest label)[5, 0, 0]
21[5, 0, 0]2 (tie between 2 and 3)[5, 1, 0]
34[5, 1, 0]3[5, 1, 4]
42[5, 1, 4]2[5, 3, 4]
53[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.

M1j1: 55M2j2j4: 2j5: 36M3j3: 44greedy (ALG): makespan T = 6
M1j1: 55M2j2j3: 45M3j4: 2j5: 35optimal: 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.

  1. 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].
  2. 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.
  3. Second lower bound on OPT. OPT must put job k on some machine, whose load is then at least ℓ[k]: T* ≥ ℓ[k].
  4. 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.

Assigning a job to the machine where it fits bestGreedy puts the job on the machine with the smallest load before the job is added, whatever happens afterwards. Do not look ahead, do not sort unless the problem says so, and break ties toward the smallest machine number. In the lecture's example, job 5 goes to machine 2 (load 3) and creates the makespan 6.
How this is testedA one-point part asks for greedy's makespan on a small instance (Practice Final 2c: job lengths [3, 1, 2, 3], m = 3, answer 4; Homework 8 Q1: ℓ = [1, 1, 2], m = 2, answer 3) or the optimal makespan (Homework 8 Q1.2, answer 2). Problem Set 8.2 and 8.3, both candidates for verbatim reuse, ask for a tight instance and for the 3/2 proof of the sorted version (Section 9.7).

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 j123456
ℓ[j]234622
machine
loads after
AnswerMachines 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.

Key points

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.

10223349510615
RoundCenters Sdist to closest center: points 1, 2, 3, 4, 5, 6Farthest point added
start{1}0, 2, 3, 9, 10, 156 (distance 15)
1{1, 6}0, 2, 3, 6, 5, 04 (distance 6)
2{1, 6, 4}0, 2, 3, 0, 1, 0stop (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.

10223349510615greedy centers 1, 6, 4 (shaded): radius 3

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*).

  1. 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*.
  2. 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.
  3. 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.

Forgetting where the triangle inequality is usedA full answer names the triangle inequality at the two places it is used: d(p, t) ≤ d(p, t*) + d(t*, t) in Case 1, and d(u₁, u₂) ≤ d(u₁, c) + d(c, u₂) in Case 2. Without it the algorithm can be arbitrarily bad, which is why the notes require d to be a metric. Also: the farthest point is measured to its closest center, not to the most recent one.
How this is testedOne-point questions ask which points can be the next center (Homework 8 Q4, Section 9.8). Problem Set 8.4 uses a hypothetical 1.9-approximation for Metric k-Center inside an algorithm for Dominating Set; it is a problem-set problem and so a candidate for verbatim reuse (Section 9.7).

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.

roundcenters beforeclosest-center distances of points 1–6point added
1{1}
2
AnswerRound 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.

Key points

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.

441571234

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:

IterationS beforeVertex moved, gainS afterCrossing edges afterw(δ(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 gainstop20

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.

441571234

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:

  1. 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).
  2. 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."
  3. 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).
  4. Upper bound on OPT: no cut contains more than all edges, so OPT ≤ w(E).
  5. 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.

Moving the vertex with the largest gainThe algorithm moves any vertex whose move helps; the exam fixes the choice by "pick the one with the smallest label". In iteration 1 of the trace, vertex 4 has the largest gain (13), but vertex 1 (gain 9) is moved. A trace that always picks the best move gives different intermediate weights and loses the point.
How this is testedHomework 8 Q5 asks for the maximum cut weight, the cut weight after 1, 2, 3 iterations and the returned weight (Section 9.8); expect the same shape in Problem 1 or 2. Practice Final 2e ("Any 1/2-approximation algorithm for Maximum Cut is also a 1/3-approximation algorithm") is True. The "half of each vertex's edges" counting reappears in Exercise 9.10.

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.

324511234
iteration12345
vertex moved
w(δ(S)) after
AnswerMove 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. 324511234

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.

Key points
Recipe A: "Prove that this is an α-approximation algorithm"
  1. Feasibility. One sentence: why the output is a valid solution (a matching, a cover, an independent set).
  2. 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).
  3. 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).
  4. Bound on ALG. Show each element of ALG receives at most c elements of OPT.
  5. 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|.)
Recipe B: "Is this an α-approximation? Prove it, or give a counterexample"
  1. 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.
  2. First word. "Yes." or "No."
  3. If Yes: follow Recipe A.
  4. 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.

  1. 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.
  2. 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*|.
  3. 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*).
  4. 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.
  5. 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}).

ALG may return {2, 3}. 1234
A maximum matching. 1234

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.

ALG may pick the center: |S| = 1. 12345
OPT takes the Δ = 4 leaves. 12345

The official solution, step by step (Recipe A inside Recipe B):

  1. First word. Yes.
  2. Feasibility. When u is added, all its neighbours are removed, so no later vertex is adjacent to u: S is independent.
  3. 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|.
  4. 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.
  5. 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.
  6. Conclusion. |OPT| = Σu∈S |OPT ∩ Su| ≤ Σu∈S Δ = Δ · |S|, so |S| ≥ |OPT|/Δ. ∎
Answering "No" because ALG is not optimal"Is this a 1/Δ-approximation?" is not asking whether ALG is optimal. The star shows ALG can be Δ times worse than OPT, and that is allowed by a 1/Δ guarantee. A counterexample must make ALG/OPT strictly smaller than 1/Δ (maximisation) or ALG/OPT strictly larger than α (minimisation).
How this is testedProblems 3 to 8 of the final include at least one approximation proof; Practice Final Problems 4 and 8 are the models, and Problem 4 was copied from Problem Set 8.1, so Problems 8.2, 8.3 and 8.4 (Section 9.7) are equally likely to reappear word for word. Points are lost for an assignment that is not shown to be well defined, for a missing "at most c per element" count, and for counterexamples without both values computed.

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?

AnswerPicking 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

PS 8.1. The input is an undirected, connected graph G, and our goal is to return a maximum matching in G. Consider the following algorithm:
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

PS 8.2. For any number of machines m ≥ 2, describe an instance of Load Balancing such that ALG / OPT = 2 − 1/m, where ALG and OPT denote the makespan of the greedy algorithm (without sorting, from Section 8.2 of the notes, Section 9.3 here) and the optimal makespan of the instance, respectively. Explain your answer (which should work for all m ≥ 2.)
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.

M111j7: 35M2112M3112greedy: T = 2m − 1 = 5
M1j7: 33M21113M31113optimal: T* = m = 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

PS 8.3. Consider the following algorithm for Load Balancing:
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

PS 8.4. In the DominatingSet problem, the input is (G, k), where G is an undirected, connected graph and k is a positive integer. Our goal is to return "yes" if G has a dominating set S such that |S| ≤ k and "no" otherwise, where S is a dominating set if for every vertex u, u ∈ S or u has a neighbor in S. Assuming that there exists a polynomial-time 1.9-approximation algorithm for Metric k-Center, describe a polynomial-time algorithm for DominatingSet and explain why it's correct.
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)

QuestionReasoningAccepted answer
ALG is a 2-approximation for Vertex Cover and OPT has size 30. Largest possible |S|?|S| ≤ 2 · 3060
ALG returns a cover of size 30. Smallest possible |S*|?30 ≤ 2 |S*|, so |S*| ≥ 1515
True or False? A 2-approximation for Vertex Cover is also a 3-approximation.|S| ≤ 2 OPT ≤ 3 OPTTrue

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

Practice Final 2c. Suppose we run the 2-approximation algorithm for Load Balancing on an instance with job lengths [3, 1, 2, 3] and m = 3 machines. What is the resulting makespan?
Solution4. 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

Practice Final 2d. True or False? Any 2-approximation algorithm for Vertex Cover is also a 3-approximation algorithm for Vertex Cover.
SolutionTrue. ALG ≤ 2 · OPT ≤ 3 · OPT for every instance.

Practice Final, Problem 2e

Practice Final 2e. True or False? Any 1/2-approximation algorithm for Maximum Cut is also a 1/3-approximation algorithm for Maximum Cut.
SolutionTrue. ALG ≥ OPT/2 ≥ OPT/3 for every instance.

Practice Final, Problem 4 (Problem Set 8.1)

Practice Final 4. The input is an undirected, connected graph G, and our goal is to return a maximum matching in G. Consider the following algorithm:
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

Practice Final 8. 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:
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|/Δ.

What to noticeThe two five-point problems are the same proof: a charging argument that assigns every element of OPT to an element of ALG that blocked it, and counts at most 2 (matching) or at most Δ (independent set) per element of ALG. The one-point parts test only the definition (2d, 2e) and the greedy trace (2c).

Before moving on

Exercises

9.1. (One point.) Greedy Load Balancing on ℓ = [1, 2, 3, 4, 5, 6] with m = 2: what is the makespan, and what is the optimal makespan?
SolutionLoads: [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.
9.2. (One point.) Metric k-Center on six points of a line at positions 0, 1, 5, 6, 7, 14 (point i at the i-th position), k = 2, first center 1. Which point is the second center, and what is the maximum radius of the result?
SolutionDistances 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.)
9.3. (One point each.) Maximum Cut on the graph with edges {1,2}: 2, {1,3}: 3, {2,3}: 4, {2,4}: 6, {3,4}: 1. Run the local search from S = ∅, moving the smallest-labelled vertex with a positive gain. What is the cut weight after 1 iteration, after 2 iterations, and at the end?
SolutionIteration 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.
9.4. True or false? (a) A 3/2-approximation algorithm for Vertex Cover is also a 2-approximation algorithm. (b) A 1/2-approximation algorithm for Maximum Cut is also a 2/3-approximation algorithm. (c) If a 2-approximation algorithm for Vertex Cover returns a cover of size 10, the minimum cover has at least 5 vertices. (d) The set M of edges picked by VC-Matching is always a maximum matching.
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.
9.5. Run the sorted greedy of Problem Set 8.3 on ℓ = [3, 3, 2, 2, 2] with m = 2. Is the result optimal? Is it consistent with the 3/2 guarantee?
SolutionSorted 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.
9.6. Consider the Load Balancing algorithm that puts every job on machine 1. Is it an m-approximation algorithm? Is it a 2-approximation algorithm for every m ≥ 2? Prove your answers or give counterexamples.
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.)

9.7. A variant of VC-Matching adds only one endpoint of each picked edge: "while G has an edge {u, v} with u < v, add v to S and remove v from G." Is it a 2-approximation for Vertex Cover? The first word of your answer should be "Yes" or "No".
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).

9.8. A student proves the Load Balancing bound like this: "On the lecture's example ALG = 6 and OPT = 5, and 6 ≤ 10, so T ≤ 2T*. Also T* = Σ ℓ[j] / m, so the bound follows." What will the grader object to?
SolutionTwo 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].
9.9. Show that the factor 2 in the analysis of VC-Matching cannot be improved: for every k ≥ 1, give a graph on which VC-Matching returns exactly 2 · OPT vertices.
SolutionTake 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.)
9.10. The input is an undirected graph G with positive edge weights. Consider this algorithm for Maximum Cut: process the vertices in the order 1, 2, …, n; put each vertex v into S or into V \ S, whichever side makes the total weight of edges from v to the already-placed vertices on the other side larger (ties may go either way). Prove that this is a 1/2-approximation algorithm and analyse its running time.
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

Not on the finalThe final covers "Ch. 1-8 except 7" (the instructor's margin notes of November 17, November 24 and December 1), and the course notes open Chapter 7 with "This chapter is rather informal; none of this content will be assessed on an exam." It is here only because it motivates the approximation algorithms of Chapter 9. Read it in fifteen minutes, or skip it.

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.

Key points

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.

"Unknown" is not "False"For 0/1 Knapsack or Vertex Cover, "there is no polynomial-time algorithm" is not known to be true. Proving it would prove P ≠ NP and win the Millennium Prize. The honest answer is "Unknown".

Check-in 10.1. Mark each running time as polynomial (P) or not polynomial (N) in the size of the input.

Running timeO(n³)O(n¹⁰⁰)O(2ⁿ)O(mn) for Bipartite-MatchingO(nB) for Knapsack-DP
P or N
AnswerP, 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.

Key points

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.

abcxyz

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:

111111sabcxyzt
StepWhat the reduction doesResult on the example
1. ConvertBuild G′ from G8 vertices, 11 edges
2. Solve BFord-Fulkerson(G′, s, t)a maximum flow of value 3: s→a→y→t, s→b→x→t, s→c→z→t
3. Convert backKeep the L-to-R edges with f(e) = 1M = {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.

111111sabcxyzt

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.

Reducing in the wrong directionTo argue that a new problem B is hard, reduce a known hard problem A to B (solve A using B). Solving B using an algorithm for A only shows that B is no harder than A, which says nothing about whether B is hard.
How this is testedIt is not, on this final. The same convert-solve-convert-back format is tested, though, whenever a Problem 3–8 asks for an algorithm that calls a named algorithm (Ford-Fulkerson, Minimum-st-Cut, Dijkstra on a modified graph).

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).

Key points

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:

StatementAccepted answerWhy
There exists a polynomial-time algorithm for Minimum Spanning Tree.TruePrim runs in O(mn) in the course notes, a polynomial.
There exists a polynomial-time algorithm for 0/1 Knapsack.UnknownThe notes name it as not known to be in P; O(nB) is not polynomial.
There exists a polynomial-time algorithm for Vertex Cover.UnknownIn 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.TrueBipartite-VC runs in O(mn).

Before moving on

Exercises

10.1. True, False, or Unknown? (a) There exists a polynomial-time algorithm for single-source shortest paths with nonnegative edge weights. (b) There exists a polynomial-time algorithm for Subset Sum. (c) There exists a polynomial-time algorithm for Bipartite Matching. (d) There exists an algorithm, of any running time, for Halting.
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".
10.2. A student writes: "0/1 Knapsack is in P, because Knapsack-DP solves it in O(nB) time." What is wrong?
SolutionO(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.
10.3. Bipartite-VC is a reduction from which problem A to which problem B? What would a fast reduction from (general) Vertex Cover to Bipartite Vertex Cover imply?
SolutionA = 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.
10.4. Run the reduction of Section 10.2 on the bipartite graph with L = {1, 2, 3}, R = {4, 5, 6} and edges 1–4, 2–4, 3–4, 3–5: list the capacities of G′, give the maximum flow value and a maximum matching.
Solutionn = 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.

The rules printed on the cover page
How to use this chapterPrint the worksheet version, set a timer for 3 hours, and write the whole exam on paper before opening a single solution. Budget about 25 minutes for Problems 1 and 2 together and about 25 minutes for each of Problems 3–8, which leaves a little time to check. Then mark your answers against the solutions below, one problem at a time, and reread the chapter that the "What to notice" box at the end names for every problem you missed.

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.

623811234s = 1t = 4
(a) What is the value of a maximum s-t flow in the instance above? (Your answer should just be an integer.) Course Ch. 6
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:

IterationAugmenting path in the residual graphBottleneckFlow value
11 → 2 → 3 → 4min(6, 3, 1) = 11
21 → 2 → 4min(5, 8) = 56
31 → 3 → 2 → 4 (uses the backward edge 3 → 2, undoing the unit on (2, 3))min(2, 1, 3) = 17

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.

6/61/20/36/81/11234s = 1t = 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.

(b) Suppose we run DFS on the graph above starting at s = 1. (Ignore the label t.) As usual, break ties in favor of the vertex with the smallest label. What are the post-values (starting with post[1])? Course Ch. 2
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):

tEventWhy
1pre[1] = 1start at s = 1
2pre[2] = 21's first out-neighbour is 2
3pre[3] = 32's first out-neighbour is 3
4pre[4] = 43's only out-neighbour is 4
5post[4] = 54 has no out-neighbours
6post[3] = 63 is finished
7post[2] = 72's other out-neighbour 4 is already visited
8post[1] = 81'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.

623811234s = 1t = 4
(c) Suppose we run Prim's algorithm on the graph above starting at s = 1. (Pretend that every edge is undirected, and ignore the label t.) List the edges chosen by the algorithm in the order in which they are chosen. Course Ch. 3
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:

RoundS beforeEdges 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.

623811234
(d) Suppose we run the O(n²)-time DP (dynamic program) for Longest Increasing Subsequence (LIS) on A = [5, 1, 7, 8, 2, 3]. What are the values in the array d? (Your answer should be 6 numbers.) Course Ch. 4
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.

i123456
A[i]517823
d[i]112323

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.

(e) Suppose we run the O(nB)-time DP for 0/1 Knapsack on v = [3, 4, 2], w = [2, 2, 1], B = 4. What are the values in the last row of d? (Your answer should be 5 numbers, starting with 0.) Course Ch. 4
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 = 01234
i = 1 (v 3, w 2)00333
i = 2 (v 4, w 2)00447
i = 3 (v 2, w 1)02467

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)

(a) Suppose we run the optimal greedy algorithm for Fractional Knapsack on v = [3, 4, 5], w = [2, 2, 1], B = 4. What are the values in x (starting with x[1])? Course Ch. 3
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 beforeAmount takenCapacity left after
3 (5)4x[3] = 1 (weight 1)3
2 (2)3x[2] = 1 (weight 2)1
1 (1.5)1x[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.

(b) What is the Edit Distance from abbc to babc? Course Ch. 4
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]])):

""babc
""01234
a11123
b21212
b32222
c43332
(c) Suppose we run the 2-approximation algorithm for Load Balancing on an instance with job lengths [3, 1, 2, 3] and m = 3 machines. What is the resulting makespan? Course Ch. 8
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):

JobLengthLoads beforeMachineLoads after
13(0, 0, 0)1(3, 0, 0)
21(3, 0, 0)2(3, 1, 0)
32(3, 1, 0)3(3, 1, 2)
43(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.)

(d) True or False? Any 2-approximation algorithm for Vertex Cover is also a 3-approximation algorithm for Vertex Cover. Course Ch. 8
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.

(e) True or False? Any 1/2-approximation algorithm for Maximum Cut is also a 1/3-approximation algorithm for Maximum Cut. Course Ch. 8
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.

Agreement checkAll ten one-point answers above were recomputed by a script (DFS, Prim, Ford-Fulkerson and a brute-force minimum cut, LIS, Knapsack-DP, Fractional-Knapsack, Edit-Distance, greedy Load-Balance), and every one agrees with both the official solutions and the instructor's handwritten 12-01 list: 1a 7, 1b [8, 7, 6, 5], 1c {1,3}, {3,4}, {2,3}, 1d [1, 1, 2, 3, 2, 3], 1e [0, 2, 4, 6, 7], 2a [0.5, 1, 1], 2b 2, 2c 4, 2d True, 2e True.

Problem 3. Buying and selling a stock (PS 4.5)

The input is an array A of n positive integers. The story is that we want to buy a stock on day i by spending A[i], sell the stock on day j and receive A[j], and we want to maximize our profit A[j] − A[i]. More specifically, the algorithm should return the maximum possible value of A[j] − A[i] over all pairs of indices (i, j) such that i < j. Describe an O(n)-time algorithm for this problem, explain why it's correct, and analyze its running time. Example: If A = [8, 2, 4, 7, 1, 3], the algorithm should return 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]:

j123456
A[j]824713
min_A before day j82221
d[j]−∞−625−12

max(d) = 5 (buy at 2 on day 2, sell at 7 on day 4).

Do not return max(A) − min(A)The maximum and minimum must come in the right order. For A = [8, 2, 4, 7, 1, 3], max(A) − min(A) = 8 − 1 = 7, but day 1 (price 8) comes before day 5 (price 1), so that "profit" is impossible. Notice also that the answer can be negative (A = [5, 3] gives −2): the problem asks for the best pair with i < j, not for the option of not trading.

Problem 4. A greedy matching is a 1/2-approximation (PS 8.1)

The input is an undirected, connected graph G, and our goal is to return a maximum matching in G. Consider the following algorithm:
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.

1234
The charging patternProblems 4 and 8 use the same proof shape, which the notes draw both times: assign every element of OPT to an element of ALG ("well-defined, because otherwise ALG would have picked it"), show each element of ALG receives at most c elements, and conclude |OPT| ≤ c · |ALG|. Learn it once, in Chapter 9, and use it for any "prove this greedy algorithm is a 1/c-approximation" problem.

Problem 5. Shortest paths with at most 10 edges

The input is (G, s), where G is a directed graph, every edge e has a length ℓ(e), and s ∈ V; assume that G has no negative cycles. Our goal is to return an array d such that for every vertex u, d[u] is the length of a shortest path, among all paths that have at most 10 edges, from s to u. If every path from s to u has more than 10 edges, then d[u] should be ∞. Describe an O(m)-time algorithm for this problem, explain why it's correct, and analyze its running time.
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.)

"BFS 10 steps, then Bellman-Ford" is too slowThe 12-01 notes record a tempting alternative in red: run BFS from s for 10 levels and then run Bellman-Ford on the subgraph reached. The instructor's objection: the subgraph "might be G", so Bellman-Ford on it can still cost O(mn). The fix is not to shrink the graph but to shrink the number of rounds. Also do not use Dijkstra: it ignores the edge-count limit and fails with negative lengths, which the problem allows.

Problem 6. Minimizing the heaviest edge of a spanning tree

The input is a connected, undirected graph G where every edge e has a distinct weight w(e) > 0. (In other words, G is an input to the MST problem, but our goal will be different.) Our goal is to return a spanning tree T such that maxe∈T w(e) is minimized. Describe an O(m²)-time algorithm for this problem, explain why it's correct, and analyze its running time.
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*).

  1. Every edge of T* weighs at most w(e*) < w(e), so e ∉ T*.
  2. T* is a spanning tree and e is not in it, so adding e to T* creates a cycle C.
  3. 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.
  4. 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.

The instructor's "often helpful" boxSuppose T is a spanning tree and e is an edge. If e ∈ T, removing e from T creates a cut. If e ∉ T, adding e to T creates a cycle. The first fact drives cut-property arguments, the second drives cycle-property arguments such as Problem 6.

Problem 7. Skipping the next B[i] elements

The input is (A, B), where A and B are both arrays of n integers. Our goal is to find a subsequence S of A such that the sum of the elements in S is maximized. However, if A[i] ∈ S, then S cannot contain A[i + 1], A[i + 2], …, A[i + B[i]]. (If i + B[i] > n, then S cannot contain anything after A[i].) In other words, if A[i] ∈ S, then S needs to skip the next B[i] elements in A. Describe an O(n)-time algorithm for this problem, explain why it's correct, and analyze its running time. The algorithm should return the sum of S, not S itself. Examples are below:
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:

i4321
A[i], B[i]2, 54, 44, 33, 2
i + B[i] + 1(base)8 > n6 > n4
d[i]2max(2, 4) = 4max(4, 4) = 4max(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.

Prefixes do not work hereA prefix subproblem ("best sum using A[1 : i]") cannot tell whether A[i] is allowed, because whether A[i] is blocked depends on which earlier element was chosen and how far its B-value reaches. The skip points to the right, so define the subproblems on suffixes and fill the table from right to left. Also, A may contain negative numbers ("arrays of n integers"), which is why the base case is max(A[n], 0).

Problem 8. Greedy independent set and the maximum degree

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:
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 ∆.

c1234
What to noticeProblems 1 and 2 are pure hand traces of named algorithms; each part was one table, and the only traps were reading the graph three ways (capacities, then DFS ignoring weights, then undirected weights) and writing the answer in the requested format (index order, edges in the order chosen). Problem 3 (Chapter 5, a one-variable DP) and Problem 4 (Chapter 9, charging argument) were copied verbatim from problem sets. Problem 5 is a "slightly modified" named algorithm, Bellman-Ford stopped early (Chapter 7). Problem 6 is a reduction to a named algorithm plus a cycle-property exchange argument (Chapter 4). Problem 7 is a fresh include/exclude DP on suffixes in the Knapsack mould (Chapter 6). Problem 8 is the charging argument of Problem 4 applied to vertices (Chapter 9). Every design answer used the same three labels, Algorithm, Correctness, Running time, and every approximation answer the same three steps: bound OPT, bound ALG, state the ratio.

Where the 40 points come from

ProblemTopicCourse chapter (guide chapter)Where the points come from
1(a)Maximum flow valueCh 6 (Chapter 8)Ford-Fulkerson, or a flow and a cut of equal value: 7
1(b)DFS post-valuesCh 2 (Chapter 3)Clock ticking at every pre and post, smallest label first
1(c)Prim edge orderCh 3 (Chapter 4)Lightest edge crossing S, in the order chosen
1(d)LIS array dCh 4 (Chapter 5)d[i] = longest increasing subsequence ending at i
1(e)0/1 Knapsack last rowCh 4 (Chapter 6)Full table, rows i = 1..n, columns 0..B
2(a)Fractional Knapsack xCh 3 (Chapter 4)Sort by v/w, fill greedily, list x in index order
2(b)Edit distanceCh 4 (Chapter 5)Two moves, or the DP table
2(c)Load Balancing makespanCh 8 (Chapter 9)Greedy in the given order, smallest load first
2(d), 2(e)Approximation ratiosCh 8 (Chapter 9)Direction of the inequality for minimization and maximization
3Best stock profit (PS 4.5)Ch 4 (Chapter 5)Running minimum; d[j] = A[j] − mini<j A[i]; O(n)
4Greedy matching (PS 8.1)Ch 8 (Chapter 9)Assign each OPT edge to an ALG edge; at most 2 per ALG edge
5Shortest paths with ≤ 10 edgesCh 5 (Chapter 7)Bellman-Ford's subproblem; 11 columns of O(m) each
6Minimum bottleneck spanning treeCh 3 (Chapter 4)Return the MST; contradiction via the cycle property; O(m²)
7Sum with skipsCh 4 (Chapter 6)Suffix subproblems, include or exclude A[i], fill right to left; O(n)
8Greedy independent setCh 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.

The cover page, as on the real examEvery problem is worth 5 points. Unless the problem states otherwise: (1) all algorithms refer to the ones described in the lectures and notes; (2) describe algorithms in pseudocode similar to the lecture examples (no hashing); (3) array indices start at 1; (4) the values in any 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. Ties are broken in favor of the smallest label. You may call 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, with every property proved in the notes, or a slightly modified version of any of them.

Problem 1 (five parts, one point each, no explanation)

(a) Suppose we run Binary-Search on A = [2, 4, 7, 9, 12, 15, 20] and t = 5. List the values of m that the algorithm computes, in order. Course Ch. 1
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.
(b) Suppose we run BFS on the graph below starting at s = 1. What are the values in the d array? Course Ch. 2 123456
Solutiond = [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). 123456
(c) Suppose we run Topological-Sort on the same graph (DFS explores vertex 1 first; as usual, ties are broken in favor of the smallest label). What list R does it return? Course Ch. 2
SolutionR = [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.
(d) Suppose we run Kruskal's algorithm on the graph below. List the edges chosen by the algorithm in the order in which they are chosen. Course Ch. 2 634172859123456
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. 634172859123456
(e) Suppose we run the O(n²)-time DP for Longest Palindromic Subsequence on A = abcbca. What are the values in the first row of d? (Your answer should be 6 numbers.) Course Ch. 4
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)

(a) Suppose we run Bellman-Ford (the original version, with the n × n table) on the graph below with s = 1. What are the values in the row of d for vertex 4, from d[4][0] through d[4][3]? Course Ch. 5 239−2511234
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: 239−2511234
(b) What is the value of a maximum s-t flow in the instance below, where s = 1, t = 6, and the numbers are capacities? (Your answer should just be an integer.) Course Ch. 6 542331523123456st
Solution6. 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: 5/51/42/23/33/30/13/50/23/3123456st
(c) Consider the instance of Metric k-Center with points X = {1, 2, 3, 4, 5, 6}, where point i sits at position p[i] on a line, p = [0, 2, 9, 10, 15, 18], the distance between i and j is |p[i] − p[j]|, and k = 3. Suppose we run the greedy 2-approximation algorithm from the course notes (which starts with S = {1}). List the centers in the order in which they are added. Course Ch. 8
Solution1, 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).
(d) True or False? When m = 3, the greedy algorithm for Load Balancing (jobs assigned in the given order, no sorting) is a 3/2-approximation algorithm. Course Ch. 8
SolutionFalse. 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.
(e) True or False? If an undirected graph G has a matching M, then every vertex cover of G has at least |M| vertices. Course Ch. 6
SolutionTrue. 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

The input is a connected, undirected graph G. We say that G is bipartite if there exists an array c such that c[u] ∈ {0, 1} for every u ∈ V, and for every {u, v} ∈ E, c[u] ≠ c[v]. (Equivalently, G is bipartite if we can color every vertex either red or blue such that every edge has differently colored endpoints.) Describe an O(m + n)-time algorithm that determines if G is bipartite (in which case it should return a valid c; otherwise, it should return nothing), explain why it's correct, and analyze its running time.
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

The input is (v, w, B), an instance of 0/1 Knapsack: v and w are arrays of n positive integers, B is a positive integer, and w[i] ≤ B for every item i. Our goal is to return a set of items whose total weight is at most B and whose total value is maximized. Consider the following algorithm:
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

The input is (G, s, t), where G is a directed graph, every edge e has a length ℓ(e) ≥ 0 and a color that is either red or blue, and s, t ∈ V. Our goal is to return the length of the shortest s-t walk that uses at least one red edge (or ∞ if no such walk exists). Describe an O(n²)-time algorithm for this problem, explain why it's correct, and analyze its running time. Example: If G has a blue edge (s, t) of length 1, a red edge (s, a) of length 2, and a blue edge (a, t) of length 2, then ALG should return 4.
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?

The input is (G, e), where G is a connected, undirected graph with distinct edge weights and e is an edge of G. Our goal is to determine (i.e., return True/False) if e is in the MST of G. Describe an O(m)-time algorithm for this problem, explain why it's correct, and analyze its running time. Example: If G is a triangle whose edges have weights 1, 2, 3, then ALG should return False for the edge of weight 3 and True for the other two.
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

The input is an m × n array A of positive integers. We start at (1, 1), we want to end at (m, n), and at each step we move either right or down (but not diagonally). The cost of a path is the sum of A[i][j] over every cell (i, j) on the path, including (1, 1) and (m, n). Describe an O(mn)-time algorithm that returns the minimum cost of such a path, explain why it's correct, and analyze its running time. Example: If A = [[1, 3, 1], [1, 5, 1], [4, 2, 1]], then the algorithm should return 7.
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

The input is an instance (G, s, t) of Maximum Flow where c(e) = 1 for every edge e, and an integer k ≤ m. Our goal is to decrease the maximum s-t flow value in G by as much as possible by removing at most k edges from G. Give an O(mn)-time algorithm that returns a list of edges we should remove, explain why it's correct, and analyze its running time.
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).

What to noticeProblem 1: (a) is the two-pointer loop of Chapter 2; (b) and (c) are BFS and Topological-Sort from Chapter 3, where the answer to (c) is simply "decreasing post-value"; (d) is Kruskal from Chapter 4 (write every rejected edge in your scratch work); (e) is the LPS table of Chapter 5. Problem 2: (a) is the original Bellman-Ford table of Chapter 7, read along a row; (b) is Chapter 8: guess a flow and certify it with a cut of the same capacity, counting only edges that leave S; (c) to (e) are Chapter 9. Problem 3 is PS 2.4 word for word (Chapter 3) and Problem 8 is PS 6.2 word for word (Chapter 8): know every problem-set solution. Problem 4 combines the approximation recipe of Chapter 9 with Fractional Knapsack from Chapter 4: the fractional optimum is the upper bound on OPT. Problem 5 is the two-copy graph trick of Chapter 7 (PS 5.3 and the Midterm 2 free-edge problem). Problem 6 uses both MST properties from Chapter 4, one per direction. Problem 7 is the grid pattern of PS 4.4 from Chapter 6. Every solution follows the same layout: Algorithm (or Subproblems and Recurrence), Correctness, Running time; for Problem 4, the bound on OPT, the bound on ALG, and the conclusion.

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.

Cover-page rules (the same as the real final)Unless a problem says otherwise: all algorithms are the ones from the lectures and notes; algorithms are described in pseudocode like the lecture examples (no hashing); array indices start at 1; the values of an array A are listed from A[1] through A[n]; a graph has vertex set V, edge set E, n = |V|, m = |E|, and is given in adjacency-list format; ties are broken in favour of the smallest label. You may call 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, with every property proved in the notes, or a slightly modified version of one of them if the modification is stated clearly.

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).

723694158123456
(a) Suppose we run Binary-Search on A = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] with t = 60. List the values of m in the order in which the algorithm computes them. Course Ch. 1
Solution5, 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.
(b) Suppose we run DFS on the graph above (ignore the weights). As usual, DFS considers the vertices in the order 1, 2, …, n and breaks ties in favour of the smallest label. What are the pre-values and the post-values (starting with pre[1] and post[1])? Course Ch. 2
Solutionpre = [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.
(c) Suppose we run Reverse-Delete on the graph above. (Pretend that every edge is undirected.) List the edges removed by the algorithm in the order in which they are removed. Course Ch. 3
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. 723694158123456 The edges that remain, {4, 5}, {1, 3}, {2, 3}, {3, 5}, {4, 6} (total weight 15), are exactly the edges Kruskal would pick.
(d) Suppose we run the O(nB)-time DP for 0/1 Knapsack on v = [4, 3, 5], w = [3, 1, 2], B = 5. What are the values in the last row of d? (Your answer should be 6 numbers, starting with 0.) Course Ch. 4
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).
(e) Suppose we run Dijkstra's algorithm on the graph above starting at s = 1. List the vertices in the order in which they are added to S. Course Ch. 5
Solution1, 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]. 723694158123456

Problem 2 (five parts, one point each, no explanation)

(a) In the flow network below, s = 1, t = 6, and the number on each edge is its capacity. Suppose we run Minimum-Cut (Ford-Fulkerson, then return the set S of vertices reachable from s in the final residual graph). What is S, and what is its capacity? Course Ch. 6 562342471123456
SolutionS = {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. 562342471123456
(b) Suppose we run the O(n²)-time DP for Longest Palindromic Subsequence on A = abacdba. What are the values in the first row of d? (Your answer should be 7 numbers.) Course Ch. 4
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.
(c) Suppose we run the 2-approximation algorithm for Load Balancing on an instance with job lengths [2, 4, 3, 5, 1, 4] and m = 3 machines. What is the resulting makespan? Course Ch. 8
Solution8. 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}.)
(d) True or False? A 2-approximation algorithm for Vertex Cover can return a vertex cover of size 7 on a graph whose minimum vertex cover has size 3. Course Ch. 8
SolutionFalse. A 2-approximation algorithm must return at most 2 · OPT = 2 · 3 = 6 vertices on that graph.
(e) True or False? If the capacity of every edge in a flow network is increased by 1, then the value of a maximum s-t flow increases by exactly 1. Course Ch. 6
SolutionFalse. 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

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, an integer that may be negative. A set S of vertices is connected if S is non-empty and for every two vertices u, v ∈ S, every vertex on the u-v path in T is also in S. Our goal is to return the maximum total weight Σu∈S w[u] over all connected sets S. Describe an O(n)-time algorithm for this problem, explain why it's correct, and analyze its running time. Examples: for the tree below, the algorithm should return 9 (S = {1, 2, 3, 4, 6}). If w[1] is changed to −10, it should return 8 (S = {2, 4}). If every weight is negative, it should return the largest single weight. 1w=−22w=53w=−14w=35w=−46w=4
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.

1w=−22w=53w=−14w=35w=−46w=4

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

Consider the following algorithm for Load Balancing:
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

The input is (G, s, t), where G is a directed graph, each edge e has a length ℓ(e) ≥ 0, and s, t ∈ V. A walk is even if it contains an even number of edges. Describe an O(n²)-time algorithm that returns the length of the shortest even walk from s to t (or ∞ if no such walk exists), explain why it's correct, and analyze its running time.
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.

251111satxy

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

The input is (G, s, t), where G is a DAG and s and t are two different vertices of G. Our goal is to return the number of vertices u such that G has an s-t path that passes through u (s and t themselves count; if s cannot reach t, the answer is 0). Describe an O(m + n)-time algorithm for this problem, explain why it's correct, and analyze its running time. Example: for the DAG below with s = 1 and t = 5, the algorithm should return 6 (the vertices 1, 2, 3, 4, 5, 8). 12345678
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.

12345678

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

The input is (G, s, t), where G is a directed graph, s and t are two different vertices of G, (s, t) ∉ E, and G (ignoring edge directions) is connected. Two s-t paths are internally vertex-disjoint if they have no vertex in common other than s and t. Our goal is to return the maximum number k such that G contains k s-t paths that are pairwise internally vertex-disjoint. Describe an O(mn)-time algorithm for this problem, explain why it's correct, and analyze its running time. Example: for the graph below, the algorithm should return 1, because every s-t path passes through c (even though there are two s-t paths that share no edge). sabcxyt
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

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. Consider the following algorithm:
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:

d123
10110
2109
31090

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.)

What to noticeProblem 1 tests Binary-Search (Chapter 2), DFS (Chapter 3), Reverse-Delete (Chapter 4), the 0/1 Knapsack table (Chapter 6) and Dijkstra (Chapter 7); one drawing serves three parts, as on the official Practice Final. Problem 2 tests Minimum-Cut (Chapter 8), the LPS table (Chapter 5), greedy Load Balancing with its tie rule, and the definition of an approximation ratio (Chapter 9), plus one flows fact. Problem 3 is a tree DP with one subproblem per vertex that must include the vertex (Chapter 6, patterns of Chapter 5). Problem 4 (Problem Set 8.3) is the lower-bound, upper-bound, conclusion recipe of Chapter 9. Problem 5 (Problem Set 5.3) is the "two copies of the graph" construction from Chapter 7. Problem 6 is a Problem Set 2 style search: Explore in G and in GR, then one pass (Chapter 3). Problem 7 is a reduction to maximum flow by vertex splitting, with the two-direction correctness argument of Chapter 8. Problem 8 is answered "No" with the smallest possible counterexample, its ALG, its OPT and the comparison (Chapter 9). Every 5-point solution has the same skeleton: Algorithm (or Subproblems and Recurrence), Correctness in both directions, Running time.

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).

PassClockWhat to doPoints at stake
00:00–0:05Read 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
10:05–0:30Problems 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
20:30–1:15The R problems, about 15 minutes each: the official solution from memory, in the three-part format, with its running-time sentence.10–15
31:15–2:45The 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
42:45–3:00The 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.

PSThe task in one lineTargetKey idea of the official solutionAlready reused
1.1Find the repeated element of an array of length n + 1 holding 1..nO(n)Return sum(A) − n(n + 1)/2, or mark seen elements in a binary array B (no hashing)
1.2Squares of a sorted array, in sorted orderO(n)Two pointers at both ends; write the larger square at the back of B and move that pointer
1.3Intersection of A (length m) and B (length n), m ≤ nO(n log m)Sort A, then binary-search A for each element of B
1.4Maximise (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 betterPractice Midterm 1, P2; Ch. 1 worksheet, Day 2
1.5Minimum difference between two elementsO(n log n)Merge Sort, then the minimum of consecutive differences
2.1Diameter of a connected undirected graphO(mn)BFS from every vertex, keep the largest max(d); n runs of O(m)Midterm 1, P2
2.2In a DAG, two vertices neither of which reaches the other, or nothingO(m + n)Topological order T; return the first consecutive pair (T[i], T[i + 1]) that is not an edgeCh. 2 worksheet, Day 3
2.3Label the connected components of an undirected graphO(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.4Is a connected graph bipartite? Return a coloring c or nothingO(m + n)BFS from 1 with c[1] = 0, color new neighbors 1 − c[u], return nothing on an edge with equal colorsThis guide: version A, P3
2.5Does 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.1k 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.2Order jobs to minimise the total waiting timeO(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.3Order jobs (p[i], d[i]) to minimise the maximum latenessO(n log n)Sort by deadline d; swapping an adjacent inverted pair cannot increase the maximum lateness
3.4New MST after the weight of a tree edge e increasesO(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 edgeMidterm 1, P3
3.5Fewest dimes, nickels and pennies for t centsO(1)Greedy, largest coin first; a case analysis shows OPT has the same number of dimes, then of nickels
4.1Sum of an array, as a DPO(n)OPT[i] = OPT[i − 1] + A[i], OPT[1] = A[1]
4.2Longest increasing contiguous subarrayO(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.3Cheapest jumps of 1 or 2 from index 0 to n + 1O(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.4Number of right/down paths in an m × n grid with obstaclesO(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 obstacleThis guide: version A, P7 (a variant)
4.5Best 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.6Largest sum with no two adjacent elementsO(n)OPT[i] = max(OPT[i − 1], A[i] + OPT[i − 2]): exclude or include A[i]
4.7Number of ordered ways to write n as a sum of A's and B'sO(n)OPT[i] = OPT[i − A] + OPT[i − B] (0 for negative indices), OPT[0] = 1; the last term is A or B
5.1Widest 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.2Shortest s-t path when exactly one edge e = (u, v) is negativeO(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.3Shortest s-t walk with an even number of edgesO(n²)Two copies of G with edges (u0, v1) and (u1, v0); Dijkstra from s0, return d[t0]This guide: version B, P5
5.4Length 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 ≠ vMidterm 2, P3
6.1Capacity of a global minimum cut, unit capacitiesO(mn²)Fix s = 1; for every t take the minimum s-t cut and the minimum t-s cut; return the smallest
6.2Remove 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.3Maximum 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 backCh. 6 worksheet, Day 3
6.4Is 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.5Baseball 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.1Prove 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.2A 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 = mCh. 8 worksheet, Day 2
8.3Prove 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.4Decide Dominating Set with a 1.9-approximation for Metric k-CenterpolynomialDistance 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.

AnswerPS 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 wordingMethodOpening sentence to writeSee
An array, "return the maximum/minimum/number of …", target O(n) or O(n²), choices made element by elementDP 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 ruleGreedy 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 changesThe 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
Matching the story instead of the structureA problem about stocks is a DP, a problem about games between teams is a flow, and a problem about a "spanning tree whose heaviest edge is smallest" is solved by an ordinary MST. Read the input and the target running time before the story: the target O(m + n) rules out Dijkstra, O(n²) on a graph points to it, and O(n³) points to Floyd-Warshall.

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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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

How this chapter is testedThe whole exam tests it. Problems 1 and 2 reward the first pass: ten traces you have done before, written in the requested format. At least two of Problems 3–8 reward the problem-set bank: the official solution, reproduced in the three-part format, in a quarter of an hour. The rest reward the pattern table and the habits of Section 14.4: an opening sentence that commits to the right structure, a stated subproblem or bound on OPT, and a correctness sentence that names its reason.

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.

Writing an answer Problems 3–8: (1) Algorithm: one or two sentences of idea, then 4–12 lines of pseudocode in the lecture idiom, calling listed algorithms by name. (2) Correctness: an argument of a named type (loop invariant or induction, two directions, exchange, cut or cycle property, reduction correspondence). (3) Running time: iterations × time per iteration, reaching the target bound. DP variant: Subproblems (and what is returned) · Recurrence with base cases and why it holds (this is the proof) · Algorithm · Running time = subproblems × time each. Approximation: feasibility · bound on OPT · bound on ALG · ratio. Prove-or-refute: first word "Yes" or "No"; a counterexample gives the instance, ALG, OPT and a ratio strictly worse than α. Problems 1–2: final answer only, in the requested format. Cover page: no hashing (sets are 0/1 arrays), indices from 1, A[1]..A[n], n = |V|, m = |E|, adjacency lists, ties to the smallest label, only the boxes are graded. See Chapter 1.
Arrays (course Ch. 1) Max-in-Array: running max m = max(m, A[i]); invariant m = max(A[1:i]); O(n). Two-Sum (sorted A, target t): start (1, n); sum < t ⇒ i += 1, sum > t ⇒ j −= 1; a solution always stays inside A[i:j]; j − i drops by 1, O(n); [1, 4, 5, 7], t = 5 → (1, 2). Binary-Search: m = ⌊(i + j)/2⌋ while i ≤ j; range halves, O(log n); [2, 4, 7, 9, 12, 15, 20], t = 5 → m = 4, 2, 3, nothing. Selection-Sort: round i swaps the minimum of A[i:n] into place, n(n + 1)/2 = O(n²). Merge-Sort: sort halves, merge (ties left), T(n) = 2T(n/2) + O(n) = O(n log n). Container (PS 1.4): start (1, n), record, move the shorter wall; O(n); [1, 3, 2, 5, 2, 2] → (2, 6), value 8. See Chapter 2.
BFS and DFS (course Ch. 2) Graphs: adjacency lists, Σ out-deg(u) = m gives every O(m + n). BFS(G, s): queue; first discovery sets d[v] = d[u] + 1 (and p[v] = u); ∞ if unreachable; counts edges; O(m + n). Lecture graph [[2, 4], [3, 5, 6], [6], [5, 7], [7], [8], [], [5]] → d = [0, 1, 2, 1, 2, 2, 2, 3]. Explore(u): pre[u] = clock, explore unvisited out-neighbors in label order, post[u] = clock; DFS restarts at the smallest unvisited label and the clock keeps running; O(m + n). [[2, 3], [3, 4], [], [1, 3]] → pre = [1, 2, 3, 5], post = [8, 7, 4, 6]. Edge (u, v): tree/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]. See Sections 3.2–3.4.
Cycles, topological sort, SCCs Find-Cycle: G has a cycle ⇔ DFS finds a back edge (prove both directions); return the tree path v → u plus (u, v); O(m + n). Topological-Sort (DAG): put each vertex at the left end of R when it gets its post value, i.e. decreasing post; proof: post[u] > post[v] for every edge, two cases; O(m + n). Increasing pre fails on [[2], [], [2]] (correct R = [3, 1, 2]). "Whenever input is a DAG, topo sort is usually helpful" (PS 2.2, 2.5: scan consecutive pairs of T). SCC: DFS on GR, then BFS in G from each unlabelled vertex in decreasing post order; each BFS labels a sink SCC; O(m + n); [[2], [3, 4], [1, 5], [5], []] → c = [3, 3, 3, 2, 1]. SCC is not on the call-by-name list. PS 2: diameter by n BFS runs O(mn); components by a BFS wrapper; bipartite by BFS 2-coloring. See Sections 3.5–3.8.
MST: cut and cycle properties, Prim, Kruskal, Reverse-Delete Connected undirected G, distinct weights, unique MST. Cut Property: for any cut S, the lightest edge crossing S is in the MST (exchange T + e − f, f on the cycle). Cycle Property: the heaviest edge of any cycle is not in the MST. Prim: S = {1}, n − 1 times add the lightest edge crossing S; O(mn) = O(m²); order is not sorted by weight. Kruskal: edges increasing, keep e if F + e is acyclic (BFS on F, O(n)); O(m log m) + m · O(n) = O(m²). Reverse-Delete: edges decreasing, delete e if G − e stays connected; O(m log m) + m · O(m) = O(m²). Lecture square {1, 2}:5, {1, 4}:4, {1, 3}:3, {2, 3}:2, {3, 4}:1 → Prim adds {1, 3}, {3, 4}, {2, 3}, weight 6. PS 3.4: remove e, add the lightest edge across the cut, O(m + n). See Sections 4.2–4.5.
Intervals, Max k-Sum, Fractional Knapsack Exchange argument: assume OPT ≠ ALG, swap at the first difference to get OPT′, show OPT′ is feasible and no worse. Max k-Sum: sort decreasing, return A[1:k]; O(n log n); [4, 5, 1, 7, 2], k = 3 → [7, 5, 4], sum 16. Select-Intervals: sort by end time, add each interval that starts strictly after the last chosen one ends (closed intervals); O(n log n); [[5, 9], [1, 4], [3, 6], [7, 8], [10, 11], [2, 12]] → [1, 4], [7, 8], [10, 11]. Fractional-Knapsack: sort by v[i]/w[i] decreasing, take as much as fits, at most one fractional item; ε-exchange; O(n log n); v = [3, 4, 5], w = [2, 2, 1], B = 4 → x = [0.5, 1, 1] in item order. The ratio rule fails for 0/1 Knapsack. See Section 4.1, 4.6, 4.7.
The DP method and patterns OPT is the reasoning, d is the array. Fill in an order where every entry read is ready. Patterns: (1) prefixes A[1:i], return OPT[n]; (2) suffixes A[i:n], fill right to left, return OPT[1]; (3) prefix that must end on A[i] (LIS trick), return max or min of d; (4) intervals A[i:j], bottom row up, return OPT[1][n]; (5) (prefix, budget), return OPT[n][B]; (6) pair of prefixes, return OPT[m][n]; (7) subtree Tu; (8) subtree that involves u (OPTin/OPTout), children before parents. PS 4: 4.1 sum; 4.2 increasing subarray, return max; 4.3 jumps, min(d[n−1], d[n]); 4.4 grid paths O(mn); 4.5 stock d[j] = A[j] − running min, [8, 2, 4, 7, 1, 3] → 5; 4.6 no two adjacent, [3, 8, 3, 1, 12] → 20; 4.7 d[i] = d[i−A] + d[i−B], (1, 2, 4) → 5. All O(n) except 4.4. See Section 5.1, 6.6, 6.7.
LIS and LPS LIS: OPT[i] = length of the LIS that must end on A[i]; OPT[i] = 1 + max{OPT[j] : j < i, A[j] < A[i]}, 1 if none; return max(d), not d[n]; O(n²); parent pointers (smallest j on ties) recover it. Lecture A = [5, 1, 2, 7, 4, 6, 3] → d = [1, 1, 2, 3, 3, 4, 3], answer 4. LPS: OPT[i][j] = LPS of A[i:j]; OPT[i][i] = 1; A[i] = A[j] ⇒ OPT[i+1][j−1] + 2, else max(OPT[i+1][j], OPT[i][j−1]); fill rows i = n down to 1, each left to right; return d[1][n]; O(n²). Row 1, entry j = LPS of the prefix A[1:j]; row k starts with k − 1 zeros. Lecture acbcbda → 5; abcbca → first row [1, 1, 1, 3, 3, 5]. See Sections 5.2–5.3.
Edit Distance OPT[i][j] = edit distance from A[1:i] to B[1:j], 0 ≤ i ≤ m, 0 ≤ j ≤ n. Base OPT[0][j] = j, OPT[i][0] = i. OPT[i][j] = min(OPT[i][j−1] + 1 insert, OPT[i−1][j] + 1 delete, OPT[i−1][j−1] + δ replace or keep), δ = 0 if A[i] = B[j], else 1; if the characters match, copy the diagonal. Why: the last move fixes B[j] by an insertion, removes A[i] by a deletion, or aligns A[i] with B[j]. Return d[m][n]; O(mn). The last row is row m and starts with m. Course example ED(star, water) = 3; Practice Final 2b ED(abbc, babc) = 2. See Section 5.4.
0/1 Knapsack OPT[i][j] = best value from items 1..i with capacity j, j = 0..B. Base row OPT[1][j] = v[1] if w[1] ≤ j, else 0. OPT[i][j] = OPT[i−1][j] if w[i] > j, else max(OPT[i−1][j], v[i] + OPT[i−1][j − w[i]]): item i is skipped or taken. Return OPT[n][B]; O(nB), which is not polynomial (B is a number). Unbounded: OPT[i][j − w[i]] in place of OPT[i−1][j − w[i]]. One array: sweep j from B down (left to right solves Unbounded). Greedy by ratio fails: v = [4, 4, 7], w = [5, 5, 6], B = 10. Lecture v = [4, 2, 3, 5], w = [3, 1, 2, 2], B = 5 → last row [0, 2, 5, 7, 8, 10], answer 10. Practice Final 1e → [0, 2, 4, 6, 7]. See Sections 6.1–6.2.
Independent set in trees Tree rooted at 1, T[u] = children. OPTin[u] = w(u) + Σ OPTout[v]; OPTout[u] = Σ max(OPTin[v], OPTout[v]); leaf (w(u), 0); return max at the root; reverse topological order (children first); O(n) since Σ |T[u]| = n − 1. Lecture tree → 21. One array: OPT[u] = max(Σchildren OPT[v], w[u] + Σgrandchildren OPT[x]). Tree matching: OPTout[u] = Σ OPT[v]; OPT[u] = max(OPTout[u], maxv w(u, v) + OPTout[v] + OPTout[u] − OPT[v]); the subtraction makes it O(n); lecture tree → 9. Alice and Bob (suffix game) [4, 1, 5, 2, 3, 10, 1, 2] → 18. See Sections 6.3–6.5.
DAG DP and Bellman-Ford Relax (u, v): d[v] = min(d[v], d[u] + ℓ(u, v)). DAG-DP: OPT[s] = 0, OPT[v] = min over in-neighbors u of OPT[u] + ℓ(u, v); topological order, in-neighbors from GR; negative lengths fine; O(m + n); max gives longest paths. Lecture → d = [0, −6, 10, −4]. Bellman-Ford (no negative cycle): OPT[v][j] = shortest walk with at most j edges = min(OPT[v][j−1], minu OPT[u][j−1] + ℓ(u, v)); column 0 is 0 at s, ∞ elsewhere; return column n − 1 (a shortest walk is a path); O(mn); k columns cost O(mk) (Practice Final 5: j ≤ 10, O(m)). Bellman-Ford-2 relaxes every edge n − 1 times and may run ahead of column j. Lecture → d = [0, 2, 1, 5]. See Sections 7.2–7.3.
Dijkstra and Floyd-Warshall Dijkstra (all ℓ ≥ 0): n times add the vertex outside S with the smallest d, relax its out-edges; induction: d[u] = δ(u) when u joins S; O(n²) with arrays, O(m log n) with a heap; ties to the smallest label; not Prim. Lecture (1, 2):3, (1, 4):10, (2, 3):1, (2, 4):4, (3, 4):2, (3, 5):3, (4, 5):1 → order 1, 2, 3, 4, 5, d = [0, 3, 4, 6, 7]. Floyd-Warshall (no negative cycle): OPT[u][v][r] = shortest u-v walk with intermediates in {1, …, r}; r = 0: 0 on the diagonal, ℓ(u, v) on edges, ∞ else; OPT[u][v][r] = min(OPT[u][v][r−1], OPT[u][r][r−1] + OPT[r][v][r−1]); return table n; O(n³). PS 5: 5.1 widest path (DAG-DP with max/min) O(m + n); 5.2 one negative edge, two Dijkstras O(n²); 5.3 even walk, two copies + Dijkstra O(n²); 5.4 shortest cycle, min d[u][v] + d[v][u] after Floyd-Warshall O(n³). See Sections 7.4–7.7.
Flows, cuts, Ford-Fulkerson Feasible flow: 0 ≤ f(e) ≤ c(e), conservation at every u ≠ s, t; |f| = fout(s). s-t cut S: s ∈ S, t ∉ S; c(S) sums only edges leaving S. Flow-Cut Lemma: |f| = fout(S) − fin(S) ≤ c(S); equal flow and cut prove both optimal. Residual graph Gf: forward (u, v) with c − f if f < c, backward (v, u) with f if f > 0. Ford-Fulkerson: while Gf has an s-t path P (DFS), push its bottleneck ΔP (add on forward, subtract on backward); each round adds ≥ 1, so O(mv), v = max flow value. Main example (1, 2):3, (1, 3):12, (2, 3):8, (2, 4):1, (3, 4):3, (3, 5):5, (4, 5):15 → three augmentations, value 9. Practice Final 1a → 7 (cut {1, 3}: 6 + 1). See Sections 8.1–8.2.
Min cut, matching, vertex cover Max-Flow Min-Cut: max flow value = min cut capacity. Minimum-st-Cut: run Ford-Fulkerson, S = vertices reachable from s in the last Gf; O(mv); main example S = {1, 2, 3}, capacity 9. Bipartite-Matching: s → L capacity 1, L → R capacity n, R → t capacity 1, Ford-Fulkerson, return edges with f(e) = 1; O(mn) since v ≤ n. Bipartite-VC: same network, minimum cut S, return (L \ S) ∪ (R ∩ S); |C| = c(S); capacity n on the middle edges forces a cover; O(mn). Reduction format: convert, solve, convert back, optimal because optimal. PS 6: 6.1 global min cut, all t both ways, O(mn²); 6.2 remove k edges leaving a min cut, O(mn); 6.3 split u into uin → uout with capacity c(u), O(mv); 6.4 path through u as a u-flow of value 2, O(m); 6.5 baseball elimination, O(n²v). See Sections 8.3–8.6.
Approximation ratios An α-approximation is a polynomial-time algorithm with, on every instance X: minimization (α ≥ 1) OPT(X) ≤ ALG(X) ≤ α · OPT(X); maximization (α ≤ 1) OPT(X) ≥ ALG(X) ≥ α · OPT(X). Any polynomial time is accepted; "an analysis is not even necessary". A 2-approximation is also a 3-approximation; a 1/2-approximation is also a 1/3-approximation (Practice Final 2d, 2e: True, True). Proof: feasibility, a bound on OPT (lower for min, upper for max), ALG in the same terms, the chained ratio. Charging: assign each OPT element to an ALG element that blocked it, at most c each ⇒ |OPT| ≤ c · |ALG| (PS 8.1: greedy maximal matching, |M*| ≤ 2|M|). Refuting: "No", a concrete run, ALG, OPT, a ratio strictly worse than α. See Section 9.1, 9.6.
Vertex Cover and Load Balancing VC-Matching: while an edge {u, v} remains, add u and v to S and delete them. Picked edges form a matching M; |S| = 2|M| ≤ 2|OPT| because every cover has |OPT| ≥ |M|; ratio 2, tight on disjoint edges. Greedy by maximum degree is not optimal: spider graph, 4 vs 3. Load Balancing: jobs in the given order, each to the least-loaded machine (ties to the smallest label). Bounds: T* ≥ Σ ℓ[j]/m and T* ≥ ℓ[k]; machine with makespan T had load ≥ T − ℓ[k] when its last job k arrived, so T ≤ Σ ℓ[j]/m + ℓ[k] ≤ 2T*, in fact (2 − 1/m)T*, tight by PS 8.2 (m(m − 1) unit jobs then one job of length m). Sorting longest first gives 3/2 (PS 8.3, extra bound T* ≥ 2ℓ[m+1]). Lecture ℓ = [5, 1, 4, 2, 3], m = 3 → ALG 6, OPT 5; Practice Final 2c [3, 1, 2, 3], m = 3 → 4. See Sections 9.2–9.3.
Metric k-Center and Maximum Cut Metric: d ≥ 0, symmetric, d(u, v) = 0 only if u = v, triangle inequality. Metric-k-Center: S = {1}, then k − 1 times add the point farthest from its closest center; 2-approximation: two points in one optimal cluster are within 2r* (triangle inequality), two cases (an ALG center in p's optimal cluster, or pigeonhole puts two ALG centers in one cluster). Points at 0, 2, 9, 10, 15, 18, k = 3 → centers 1, 6, 3. Maximum Cut local search: S = ∅; move any single vertex whose move increases w(δ(S)) (in a trace, the smallest label that helps); at the end α(u) ≥ w(δ(u))/2, so 2 · ALG = Σ α(u) ≥ w(E) ≥ OPT: a 1/2-approximation; at most w(E) iterations, not polynomial in general. PS 8.4: Dominating Set via a 1.9-approximation for k-Center (distances 1 and 2). See Sections 9.4–9.5.
Which method when Pair or window in an array → two pointers. Sorted search → Binary-Search. Repeated element without hashing → a 0/1 array. Unit-length distances, components, 2-coloring → BFS. Reachability, cycles, ordering → DFS, Find-Cycle; a DAG → Topological-Sort. Spanning tree, "is e in the MST", updates → Prim/Kruskal plus the cut or cycle property. A greedy choice you can exchange → greedy with an exchange proof; otherwise DP, choosing the pattern from the input shape. Shortest paths: equal lengths → BFS; DAG → DAG-DP; ℓ ≥ 0 → Dijkstra; negative lengths, no negative cycle → Bellman-Ford; at most k edges → k columns; all pairs or cycles → Floyd-Warshall; parity or one special edge → two copies of G plus Dijkstra. Disjoint paths, assignments, vertex limits, cutting edges → flow network and min cut. A problem with no known polynomial optimal algorithm (Vertex Cover, Load Balancing, k-Center, Max Cut) → approximation with a bound on OPT. See Section 14.3 (and Section 7.6 for shortest paths).
Costs and results O(log n): Binary-Search. O(n): Max-in-Array, Two-Sum, container, PS 4.1–4.3 and 4.5–4.7, tree DPs (MIS, matching), the Practice Final 7 suffix DP. O(n log n): Merge-Sort, Max k-Sum, Select-Intervals, Fractional-Knapsack. O(n²): Selection-Sort, LIS, LPS, Dijkstra (array; O(m log n) heap). O(m + n): BFS, DFS, Explore, Find-Cycle, Topological-Sort, SCC, DAG-DP, PS 3.4. O(mn): Bellman-Ford, PS 2.1 diameter, Bipartite-Matching, Bipartite-VC, PS 6.2; O(mk) for k Bellman-Ford columns. O(mn) = O(m²): Prim. O(m log m) + m · O(n) = O(m²): Kruskal. O(m log m) + m · O(m) = O(m²): Reverse-Delete. O(mn): Edit Distance (strings of lengths m, n). O(nB): Knapsack-DP (not polynomial). O(n³): Floyd-Warshall, PS 5.4. O(mv): Ford-Fulkerson, Minimum-st-Cut, PS 6.3. Approximations: any polynomial time; Max Cut local search at most w(E) iterations. Ratios: VC 2, Load Balancing 2 (2 − 1/m), sorted 3/2, k-Center 2, Max Cut 1/2, greedy matching 1/2.
Traps that cost points Writing the algorithm but not why it works. Proving only one direction. Swapping without checking feasibility; "OPT′ is better" is not a proof. Recurrence without the "why"; defining OPT vaguely. Calling Dijkstra with a negative edge ("no negative cycle" is not enough). Charging n per vertex for adjacency lists; scanning G[u] is not free. ∞ for unreachable vertices. The DFS clock keeps running across restarts. Decreasing post, not increasing pre. DFS on the reverse, BFS on the original. Prim's edges in the order chosen. Kruskal's cycle test runs on F, not G. Endpoints are included (strict test for intervals). Report x in item order; sort by ratio, not value. Return max(d), not d[n]. Fill LPS from the bottom row. The ED last row is row m and starts with m. Knapsack reads the row above; the one-array 0/1 version sweeps j downward. Children before parents. "d after round j" is not "column j". c(S) counts only edges leaving S; a saturated edge is not necessarily a cut edge. (L \ S) ∪ (R ∩ S). Flip the inequality for maximization. A counterexample whose ratio is exactly α proves nothing; "No" needs more than "ALG is not optimal". Right trace, wrong format.
Practice exam answers Official Practice Final (Chapter 11): 1a 7; 1b post = [8, 7, 6, 5]; 1c {1, 3}, {3, 4}, {2, 3}; 1d d = [1, 1, 2, 3, 2, 3]; 1e [0, 2, 4, 6, 7]; 2a x = [0.5, 1, 1]; 2b 2; 2c 4; 2d True; 2e True. P3 (PS 4.5) d[j] = A[j] − running min, return max, O(n). P4 (PS 8.1) assign each optimal edge to a chosen edge sharing an endpoint, at most 2 each, |M*| ≤ 2|M|. P5 Bellman-Ford table to column 10, O(m). P6 return the MST; the cycle property shows its heaviest edge is optimal, O(m²). P7 suffix DP OPT[i] = max(OPT[i+1], A[i] + OPT[i + B[i] + 1]), O(n). P8 Yes, 1/Δ: each chosen u removes at most Δ optimal vertices. Version A (Chapter 12): 1a m = 4, 2, 3, nothing; 1b [0, 1, 1, 2, 2, 3]; 1c R = [1, 3, 2, 5, 4, 6]; 1d {2, 4}, {3, 5}, {1, 4}, {2, 3}, {3, 6}; 1e [1, 1, 1, 3, 3, 5]; 2a [∞, 9, 4, 1]; 2b 6; 2c 1, 6, 3; 2d False; 2e True. P3 BFS 2-coloring (PS 2.4); P4 better of greedy prefix and the next item, OPT ≤ 2 · ALG; P5 two copies, red edges into copy 1, Dijkstra, d[t₁]; P6 e in MST iff BFS on lighter edges cannot join its ends, O(m); P7 grid DP, O(mn); P8 k edges leaving a min cut (PS 6.2). Version B (Chapter 13): 1a m = 5, 8, 9; 1b pre = [1, 2, 10, 3, 5, 4], post = [12, 9, 11, 8, 6, 7]; 1c removes {3, 4}, {5, 6}, {1, 2}, {2, 4}; 1d [0, 3, 5, 8, 8, 9]; 1e 1, 3, 2, 5, 4, 6; 2a S = {1, 2, 3}, 8; 2b [1, 1, 3, 3, 3, 3, 5]; 2c 8; 2d False; 2e False. P3 OPT[u] = w[u] + Σ max(0, OPT[v]), return max, O(n); P4 sorted greedy 3/2 (PS 8.3); P5 even walk (PS 5.3); P6 Explore from s in G and from t in GR, count both, O(m + n); P7 split vertices, capacity 1, max flow, O(mn); P8 No: points 0, 1, 10, k = 2, radius 9 vs 1.
The examination Thursday, December 10, 2026, 4:00–7:00 pm, Chapman Hall 211 (the usual room). Three hours, on paper, closed-everything; bring your UNC One Card. Scope: course Chapters 1–8 except 7 (course Chapter 7, computational complexity, and course Chapter 9, formal methods, are not examined; see Chapter 10 of this guide). Eight problems of five points, 40 points, 30% of the course grade; if it is higher, the final score replaces the lower midterm score (syllabus). Problems 1–2: five one-point parts each, like short homework, no explanation. Problems 3–8: like problem sets, at least two identical to problem-set problems. Pseudocode like the lectures, no hashing, indices from 1, adjacency lists, listed algorithms may be called by name. Anything outside the boxes is ignored. Time plan in Chapter 14.