08 · Dynamic Programming

LCS · edit distance · 0/1 knapsack — three classic DP tables fill cell-by-cell, then traceback in red.

Longest Common Subsequence click "Run" to fill the DP table
try:

What you're watching

A DP table is a 2-D array indexed by sub-problem coordinates. Each cell stores the answer to one sub-problem; later cells combine earlier cells' answers via a recurrence. Watching the cells fill, in order, makes the recurrence concrete: every cell's value comes from at most three other cells (its top, left, and diagonal neighbours, depending on the problem). The red path at the end is the traceback — the chain of cells whose decisions add up to the optimal answer at the bottom-right corner.

The three problems

Longest Common Subsequence (LCS)   O(mn)

Given two strings A and B of length m and n, find the longest sequence of characters that appears in both, in order (but not necessarily contiguous). Recurrence:

Final answer is at dp[m][n]. Traceback walks diagonally on a match, otherwise to whichever neighbour holds the larger value.

Edit (Levenshtein) Distance   O(mn)

Minimum number of single-character edits (insert / delete / substitute) to turn A into B. Recurrence:

The three options at each non-match cell correspond to the three edit operations: substitute (diagonal), delete (up), insert (left).

0/1 Knapsack   O(nW)

Given n items with weights and values, and a knapsack of capacity W, pick a subset of items maximising total value while keeping total weight ≤ W. The "0/1" means each item is either taken whole or not at all. Recurrence:

Note this is pseudo-polynomial: O(nW), where W is the numerical capacity, not the input size in bits. When W is huge, DP becomes infeasible — the problem is actually NP-hard in the general case.

WHY THE TRACEBACK MATTERS
Filling the table tells you the cost / count of the optimal solution. But to actually recover that solution (which characters in the LCS, which edit operations, which items in the knapsack) you need a second pass that walks back from the final cell, deciding at each step which neighbour was the predecessor. The red path on the canvas above is exactly that second pass.

What I learned writing this

← Back to all algorithms