Dynamic programming
Solve problems with overlapping subproblems by computing each one once and reusing the answer, often by filling a table: edit distance, knapsack, routing.
Description
Some recursive problems solve the same subproblems again and again. Computing Fibonacci numbers naively, fib(n) = fib(n−1) + fib(n−2), recomputes fib(2) an exponential number of times. Dynamic programming computes each subproblem once and stores the answer.
There are two styles. Memoization (top-down) keeps the recursive code and caches results in a map. Tabulation (bottom-up) fills a table in an order where every cell's dependencies are already filled, often in a simple loop, as in the step-through.
A problem suits DP when it has optimal substructure (the best answer is built from best answers to subproblems) and overlapping subproblems. The hard part is defining the subproblem. For edit distance, the number of insertions, deletions and replacements to turn one word into another, the subproblem is: the distance between the first i letters of one word and the first j letters of the other. Each cell depends on three neighbors: above (delete), left (insert) and diagonal (replace or match).
DP powers spell checkers and diff (edit distance and longest common subsequence), DNA alignment, route planning, the knapsack problem in resource allocation, text justification, and many scheduling problems.
How it works
The finished edit-distance table for "kitten" → "sitting": the answer, 3, is in the bottom-right corner
- : 0, 1, 2, 3, 4, 5, 6, 7
- k: 1, 1, 2, 3, 4, 5, 6, 7
- i: 2, 2, 1, 2, 3, 4, 5, 6
- t: 3, 3, 2, 1, 2, 3, 4, 5
- t: 4, 4, 3, 2, 1, 2, 3, 4
- e: 5, 5, 4, 3, 2, 2, 3, 4
- n: 6, 6, 5, 4, 3, 3, 2, 3
Step through: edit distance from "cat" to "cart", one cell at a time
Step 1 of 14Turn "cat" into "cart". The first row and column are the cost from or to an empty string.
Complexity
| Operation | Average | Worst |
|---|---|---|
| Edit distance of lengths m and n | O(m · n) | O(m · n) |
| 0/1 knapsack, n items, capacity WPseudo-polynomial: depends on W's value. | O(n · W) | O(n · W) |
| Fibonacci: naive recursion vs DP | O(φⁿ) vs O(n) | O(φⁿ) vs O(n) |
Space: O(m · n) for the full table; often O(min(m, n)) keeping only the last row
TypeScript implementation
Edit distance with a two-row table, and the 0/1 knapsack problem with memory reduced to one row.
// Two classic dynamic programming problems, each keeping only one or two
// rows of the table in memory.
/** Minimum insertions, deletions and replacements to turn a into b. */
export function editDistance(a: string, b: string): number {
let prev = Array.from({ length: b.length + 1 }, (_, j) => j); // row for the empty prefix of a
for (let i = 1; i <= a.length; i++) {
const cur = [i];
for (let j = 1; j <= b.length; j++) {
cur[j] = Math.min(
prev[j] + 1, // delete a[i-1]
cur[j - 1] + 1, // insert b[j-1]
prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1), // replace, or match for free
);
}
prev = cur;
}
return prev[b.length];
}
/** 0/1 knapsack: best total value within a weight budget, each item used at most once. */
export function knapsack(items: { name: string; weight: number; value: number }[], capacity: number): number {
const best = new Array(capacity + 1).fill(0); // best[w] = best value with budget w
for (const it of items) {
for (let w = capacity; w >= it.weight; w--) {
// iterate downwards so each item is counted once
best[w] = Math.max(best[w], best[w - it.weight] + it.value);
}
}
return best[capacity];
}
export function demo(): string[] {
const features = [
{ name: "SSO", weight: 5, value: 10 },
{ name: "audit log", weight: 4, value: 40 },
{ name: "exports", weight: 6, value: 30 },
{ name: "API v2", weight: 3, value: 50 },
];
return [
`edit distance kitten → sitting: ${editDistance("kitten", "sitting")}`,
`edit distance cat → cart: ${editDistance("cat", "cart")}`,
`best value of features fitting 10 engineer-weeks: ${knapsack(features, 10)} (audit log + API v2)`,
];
}When to use it
Use it when
- Optimization or counting problems with overlapping subproblems: sequences, grids, budgets.
- Naive recursion is exponential but the number of distinct subproblems is small.
- Comparing sequences: diffs, spell checking, alignment.
Avoid it when
- Subproblems don't overlap: plain recursion or divide and conquer is enough.
- A greedy choice is provably optimal: it's simpler and faster.
- The state space is enormous: approximation or heuristics may be needed.
Pitfalls
- Defining the wrong state, missing information the subproblem needs.
- Filling the table in the wrong order, reading cells that aren't computed yet.
- Using O(m · n) memory when only the previous row is needed.
- Off-by-one indexing between string positions and table positions, which are shifted by one for the empty-prefix row and column.
Alternatives
Backtracking
Choose it when you need to enumerate solutions rather than optimize, and subproblems don't repeat.
Greedy algorithms
Choose it when local choices are provably optimal, as in interval scheduling.
Dijkstra's shortest path
Choose it when the problem is a shortest path with non-negative costs; it's DP with a smart order.