Exercises
Fourteen problems covering the whole course: dynamic programming, greedy algorithms and amortized analysis. Try each one on paper first. Every problem has a short Answer to check yourself against and a full Solution; several solutions include a program that confirms the result, which you can edit and run.
Tip: For a DP, write down the subproblem in words before the recurrence (" is the best value for ..."); most wrong recurrences come from a subproblem that was never stated precisely. For a greedy algorithm, look for a counterexample on three or four elements before trying to prove it.
| # | Exercise | Practises |
|---|---|---|
| 1 | Rod cutting by hand | bottom-up DP, reconstruction |
| 2 | Strings without two adjacent ones | setting up a counting DP |
| 3 | A chain of four matrices | interval DP |
| 4 | LCS and edit distance by hand | prefix-pair DPs |
| 5 | Houses on a street | choosing the state |
| 6 | A tiny knapsack, and a huge capacity | 0/1 knapsack, pseudo-polynomial time |
| 7 | Three keys in a search tree | optimal BSTs |
| 8 | Stabbing intervals with points | greedy choice, exchange argument |
| 9 | Huffman code by hand | Huffman's algorithm |
| 10 | Two per category | partition matroids, greedy |
| 11 | Five jobs with deadlines | unit-task scheduling |
| 12 | A ternary counter | aggregate method |
| 13 | A table that triples | potential method |
| 14 | Why the quarter? | table contraction |
Exercise 1: Rod cutting by hand
Prices for lengths 1 to 5 are . Find and an optimal cutting of a rod of length 5.
Answer
. Length 5 is best cut into , for .
Solution
Bottom-up, with : ; ; ; ; . The smallest winning first piece for length 5 is 2, and the rest, length 3, is best uncut. See Reconstructing an Optimal Solution.
p = [3, 7, 11, 12, 16]
r, s = [0] * 6, [0] * 6
for j in range(1, 6):
best = -1
for i in range(1, j + 1):
if p[i - 1] + r[j - i] > best:
best, s[j] = p[i - 1] + r[j - i], i
r[j] = best
pieces, n = [], 5
while n:
pieces.append(s[n]); n -= s[n]
print("r =", r[1:], " cutting of 5:", pieces)r = [3, 7, 11, 14, 18] cutting of 5: [2, 3]
Exercise 2: Strings without two adjacent ones
How many binary strings of length contain no two consecutive 1s? Give a recurrence, the value for , and the running time of the bottom-up computation.
Answer
with , ; (the Fibonacci number ). additions.
Solution
Split by the last character. A valid string ending in 0 is any valid string of length followed by 0. A valid string ending in 1 must end in , so it is a valid string of length followed by . These cases are disjoint and cover everything, so . With (0, 1) and (00, 01, 10), the sequence is , so . The subproblems are the lengths , each with two ingredients. A brute-force check:
from itertools import product
a = {1: 2, 2: 3}
for n in range(3, 11):
a[n] = a[n - 1] + a[n - 2]
brute = sum(1 for bits in product("01", repeat=10) if "11" not in "".join(bits))
print("a_10 =", a[10], " brute force:", brute)a_10 = 144 brute force: 144
Exercise 3: A chain of four matrices
Find the cheapest order for multiplying matrices with dimensions , and its cost.
Answer
with 405 scalar multiplications.
Solution
Length 2: , , . Length 3: ; . Length 4: , at the split . Both halves are single products. See Matrix-Chain Multiplication: The Table.
Exercise 4: LCS and edit distance by hand
(a) Find the length of an LCS of BANANA and ATANA. (b) Find the edit distance from PARK to SPARE.
Answer
(a) 4, for example AANA. (b) 2: insert S at the front and substitute K by E.
Solution
(a) ATANA minus its T is AANA, which is a subsequence of BANANA (positions 2, 4, 5, 6). Length 5 is impossible: it would be all of ATANA, but BANANA has no T. (b) Lengths differ by 1, so at least one insertion is needed, and PARK and SPARE differ in more than the inserted letter (the last letters differ), so 1 is impossible; the two edits given reach SPARE. The tables confirm both:
def lcs(x, y):
c = [[0] * (len(y) + 1) for _ in range(len(x) + 1)]
for i in range(1, len(x) + 1):
for j in range(1, len(y) + 1):
c[i][j] = c[i - 1][j - 1] + 1 if x[i - 1] == y[j - 1] else max(c[i - 1][j], c[i][j - 1])
return c[-1][-1]
def edit(x, y):
prev = list(range(len(y) + 1))
for i, ch in enumerate(x, 1):
cur = [i]
for j, d in enumerate(y, 1):
cur.append(min(prev[j - 1] + (ch != d), prev[j] + 1, cur[-1] + 1))
prev = cur
return prev[-1]
print("LCS(BANANA, ATANA) =", lcs("BANANA", "ATANA"))
print("d(PARK, SPARE) =", edit("PARK", "SPARE"))LCS(BANANA, ATANA) = 4
d(PARK, SPARE) = 2
Exercise 5: Houses on a street
Houses along a street hold amounts . A collector may visit any set of houses but never two neighbours. Give an algorithm for the largest total, and apply it to .
Answer
with , . For the example : houses 1, 4 and 6 ().
Solution
State: , the best total using only houses . Either house is skipped (), or it is visited, and then house is not, leaving houses (). One pass computes ; two variables suffice for the values. For the example, . A greedy rule such as "take the largest remaining house, discard its neighbours" fails on : it takes the 3, while is better.
Exercise 6: A tiny knapsack, and a huge capacity
(a) Items (weight, value): , , , ; capacity 7. Find the best 0/1 packing. (b) A program solves 0/1 knapsack in time. Is it practical for items with weights around and ?
Answer
(a) Value 9, items 2 and 3. (b) No: steps (and as many table cells), although the input has only a few thousand bits.
Solution
(a) The candidates that fit: items 2 and 3 (weight 7, value 9), items 1 and 4 (weight 6, value 8), items 1 and 2 (value 5), items 1 and 3 (value 6), and singles. Note that item 4 has the best density but is not in the optimum. (b) The running time is polynomial in the value of but exponential in its length (about 42 bits): pseudo-polynomial (0/1 Knapsack and Pseudo-Polynomial Time). With 50 items, meet-in-the-middle ( subsets per half) or branch and bound with the fractional bound would be the realistic choices.
Exercise 7: Three keys in a search tree
Keys are searched , and times. Find an optimal BST and its cost (comparisons = depth + 1).
Answer
Root with children and : cost .
Solution
There are five BSTs on three keys. Root : 15. Root with below and below that: ; root , then , then : . Root with then : ; root , then , then : . With the recurrence: , and , where (root ) and (root ). See Optimal Binary Search Trees.
Exercise 8: Stabbing intervals with points
Given closed intervals on the line, place as few points as possible so that every interval contains at least one point. Give a greedy algorithm and prove it optimal. Apply it to .
Answer
Repeatedly take the interval with the smallest right endpoint among those not yet stabbed, place a point at , and remove every interval containing it. For the example: points 4 and 8.
Solution
Greedy choice. Let have the smallest right endpoint. Any solution has a point , so . Moving to keeps every interval it stabbed stabbed: an interval containing has and (since is the smallest right endpoint), so it contains . So some optimal solution uses the point . Optimal substructure: the intervals not containing form a smaller instance, and an optimal solution for it plus is optimal overall. On the example, point 4 stabs ; the first remaining right endpoint is 8, which stabs . Two points are needed, since and are disjoint. This is the "dual" of activity selection: the number of points equals the maximum number of pairwise disjoint intervals.
Exercise 9: Huffman code by hand
Build a Huffman code for frequencies and find the total number of bits.
Answer
Merges , , , , ; total bits.
Solution
Each merge adds its weight to the total (Prefix Codes and Huffman's Algorithm). Codeword lengths: 13 and 11 get 2 bits, 7 gets 2 bits, 5 gets 3, and 2 and 3 get 4 bits each: . A fixed-length code would need bits.
#include <cstdio>
#include <functional>
#include <queue>
#include <vector>
int main() {
std::priority_queue<int, std::vector<int>, std::greater<int>> q;
for (int f : {2, 3, 5, 7, 11, 13}) q.push(f);
int total = 0;
while (q.size() > 1) {
int a = q.top(); q.pop();
int b = q.top(); q.pop();
std::printf("merge %d + %d = %d\n", a, b, a + b);
total += a + b;
q.push(a + b);
}
std::printf("total %d bits\n", total);
}merge 2 + 3 = 5
merge 5 + 5 = 10
merge 7 + 10 = 17
merge 11 + 13 = 24
merge 17 + 24 = 41
total 97 bits
Exercise 10: Two per category
A shop chooses items for a display: from each category at most two items, and the goal is the largest total value. Show that the feasible sets form a matroid, and find the best display for: fruit 9, 4, 7; bread 6, 8; cheese 5, 3, 10, 2.
Answer
It is a partition matroid. Greedy gives fruit 9 and 7, bread 8 and 6, cheese 10 and 5: total 45.
Solution
Hereditary: removing items keeps every category within its limit. Exchange: if , some category has more items in than in , so has fewer than two from it, and any item of from that category can be added. By the weighted matroid theorem, greedy is optimal: take items by decreasing value, skipping one when its category is full: 10, 9, 8, 7, 6, then 5 (cheese has only one so far), then 4 (fruit full, skip), 3 and 2 (cheese full, skip). Here greedy is just "the two best of each category", which is obviously optimal; the matroid view matters when constraints are combined in less obvious ways.
Exercise 11: Five jobs with deadlines
Unit-time jobs with deadlines and penalties . Find a schedule with minimum total penalty.
Answer
Early jobs 1, 2, 4 in the order (or ), then jobs 3 and 5 late: penalty .
Solution
Greedy by decreasing penalty, with the test (Scheduling Unit Tasks): job 1 (deadline 2) accepted; job 2 (deadline 2): , accepted; job 3 (deadline 1): would be 3, rejected; job 4 (deadline 3): , accepted; job 5 (deadline 3): would be 4, rejected. The accepted jobs run in deadline order in hours 1 to 3, the rejected ones after.
Exercise 12: A ternary counter
A counter stores a number in base 3, with digits . An increment turns trailing 2s into 0s and adds one to the next digit. Show that increments from 0 change fewer than digits in total.
Answer
Digit changes exactly times, so the total is less than .
Solution
Digit changes exactly when all lower digits are 2 before the increment, which happens once every increments. Summing the geometric series as in The Aggregate Method gives the bound, so the amortized cost of an increment is below 1.5 digit changes. For example, 9 increments change digits and 27 increments change . In base the bound becomes .
Exercise 13: A table that triples
A dynamic table triples its size when an insertion finds it full. Find a potential function that gives every insertion the same amortized cost, and find that cost.
Answer
; every insertion (after the first) has amortized cost .
Solution
Look for that is 0 right after an expansion, when , and equals when the table is full, to pay for copying. That gives and , so and . Without expansion, . With expansion from a full table of size : , and goes from to , so . This matches the general for growth factor (Dynamic Tables: Expansion). because the table is always at least a third full.
Exercise 14: Why the quarter?
A table doubles when full and halves when a deletion leaves it less than a fraction full. For which is the amortized cost of every operation , and why does fail?
Answer
Any constant works; allows thrashing.
Solution
After a doubling or a halving the load factor is . With , the next resize needs either enough insertions to fill the table (about of them) or enough deletions to bring it from to (about of them), and the resize copies at most items, so the copies are paid by operations, a constant each (the constant grows like ). With , a table that has just doubled is exactly at the threshold, so two deletions halve it and the next insertions double it again: per operation for an adversary (Dynamic Tables: Contraction). The choice is the usual one because it gives small constants (3 and 2) and wastes at most a factor 4 in memory.
Test yourself
In Exercise 5 (houses on a street), what does stand for?
- The best total using exactly house
- The best total using only houses
- The amount in house
- The number of houses visited
Where does the greedy algorithm of Exercise 8 place its first point?
- At the leftmost start point
- At the smallest right endpoint
- At the midpoint of the longest interval
- At the point covered by the most intervals
What is the amortized number of digit changes per increment of a base-10 counter, by the method of Exercise 12?
- Less than
- Less than 2
- Exactly 1