TExcelTAD
Home › Design Techniques: Dynamic Programming, Greedy & Amortized Analysis › Design Techniques: What This Course Covers

Design Techniques: What This Course Covers

The first three courses of this track analysed algorithms that were handed to you: sorts, selection, search trees, hash tables. This course is about inventing algorithms. It teaches three general techniques that turn a problem statement into an efficient algorithm, together with the proof methods that tell you when each one is correct:

  • Dynamic programming solves a problem by combining the solutions of overlapping subproblems, each solved once and stored in a table.
  • Greedy algorithms make one locally best choice after another and never look back, which is fast but only correct when an exchange argument says so.
  • Amortized analysis is not a design technique but a way of measuring: it bounds the total cost of a sequence of operations, which is what makes structures with occasional expensive steps, such as growable arrays, provably efficient.

Like the rest of the track, the course follows the topic order of Introduction to Algorithms by Cormen, Leiserson, Rivest and Stein (Part IV, "Advanced Design and Analysis Techniques"), with every explanation, example, figure and exercise written from scratch. Other good companions are Algorithm Design by Kleinberg and Tardos, whose chapters on greedy algorithms and dynamic programming are especially readable, and Algorithms by Dasgupta, Papadimitriou and Vazirani.

Three small puzzles

Each technique starts from a situation where the obvious approach goes wrong. The program below shows one of each: a recursion that does exponentially more work than necessary, a greedy rule that gives a wrong answer, and an operation whose worst case is misleading.

python · try it yourself
# 1. Dynamic programming: count the ways to climb n stairs taking 1 or 2 steps at a time
calls = 0
def ways(n):
    global calls
    calls += 1
    return 1 if n <= 1 else ways(n - 1) + ways(n - 2)

print("ways(25) =", ways(25), "with", calls, "calls")
table = [1, 1]
for n in range(2, 26):
    table.append(table[-1] + table[-2])
print("bottom-up table: ways(25) =", table[25], "with", len(table) - 2, "additions")

# 2. Greedy: pay 12 with coins 1, 6 and 9, always taking the largest coin that fits
amount, coins, greedy = 12, [9, 6, 1], []
for c in coins:
    while amount >= c:
        greedy.append(c); amount -= c
print("greedy pays 12 as", greedy, "but 6 + 6 uses only 2 coins")

# 3. Amortized: appending to a table that doubles when full
size, num, copies, worst = 1, 0, 0, 0
for _ in range(1000):
    cost = 1
    if num == size:
        cost += num; copies += num; size *= 2
    num += 1
    worst = max(worst, cost)
print(f"1000 appends: worst single append {worst} steps, but only {copies} copies in total")
ways(25) = 121393 with 242785 calls
bottom-up table: ways(25) = 121393 with 24 additions
greedy pays 12 as [9, 1, 1, 1] but 6 + 6 uses only 2 coins
1000 appends: worst single append 513 steps, but only 1023 copies in total

The recursion makes 242,785 calls to compute a number that a table of 26 entries gives in 24 additions: it keeps solving the same subproblems. The greedy coin rule is wrong for this coin system, and the course shows how to tell when greedy is safe. The doubling table has one append that costs 513 steps, yet a thousand appends copy only 1023 items in total, about one per append: an amortized cost of O(1)O(1) per append.

Greedy or dynamic programming?

The two design techniques often meet on the same problem. Scheduling talks in one lecture hall to fit in as many as possible is solved by a greedy rule (always take the talk that ends first). Give each talk a value and ask for the largest total value, and the same greedy rule breaks, while a dynamic program still works. The program compares both on a small instance, with brute force as the referee.

python · try it yourself
from itertools import combinations

talks = [("a", 0, 3, 2), ("b", 2, 5, 9), ("c", 4, 7, 3), ("d", 7, 9, 4), ("e", 3, 10, 12)]   # name, start, end, value

def compatible(chosen):
    chosen = sorted(chosen, key=lambda t: t[1])
    return all(x[2] <= y[1] for x, y in zip(chosen, chosen[1:]))

def greedy(talks):
    chosen, free_at = [], float("-inf")
    for t in sorted(talks, key=lambda t: t[2]):          # earliest end first
        if t[1] >= free_at:
            chosen.append(t); free_at = t[2]
    return chosen

def best(talks, score):
    return max((c for k in range(len(talks) + 1) for c in combinations(talks, k) if compatible(c)), key=score)

g = greedy(talks)
print("greedy picks", [t[0] for t in g], "->", len(g), "talks, value", sum(t[3] for t in g))
most = best(talks, len)
print("most talks  ", [t[0] for t in most], "->", len(most), "talks")
richest = best(talks, lambda c: sum(t[3] for t in c))
print("best value  ", [t[0] for t in richest], "-> value", sum(t[3] for t in richest))
greedy picks ['a', 'c', 'd'] -> 3 talks, value 9
most talks   ['a', 'c', 'd'] -> 3 talks
best value   ['a', 'e'] -> value 14

Greedy finds the maximum number of talks, three, but a poor total value; the best value comes from just two talks, one of which greedy rejected. The unweighted problem is the subject of Activity Selection, and the weighted one is solved by the DP in Choosing the State. Telling the two situations apart, and proving which technique applies, is the main skill this course teaches.

What the course covers

Section Problems and algorithms Main results
Dynamic programming rod cutting, matrix chains, longest common subsequence, optimal BSTs, edit distance, 0/1 knapsack, weighted intervals, longest increasing subsequence from 2n2^n recursive calls to Θ(n2)\Theta(n^2); Θ(n3)\Theta(n^3) interval DPs; Θ(mn)\Theta(mn) string DPs; pseudo-polynomial Θ(nW)\Theta(nW); Θ(nlg⁡n)\Theta(n \lg n) by choosing the state
Greedy algorithms activity selection, shortest job first, fractional knapsack, Huffman codes, matroids, unit-task scheduling exchange arguments; Huffman optimality; greedy is optimal on every weighted matroid
Amortized analysis stack with multipop, binary counter, two-stack queue, dynamic tables aggregate, accounting and potential methods; O(1)O(1) amortized with doubling and the quarter rule

The DP lessons build one method step by step: first rod cutting, from naive recursion through memoization and bottom-up tables to reconstructing the solution, then the general principles (optimal substructure and overlapping subproblems), then a series of classic problems with different table shapes: one-dimensional, intervals i..ji..j, pairs of prefixes, items by capacity.

Conventions

  • Pseudocode follows the track's conventions (How to read pseudocode): arrays are 0-based, for i = 1 to n includes both ends, and DP tables are indexed by the natural subproblem parameters (a table entry m[i,j]m[i, j] for the subchain Ai⋯AjA_i \cdots A_j uses the matrix numbers 1..n1..n, and the Python version simply leaves row and column 0 unused).
  • lg⁡n\lg n is log⁡2n\log_2 n. Costs are counted in basic steps (table cells filled, calls made, bits flipped), never timed, so the numbers you see when you run an example are exactly the ones in the text.
  • Every algorithm comes with a Python version, and the core algorithms also with a C++20 version. Analysis and brute-force checks stay in Python. Random choices use a fixed seed.
  • The animations of DP tables (LCS, edit distance, knapsack, matrix chains) are produced by running the real algorithm. Next to each one, a Python program prints the same table.

What you should know first

The course assumes the analysis tools of Foundations of Algorithm Analysis (asymptotic notation, recurrences, loop invariants) and the data structures of Data Structures: Hashing, Search Trees, B-Trees & Union-Find: heaps for Huffman's algorithm, union-find for Kruskal's algorithm and for scheduling, dynamic arrays for amortized analysis. If dynamic programming is entirely new to you, the DSA course's lessons Memoization, Tabulation, Dynamic Programming and Greedy Algorithms are a gentle first look, and Counting with Dynamic Programming in Discrete Mathematics shows DP as a counting tool.

The course has practice problems in the practice area: rod cutting, matrix chains, LCS, edit distance, knapsack and subset sum, weighted job scheduling, longest increasing subsequence, activity selection, Huffman code length, optimal BSTs and the binary counter. Each lesson links to the ones it prepares you for.

Test yourself

Which two properties make a problem suitable for dynamic programming?

  1. Optimal substructure and overlapping subproblems
  2. The greedy-choice property and optimal substructure
  3. Sorted input and a small alphabet
  4. Divide and conquer and randomization

What does an amortized cost of O(1)O(1) per operation guarantee?

  1. Every single operation is O(1)O(1)
  2. Any sequence of nn operations costs O(n)O(n) in total
  3. Operations are O(1)O(1) on average over random inputs
  4. The data structure uses O(1)O(1) memory

With coins 1, 6 and 9, how many coins does the greedy rule use to pay 12, and what is optimal?

  1. 2 and 2
  2. 4 and 2
  3. 3 and 2
  4. 4 and 3