Dynamic Programming
Dynamic programming (DP) solves a problem by breaking it into smaller subproblems, solving each subproblem once, and combining the stored answers. The previous lessons showed the two implementation styles (memoization and tabulation); this lesson is about recognising DP problems and designing solutions for them.
A problem is a good DP candidate when it has:
- Optimal substructure: an optimal solution is built from optimal solutions of subproblems.
- Overlapping subproblems: the same subproblems come up again and again.
Typical signs: "count the number of ways…", "find the minimum/maximum…", "is it possible to…", over sequences, grids, budgets or strings.
The design recipe
| Step | Question |
|---|---|
| 1. State | What does one subproblem look like? (dp[i] = best answer for the first i items…) |
| 2. Transition | How is a state computed from smaller states? |
| 3. Base cases | Which states are known without computation? |
| 4. Order | In what order must states be computed (or just memoize)? |
| 5. Answer | Which state (or combination) is the final answer? |
Let's apply it to three classic problems.
Example 1: climbing stairs
You can climb 1 or 2 steps at a time. How many different ways are there to climb n steps?
- State:
ways[i]= number of ways to reach stepi. - Transition: the last move was 1 step (from
i-1) or 2 steps (fromi-2):ways[i] = ways[i-1] + ways[i-2]. - Base:
ways[0] = 1(do nothing),ways[1] = 1.
def climb(n, steps=(1, 2)):
ways = [1] + [0] * n
for i in range(1, n + 1):
ways[i] = sum(ways[i - s] for s in steps if s <= i)
return ways
print(climb(10))
print("with 1, 2 or 3 steps:", climb(10, (1, 2, 3))[10])[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
with 1, 2 or 3 steps: 274
With steps of 1 and 2 this is the Fibonacci sequence again. Generalising to any set of step sizes needed one change.
Example 2: house robber (pick non-adjacent items)
Houses along a street hold different amounts of money. A robber can't rob two neighbouring houses (the alarm would go off). What is the maximum total?
- State:
best[i]= maximum money from the firstihouses. - Transition: either skip house
i(best[i-1]) or rob it and skip its neighbour (money[i] + best[i-2]).
def max_loot(money):
best = [0] * (len(money) + 1)
best[1] = money[0]
for i in range(2, len(money) + 1):
best[i] = max(best[i - 1], money[i - 1] + best[i - 2])
# trace back which houses were robbed
picked, i = [], len(money)
while i > 0:
if i == 1 or best[i] != best[i - 1]:
picked.append(i - 1)
i -= 2
else:
i -= 1
return best[-1], sorted(picked)
houses = [6, 7, 1, 30, 8, 2, 4]
total, picked = max_loot(houses)
print("houses:", houses)
print("best total:", total, "robbing houses at index", picked, [houses[i] for i in picked])houses: [6, 7, 1, 30, 8, 2, 4]
best total: 41 robbing houses at index [1, 3, 6] [7, 30, 4]
A greedy rule like "always take the richest remaining house" isn't guaranteed to work here; DP checks both options at every house.
Example 3: edit distance
How many single-character insertions, deletions or substitutions turn one word into another? This edit distance (Levenshtein distance) powers spell checkers ("did you mean…?") and fuzzy search.
- State:
d[i][j]= edit distance between the firstiletters ofaand the firstjletters ofb. - Transition: if the last letters match,
d[i][j] = d[i-1][j-1]; otherwise1 + min(d[i-1][j](delete),d[i][j-1](insert),d[i-1][j-1](substitute)). - Base:
d[i][0] = i,d[0][j] = j(delete or insert everything).
def edit_distance(a, b):
d = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
for i in range(len(a) + 1):
d[i][0] = i
for j in range(len(b) + 1):
d[0][j] = j
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
if a[i - 1] == b[j - 1]:
d[i][j] = d[i - 1][j - 1]
else:
d[i][j] = 1 + min(d[i - 1][j], d[i][j - 1], d[i - 1][j - 1])
return d[len(a)][len(b)]
for a, b in [("kitten", "sitting"), ("flaw", "lawn"), ("python", "python"), ("", "abc")]:
print(f"{a!r} -> {b!r}: {edit_distance(a, b)}")
words = ["apple", "apply", "ample", "maple", "angle"]
typo = "appel"
print("closest to", typo, "->", min(words, key=lambda w: edit_distance(typo, w)))'kitten' -> 'sitting': 3
'flaw' -> 'lawn': 2
'python' -> 'python': 0
'' -> 'abc': 3
closest to appel -> apple
kitten → sitting needs 3 edits: substitute k→s, substitute e→i, insert g.
DP vs greedy vs divide and conquer
| Technique | Subproblems | Decision |
|---|---|---|
| Divide and conquer (merge sort) | independent, don't overlap | combine results |
| Greedy (Huffman, Prim) | one choice at a time, never revisited | locally best choice |
| Dynamic programming | overlap, reused from a table | try all choices, keep the best |
DP is the safe choice when greedy might be wrong; greedy is faster when you can prove the local choice is safe.
Complexity
The cost of a DP is usually number of states × work per state: climbing stairs is O(n · s) for s step sizes, house robber is O(n), edit distance is O(len(a) · len(b)).
Going further: Design Techniques in the Algorithm Theory track treats dynamic programming in depth: optimal substructure, reconstructing solutions, optimal BSTs and pseudo-polynomial time.
Test yourself
Which two properties make a problem suitable for dynamic programming?
- Sorted input and small values
- Optimal substructure and overlapping subproblems
- A greedy choice and a heap
- Recursion and randomness
How many ways are there to climb 5 steps taking 1 or 2 steps at a time?
- 5
- 8
- 10
- 13
What is the edit distance between "cat" and "cut"?
- 0
- 1
- 2
- 3