Dynamic programming: principles and sequence problems
Develop dynamic programming from subproblem DAGs through LIS, knapsack, edit distance and Hirschberg reconstruction.
After this lesson you can
- Formulate dynamic programming by defining subproblems, recurrence, evaluation order and base cases.
- Draw the subproblem graph and calculate cost from it.
- Reconstruct an optimal solution, not only its value, with pointers or recomputation.
- Implement O(n log n) LIS, 0/1 knapsack and edit distance.
- Reduce memory to O(n) and recover alignment with Hirschberg.
Before you start
Motivation: the same question a thousand times
Fibonacci numbers obey recurrence , , , and a literal code translation is a function calling itself twice. It is correct and disastrous. Let count calls made computing : count one for itself and its two children’s calls, with . Induction shows : true for , and if true for and , then . Since grows like with , computing makes 331,160,281 calls and more than . Yet only distinct values need computing: . The recursion tree repeats the same subproblems again and again, and all cost is in those repetitions.
The solution is this lesson’s idea: compute each subproblem once and remember its result. Then costs operations, an exponential-to-linear improvement without changing the recurrence. Applied methodically, this is dynamic programming, probably the algorithm-design technique solving the most useful problems:
- Compare text and sequences. The
diffused with Git, spellchecking, DNA and protein alignment and speech-transcript comparison are the same dynamic-programming table (edit distance, seen in full here). - Inference in sequence models. The Viterbi and forward algorithms for a hidden Markov model, and CTC alignment in speech recognition, are dynamic programming on a state grid.
- Sequential decisions. Reinforcement learning’s value iteration and Bellman optimality equations are literally the technique naming this lesson.
- Combinatorial optimization. Knapsack, rod cutting, increasing subsequences and almost every problem of “choosing a good sequence of decisions”.
The first interactive shows the phenomenon. Choose a problem and raise : the recursion tree explodes while distinct subproblems barely grow. Switch among three views (tree, memoized tree, subproblem graph) and hover a node to see all its repetitions.
The lesson proceeds as follows. First, what structure a problem needs for dynamic programming and how to formalize it as a graph. Then two implementations (memoization and tabulation) and the practical issue of recovering the solution, not just its value. Next four canonical problems: rod cutting, longest increasing subsequence (including its version), knapsack (introducing pseudopolynomiality), and edit distance. We end with Hirschberg’s trick, reducing memory from quadratic to linear.
Optimal substructure and overlapping subproblems
The first property is Bellman’s principle of optimality: in an optimal policy, remaining decisions from any reached state are optimal for that state. The second distinguishes dynamic programming from familiar techniques:
- With divide and conquer, subproblems are disjoint (mergesort sorts two different halves), so nothing needs remembering; without repeated subproblems a table saves no steps.
- A greedy algorithm takes one local decision and continues without exploring alternatives. Dynamic programming explores all options per subproblem, but only once per subproblem; thus it is slower than a correct greedy algorithm and more general (in the previous lesson, 0/1 knapsack was where greedy failed and dynamic programming succeeded).
To make optimal substructure more than a slogan, see how it is proved. The same “cut and paste” argument always applies:
Proof
Let be the optimum and the part of cutting a rod of length . If a solution for earned more than , piece plus would solve with revenue , contradicting optimality of (proof by contradiction).
∎The key is that the subproblem is independent of the rest: its solution can change without affecting anything else. When independence fails, dynamic programming does not apply as stated. The classic example is the longest simple path (no repeated vertices). In four-vertex cycle , the longest simple path from to may be , but its first segment is not the longest simple path from to (which is ): pasting it with would visit twice. Subproblem and remainder share vertices, so optimizing one separately breaks the other. The shortest path does have optimal substructure, hence Dijkstra, Bellman-Ford and Floyd-Warshall work; longest simple path is NP-hard.
Dynamic-programming design steps are always the same; write them explicitly before coding:
- Subproblem. Which parameters define a subproblem and what is calculated for each. This is the most important decision: state must contain everything the future needs to know about the past.
- Recurrence. Express a subproblem’s value using smaller ones, trying every “last decision” option.
- Base cases. Subproblems with no dependencies.
- Order. An evaluation order placing each subproblem after its dependencies.
- Answer and reconstruction. Which subproblem (or maximum among them) is the solution and, when the solution rather than only its value is requested, what must be stored to recover it.
Cost reads the same way: number of subproblems times work per subproblem, made a theorem next.
The subproblem graph
Notice the interactive’s “DAG” view. Nodes are distinct subproblems and an edge appears whenever solving one requires another’s value. This form is general.
Acyclicity makes the recurrence a valid definition (well-founded induction: each value is defined using earlier ones in the order) and permits ordered computation. A topological order, a linear extension of the partial order “ before if depends on ”, is exactly a valid evaluation order (recipe step 4). Cost then follows without surprises:
Proof
In topological order each node is evaluated once, reading already computed dependency values in the table. Total cost is . (Memoization, evaluating in depth-first order, has the same cost plus recursion management.)
∎In other words, dynamic-programming time is the size of its graph, not its recursion tree, and the two may differ by orders of magnitude. In the interactive, with for Fibonacci the tree has nodes and the graph 41 nodes and 78 edges.
A second useful reading of the same object: if each edge has a weight, a subproblem’s optimum is the best path to base cases: a shortest or longest DAG path computed in linear time in topological order (the DAG shortest-path algorithm covered later). In this language:
- Rod cutting. Nodes (length already cut) and edge of weight for each possible piece. Maximum revenue is the longest path from to .
- Longest increasing subsequence. Edge when and , weight 1. LIS is the DAG’s longest path (with source and terminal nodes).
- Edit distance. A grid of nodes with horizontal, vertical and diagonal edges weighted by operation cost. Distance is the shortest path from to , as drawn in the table below.
- Knapsack. Nodes by item and remaining capacity, with two outgoing edges: take the item or not.
Not everything reduces to paths (problems where one decision combines two subproblems, such as matrix-chain multiplication, are hypergraphs studied in the next lesson), but the DAG remains the right picture for cost and order.
Memoization versus tabulation
There are two ways to organize computation on the DAG, both appearing in real code.
Both compute exactly the same values with the same recurrence operations, but behave differently in practice:
| Memoization (top-down) | Tabulation (bottom-up) | |
|---|---|---|
| Writing it | Almost free: recurrence as-is (in Python, @functools.cache) | Decide loop order |
| Subproblems computed | Only those reachable from the answer | All table entries (even unneeded ones) |
| Memory | Stores every result | Can discard no-longer-needed values (two-variable Fibonacci, LIS or two-row edit distance) |
| Speed per subproblem | Slower: calls, hash table | Fast; can be vectorized (Lab 2) |
| Stack depth | Up to longest DAG path: overflows Python’s stack (usual limit 1000) | None |
The practical choice: memoization for prototyping, recurrence verification and when only a fraction of subproblems is needed; tabulation for speed, memory control or avoiding recursion limits. A good workflow writes the memoized version first (almost the recurrence without noise) and uses it as an oracle to test tabulation.
Rod cutting and solution reconstruction
A rod of length can be sold whole or cut into integer-length pieces, and a length- piece earns (prices are nonlinear). How should it be cut for maximum revenue? With the earlier optimal-substructure lemma, try every first-piece option:
With prices for we obtain . The subproblem is “remaining length”; there are subproblems and length tries options, so cost is time and memory. The recursion tree without memory has exactly nodes (recurrence is solved by induction: ): for , 1024 calls versus 11 subproblems. See the opening interactive.
So far we computed optimum value. Usually the solution is also requested: not merely revenue, but how to cut. Two ways recover it:
- Pointers (or saved decisions): alongside store , the maximizing piece. Reconstruction follows pointers from : cut , move to , and continue to 0. It costs extra memory and time.
- Recomputation: store only the value table and during reconstruction search again for the option explaining each state (). No extra memory is needed, but the search repeats: generally one decision’s work per reconstruction step. Here, if each state’s are tried increasingly until the first match, checks cut a piece of length ; since piece lengths sum to , entire reconstruction costs .
Recomputation is what edit distance does while backtracking through its table, and enables memory savings (for example, Hirschberg). Lab 1 implements both for rod cutting.
Longest increasing subsequence
A subsequence is not a substring: elements can be separated. With many increasing subsequences exist, and the longest found by the algorithm below is , of length 6. Trying subsets is infeasible; dynamic programming solves it in quadratic time.
The version. The useful subproblem is , the length of the best increasing subsequence ending at (not “among the first elements”: that definition has no recurrence because the last element matters for extension). The last decision is the previous element, and
There are subproblems with work each, and the DAG is “ if and ” (in the opening interactive, with sentinels and for a single source and destination). Storing for each the maximizing reconstructs the subsequence.
The version. To improve on quadratic, change state: rather than one value per position, maintain for every length the smallest possible tail:
A smaller tail is better because it allows more extensions. Two facts enable the algorithm: sequence is strictly increasing (from a length- subsequence ending at obtain a length- one ending below ), and on reading element only one tail changes: the first with becomes , and if no exists, a new tail appears. Since is sorted, binary search finds that position in .
Visualize it as solitaire, patience sorting: deal sequence cards left to right, placing each on the leftmost pile whose top is greater than or equal; if none exists, open a new pile to the right. Pile tops are exactly tails , always sorted, so pile search is binary.
The key is that pile count is LIS length, and pointers (one position per element) suffice to reconstruct an optimal subsequence, even though tails change and the reconstructed subsequence may never have been the pile tops simultaneously. The invariant proving it follows, and proving it is the final “Patience sorting computes LIS” exercise.
The algorithm costs time and memory and cannot improve in the comparison model: Fredman (1975) proved computing LIS length requires comparisons in the worst case, attained by a variant of this algorithm that checks whether the card opens a new pile before binary search. Two easily broken details: for strictly increasing LIS use bisect_left (first tail ), and for nondecreasing (allowing repeats) use bisect_right (first tail ); and the card’s pointer is not the current top of pile but the one present at that moment.
The piles hide a classic combinatorial result, with a three-line proof thanks to them.
Proof
Deal cards with patience sorting. If LIS length were at most , there would be at most piles. Each pile is a decreasing subsequence (each card lands on a greater one, strictly greater if values are distinct). If all decreasing subsequences had length at most , no pile would exceed cards and total cards would be at most . With cards this is impossible.
∎For a random permutation of elements, LIS is surprisingly short: mean length grows like (Vershik and Kerov, Logan and Shepp, 1977), with correction and fluctuations of order following the Tracy–Widom distribution (Baik, Deift and Johansson, 1999). Lab 1 checks this by simulation.
0/1 knapsack and pseudopolynomiality
There are items, item with integer weight and value , and a knapsack with integer capacity . Each item is taken whole or left (0/1). Maximize total value without exceeding capacity. This is where the previous lesson’s greedy algorithm failed: with and density-greedy gets 160 and optimum 220.
The subproblem is , best value using only the first items at capacity . For item there are two choices, leave or take it (if it fits):
There are subproblems with work each: time and memory. Reconstruction backtracks from : if , item is in the solution and move to ; otherwise move to . Since each row depends only on the previous one, the value needs one row of positions updated right to left:
for v, p in zip(valores, pesos):
for w in range(W, p - 1, -1):
dp[w] = max(dp[w], dp[w - p] + v)
Direction matters. Traversed left to right, dp[w - p] already includes the current item and it can be used repeatedly: this solves unbounded knapsack, a different problem (Lab 1 shows 300 with the three items above, five copies of the first).
Now the delicate point. looks polynomial, but not in the sense relevant to complexity. Correct input size is the number of bits occupied, and number occupies bits, not . An input with items and -bit capacity has size , and the algorithm performs operations: exponential in input size. One extra bit in doubles work.
This contradicts nothing: knapsack is NP-hard, so an algorithm polynomial in bit size would prove . Dynamic programming gives a regime where it is easy: when weights are small (for example bounded by a polynomial in ), the algorithm is polynomial. Problems with this property are called weakly NP-hard, unlike strongly NP-hard problems (such as 3-partition, distributing numbers into equal-sum triples, or traveling salesperson), which stay hard even with small numbers. Later NP-completeness and approximation lessons revisit this.
There is also a by-value version: is minimum weight needed for exact value with the first items, and the answer is the largest with . It costs with and is pseudopolynomial in values, not weights. Rounding values so is small gives a fully polynomial approximation scheme (FPTAS), a central approximation idea covered in the module.
Edit distance, LCS and alignment
How similar are “kitten” and “sitting”? A natural answer counts the minimum elementary edits transforming one into the other.
Let be distance between prefixes and . The last column of an optimal alignment can be three types: aligned with (match or substitute), aligned with a gap (delete), or a gap aligned with (insert ). Each leaves a smaller problem of the same type, and the recurrence is
with and . This is an -cell table with three candidates per cell: time and memory, with distance . Graphically it is the grid shortest path discussed earlier: each cell has three incoming edges weighted by operation costs.
Try the interactive with your own strings. Each cell’s arrows (diagonal, up, left) identify which of the three candidates attains the minimum, and at the end reconstruction follows them backward from the final corner.
Recurrence correctness is proved by induction on in the first final exercise. The idea is optimal substructure: removing the last column of an optimal alignment of leaves an alignment of one of three smaller prefixes that must be optimal (otherwise the total improves); conversely, each option can be built by adding a column to an optimal alignment of the corresponding prefix.
This is one of computing’s most reused tables.
- LCS. The longest common subsequence of and satisfies if , and otherwise. It is edit distance with unit insertions and deletions and impossible (or cost-2) substitution: . For “intention” and “execution” LCS is 5 and unit-cost distance 5, whereas cost-2 substitution gives 8 (the example’s ).
- Needleman–Wunsch (1970). Global biological-sequence alignment: instead of minimizing costs, maximize a score, with a substitution matrix (scoring substitutions between similar amino acids higher) and gap penalty. It is the same table with changed to . Smith and Waterman (1981) add zero to the recurrence for best local alignment.
diff. Comparing two files calculates an LCS on lines: lines in LCS are unchanged, the rest deletions and additions. Original Unixdiff(Hunt and McIlroy, 1976) computes that LCS using a variant visiting only equal-line pairs instead of the whole table; GNU uses Myers’s algorithm (1986), costing with the edit-script size, very fast for similar files, the usual case.- Machine learning. Speech recognition word error rate (WER) is edit distance between words, and dynamic time warping (DTW) uses the same grid with another cost function.
One complexity observation. The table costs and nothing substantially better is known (for finite alphabets Masek and Paterson’s 1980 “four Russians” technique gains only a logarithmic factor): Backurs and Indyk (2015) showed an -time edit-distance algorithm with would refute the strong exponential time hypothesis (SETH). This is a case where textbook dynamic programming is essentially optimal.
Hirschberg: linear memory
Filling the edit-distance table costs quadratic time, often tolerable; quadratic memory often is not. Two sequences of symbols produce cells: about 40 GB with 4-byte integers. To compute only distance value, two rows suffice (each depends on the preceding one), requiring memory. Alignment is the problem: backtracking needs every cell’s arrows.
Hirschberg’s solution (1975) combines dynamic programming and divide and conquer: Hirschberg’s space reduction recovers the full alignment with linear memory, at the cost of doubling time, recomputing instead of storing. A middle-row lemma is key. Let and define, for each ,
the distance of the upper half of to a prefix of and of the lower half to the complementary suffix. is the table’s middle row and the same row computed backwards, over reversed strings (reversing both changes no operation cost). Both use two rows of memory.
Proof
Every alignment corresponds to a monotone path from to in the grid, and every path contains at least one cell in the middle row. Its cost is the sum of the segment to that cell, at least , and the segment from it, at least . Thus . Conversely, for every , joining an optimal path from to with one from to gives cost , so for every . Therefore , and the path built at a minimizing costs .
∎The algorithm is recursive: compute and , take an minimizing , and split into two independent subproblems: align with and with , each with half the rows. When either string has one character or none, solve directly with a one-row table.
Proof
Time. Count evaluated cells; each costs . In a rectangle of rows and columns, and together cost cells (each row computed once, forward or backward). With and , total satisfies , with and .
If is a power of 2, induction is immediate: . This is a geometric series: subrectangle area at each level is half the preceding level, and .
For arbitrary , rounding adds a lower-order term. Let , satisfying for . Inductively prove . Base case . In the step, since ,
Term is needed: with , and splits in the worst possible places, 20 cells are evaluated, more than . But it is negligible relative to .
Space. Each call needs memory (three rows: and the two work rows of ), recursion depth is , and subproblems are solved one after another, reusing working memory. The resulting alignment, size , must also be stored.
∎In the interactive example (8 by 5 characters), the algorithm calculates 75 cells versus the table’s 40 interior cells, a factor of 1.88, with 18 cells of memory instead of 54. The trick works because recomputation is cheap: spend another factor 2 in time to avoid storing arrows. It applies to any grid dynamic program whose path can split at an intermediate row, and extends to affine-gap scoring (Myers and Miller, 1988), used by long-sequence aligners.
Lab 1: dynamic programming from the recurrence
Each cell implements a lesson component from scratch and checks it against brute force or the standard library. The first compares recursion tree with table for functools.cache and rod cutting, reconstructing by pointers and recomputation.
import sys, time
from functools import cache
# ---------- 1. Fibonacci: el árbol de recursión frente a la tabla ----------
def fib_ingenuo(n, llamadas):
llamadas[0] += 1
return n if n < 2 else fib_ingenuo(n - 1, llamadas) + fib_ingenuo(n - 2, llamadas)
def fib_memo(n):
@cache
def f(k):
return k if k < 2 else f(k - 1) + f(k - 2)
v = f(n)
return v, f.cache_info()
def fib_tabla(n):
a, b = 0, 1 # solo se necesitan los dos últimos valores
for _ in range(n):
a, b = b, a + b
return a
for n in (10, 20, 25):
c = [0]
v = fib_ingenuo(n, c)
_, info = fib_memo(n)
print(f"F({n}) = {v:6d} | llamadas ingenuas: {c[0]:7d} | con memo: {info.misses} cálculos y {info.hits} consultas")
# la recursión profunda tiene un límite en Python; la tabla, no
limite = sys.getrecursionlimit()
sys.setrecursionlimit(200) # límite bajo a propósito: el fallo es el mismo en cualquier entorno, y la pila no corre peligro
try:
fib_memo(500)
except RecursionError:
print("fib_memo(500) con límite de recursión 200: RecursionError (el límite por defecto era", limite, ")")
finally:
sys.setrecursionlimit(limite)
print("fib_tabla(5000) tiene", len(str(fib_tabla(5000))), "cifras")
# ---------- 2. Corte de varillas: valor, puntero y reconstrucción ----------
PRECIOS = [0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30] # PRECIOS[i] = precio de un trozo de longitud i
def corte_memo(n, precios):
"""Arriba-abajo: r(n) = max_k precios[k] + r(n - k). Devuelve el valor y cuántos subproblemas distintos resolvió."""
@cache
def r(m):
return 0 if m == 0 else max(precios[k] + r(m - k) for k in range(1, m + 1))
return r(n), r.cache_info().currsize
def corte_tabla(n, precios):
"""Abajo-arriba, con un puntero por subproblema: primero[m] = longitud del primer trozo de una solución óptima."""
r = [0] * (n + 1)
primero = [0] * (n + 1)
for m in range(1, n + 1):
r[m], primero[m] = max((precios[k] + r[m - k], k) for k in range(1, m + 1))
trozos, m = [], n
while m > 0: # la reconstrucción sigue los punteros
trozos.append(primero[m])
m -= primero[m]
return r[n], trozos
def corte_recomputando(n, precios, r):
"""Sin punteros: se vuelve a buscar qué opción alcanza el óptimo, usando solo la tabla de valores."""
trozos, m = [], n
while m > 0:
k = next(k for k in range(1, m + 1) if precios[k] + r[m - k] == r[m])
trozos.append(k)
m -= k
return trozos
r = [corte_tabla(m, PRECIOS)[0] for m in range(11)]
print("r(0..10) =", r)
for n in (7, 10):
valor, trozos = corte_tabla(n, PRECIOS)
print(f"n = {n:2d}: ingreso {valor}, trozos {trozos} | memo (valor, subproblemas) = {corte_memo(n, PRECIOS)} | sin punteros {corte_recomputando(n, PRECIOS, r)}")
t = time.perf_counter()
fib_tabla(20000)
print(f"fib_tabla(20000): {1000 * (time.perf_counter() - t):.1f} ms")Naive calls match (for example 177 for ), while memoization has computations and lookups: total calls, DAG edge count plus one. Memoized recursion fails with RecursionError once exceeds the recursion limit (deliberately lowered to 200 so failure is identical everywhere and does not endanger the interpreter stack), while tabulation computes a number with over a thousand digits easily. Rod-cutting recomputation reconstructs a valid solution (possibly different from pointers on ties: here for several decompositions are worth 18).
The second cell implements LIS both ways, checks against brute force and tests the random-permutation LIS law.
import bisect, itertools, math, random, time
# ---------- LIS en O(n^2): L[i] = 1 + max L[j], j < i, a[j] < a[i] ----------
def lis_cuadratica(a):
n = len(a)
L, padre = [1] * n, [-1] * n
for i in range(n):
for j in range(i):
if a[j] < a[i] and L[j] + 1 > L[i]:
L[i], padre[i] = L[j] + 1, j
fin = max(range(n), key=L.__getitem__) if n else -1
sub = []
while fin >= 0:
sub.append(a[fin])
fin = padre[fin]
return sub[::-1]
# ---------- LIS en O(n log n): patience sorting con punteros ----------
def lis_patience(a):
colas = [] # colas[k] = índice de la menor cola de una subsecuencia creciente de longitud k+1
valores = [] # lo mismo, pero con los valores (para bisect)
padre = [-1] * len(a)
for i, x in enumerate(a):
k = bisect.bisect_left(valores, x) # estrictamente creciente: bisect_left
if k == len(valores):
colas.append(i); valores.append(x)
else:
colas[k] = i; valores[k] = x
padre[i] = colas[k - 1] if k > 0 else -1
sub, i = [], colas[-1] if colas else -1
while i >= 0:
sub.append(a[i])
i = padre[i]
return sub[::-1]
def es_creciente(s):
return all(x < y for x, y in zip(s, s[1:]))
def es_subsecuencia(s, a):
it = iter(a)
return all(x in it for x in s)
# ---------- comprobación contra la fuerza bruta ----------
def lis_bruta(a):
for r in range(len(a), 0, -1):
for idx in itertools.combinations(range(len(a)), r):
if es_creciente([a[i] for i in idx]):
return r
return 0
rnd = random.Random(1)
for _ in range(300):
a = [rnd.randint(1, 9) for _ in range(rnd.randint(0, 11))]
p, c = lis_patience(a), lis_cuadratica(a)
assert len(p) == len(c) == lis_bruta(a), a
assert es_creciente(p) and es_subsecuencia(p, a), (a, p)
print("patience y O(n^2) coinciden con la fuerza bruta, y la subsecuencia devuelta es válida (300 casos)")
ejemplo = [4, 9, 2, 7, 3, 8, 6, 10, 1, 5, 11, 7, 12, 8]
print("ejemplo:", lis_patience(ejemplo), "de longitud", len(lis_patience(ejemplo)))
# ---------- tiempos y la ley de la LIS de una permutación aleatoria ----------
def longitud(a):
t = []
for x in a:
k = bisect.bisect_left(t, x)
if k == len(t): t.append(x)
else: t[k] = x
return len(t)
for n in (500, 1000, 2000):
a = list(range(n)); rnd.shuffle(a)
t0 = time.perf_counter(); lis_cuadratica(a); t1 = time.perf_counter(); longitud(a); t2 = time.perf_counter()
print(f"n = {n:5d}: O(n^2) {1000 * (t1 - t0):7.1f} ms | O(n log n) {1000 * (t2 - t1):6.2f} ms")
for n in (100, 10000, 100000):
medias = []
for _ in range(20 if n <= 10000 else 5):
a = list(range(n)); rnd.shuffle(a)
medias.append(longitud(a))
print(f"permutaciones de {n:6d}: LIS media {sum(medias) / len(medias):7.1f} | 2*sqrt(n) = {2 * math.sqrt(n):6.1f} | 2*sqrt(n) - 1.77*n^(1/6) = {2 * math.sqrt(n) - 1.77 * n ** (1 / 6):6.1f}")The third is knapsack: table with reconstruction, one row in correct and incorrect directions, the by-value version and experimental demonstration of pseudopolynomiality.
import itertools, random, time
# ---------- mochila 0/1: tabla bidimensional con reconstrucción ----------
def mochila_tabla(valores, pesos, W):
n = len(valores)
T = [[0] * (W + 1) for _ in range(n + 1)] # T[i][w] = mejor valor con los i primeros objetos y capacidad w
for i in range(1, n + 1):
v, p = valores[i - 1], pesos[i - 1]
for w in range(W + 1):
T[i][w] = T[i - 1][w]
if p <= w and T[i - 1][w - p] + v > T[i][w]:
T[i][w] = T[i - 1][w - p] + v
elegidos, w = [], W
for i in range(n, 0, -1): # se retrocede: ¿cambió el valor al añadir el objeto i?
if T[i][w] != T[i - 1][w]:
elegidos.append(i - 1)
w -= pesos[i - 1]
return T[n][W], sorted(elegidos)
# ---------- una sola fila: el sentido del bucle lo es todo ----------
def mochila_fila(valores, pesos, W):
dp = [0] * (W + 1)
for v, p in zip(valores, pesos):
for w in range(W, p - 1, -1): # de derecha a izquierda: cada objeto se usa como mucho una vez
dp[w] = max(dp[w], dp[w - p] + v)
return dp[W]
def mochila_fila_mal(valores, pesos, W):
dp = [0] * (W + 1)
for v, p in zip(valores, pesos):
for w in range(p, W + 1): # de izquierda a derecha: dp[w - p] ya incluye este objeto
dp[w] = max(dp[w], dp[w - p] + v)
return dp[W]
valores, pesos, W = [60, 100, 120], [10, 20, 30], 50
print("tabla:", mochila_tabla(valores, pesos, W), "| una fila:", mochila_fila(valores, pesos, W), "| sentido equivocado:", mochila_fila_mal(valores, pesos, W))
def mochila_bruta(valores, pesos, W):
mejor = 0
for m in itertools.product([0, 1], repeat=len(valores)):
if sum(p for p, t in zip(pesos, m) if t) <= W:
mejor = max(mejor, sum(v for v, t in zip(valores, m) if t))
return mejor
rnd = random.Random(7)
for _ in range(200):
n = rnd.randint(1, 9)
v = [rnd.randint(1, 30) for _ in range(n)]
p = [rnd.randint(1, 12) for _ in range(n)]
W = rnd.randint(1, 40)
assert mochila_tabla(v, p, W)[0] == mochila_fila(v, p, W) == mochila_bruta(v, p, W)
valor, sel = mochila_tabla(v, p, W)
assert sum(p[i] for i in sel) <= W and sum(v[i] for i in sel) == valor
print("tabla, una fila y fuerza bruta coinciden en 200 instancias; la reconstrucción es válida")
# ---------- versión por valor: dp[u] = peso mínimo para conseguir valor u ----------
def mochila_por_valor(valores, pesos, W):
V = sum(valores)
INF = float("inf")
dp = [0] + [INF] * V
for v, p in zip(valores, pesos):
for u in range(V, v - 1, -1):
dp[u] = min(dp[u], dp[u - v] + p)
return max(u for u in range(V + 1) if dp[u] <= W)
print("por valor:", mochila_por_valor([60, 100, 120], [10, 20, 30], 50))
# ---------- pseudopolinómica: el tiempo crece con el VALOR de W, no con su longitud en bits ----------
n = 40
v = [rnd.randint(10, 99) for _ in range(n)]
p = [rnd.randint(50, 999) for _ in range(n)]
for W in (1000, 2000, 4000, 8000):
t0 = time.perf_counter(); mochila_fila(v, p, W); t = time.perf_counter() - t0
print(f"W = {W:5d} ({W.bit_length():2d} bits): {1000 * t:7.1f} ms, {n * W:7d} celdas")
print("Cada bit más en la entrada duplica el trabajo: con W de 64 bits habría 2^64 celdas por objeto")The fourth combines edit distance with alignment, Hirschberg from scratch and diff: check Hirschberg returns valid alignments of the same cost as the full table and compare LCS-based diff with standard-library difflib.
import difflib, random
# ---------- distancia de edición con tabla completa y alineamiento ----------
def tabla_edicion(a, b, ins=1, borr=1, sust=1):
m, n = len(a), len(b)
D = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
D[i][0] = i * borr
for j in range(1, n + 1):
D[0][j] = j * ins
for i in range(1, m + 1):
for j in range(1, n + 1):
D[i][j] = min(D[i - 1][j - 1] + (0 if a[i - 1] == b[j - 1] else sust),
D[i - 1][j] + borr,
D[i][j - 1] + ins)
return D
def alineamiento(a, b, ins=1, borr=1, sust=1):
"""Retrocede por la tabla: en cada celda se elige una operación que explica su valor."""
D = tabla_edicion(a, b, ins, borr, sust)
i, j, arriba, abajo = len(a), len(b), [], []
while i > 0 or j > 0:
if i > 0 and j > 0 and D[i][j] == D[i - 1][j - 1] + (0 if a[i - 1] == b[j - 1] else sust):
arriba.append(a[i - 1]); abajo.append(b[j - 1]); i, j = i - 1, j - 1
elif i > 0 and D[i][j] == D[i - 1][j] + borr:
arriba.append(a[i - 1]); abajo.append("-"); i -= 1
else:
arriba.append("-"); abajo.append(b[j - 1]); j -= 1
return D[len(a)][len(b)], "".join(reversed(arriba)), "".join(reversed(abajo))
d, s1, s2 = alineamiento("intention", "execution")
print(f"intention -> execution: distancia {d}\n {s1}\n {s2}")
print("kitten -> sitting:", alineamiento("kitten", "sitting")[0], "| intention -> execution con sustituir = 2:", tabla_edicion("intention", "execution", sust=2)[-1][-1])
# ---------- memoria lineal: solo la última fila ----------
def ultima_fila(a, b):
previa = list(range(len(b) + 1))
for i in range(1, len(a) + 1):
actual = [i] + [0] * len(b)
for j in range(1, len(b) + 1):
actual[j] = min(previa[j - 1] + (a[i - 1] != b[j - 1]), previa[j] + 1, actual[j - 1] + 1)
previa = actual
return previa
# ---------- Hirschberg ----------
def hirschberg(a, b):
"""Devuelve (arriba, abajo): un alineamiento óptimo con memoria O(len(b)) por llamada."""
if len(a) == 0:
return "-" * len(b), b
if len(b) == 0:
return a, "-" * len(a)
if len(a) == 1:
_, x, y = alineamiento(a, b) # caso base: una sola fila
return x, y
medio = len(a) // 2
F = ultima_fila(a[:medio], b) # prefijos de b contra la mitad superior de a
B = ultima_fila(a[medio:][::-1], b[::-1])[::-1] # sufijos de b contra la mitad inferior de a
k = min(range(len(b) + 1), key=lambda j: F[j] + B[j])
x1, y1 = hirschberg(a[:medio], b[:k])
x2, y2 = hirschberg(a[medio:], b[k:])
return x1 + x2, y1 + y2
def coste(x, y):
return sum(1 for p, q in zip(x, y) if p != q) # igualdad 0; sustitución, inserción y borrado 1
for a, b in [("AGTACGCA", "TATGC"), ("intention", "execution")]:
x, y = hirschberg(a, b)
print(f"{a} / {b}: coste {coste(x, y)} = tabla completa {tabla_edicion(a, b)[-1][-1]}\n {x}\n {y}")
rnd = random.Random(3)
for _ in range(200):
a = "".join(rnd.choice("ACGT") for _ in range(rnd.randint(0, 14)))
b = "".join(rnd.choice("ACGT") for _ in range(rnd.randint(0, 14)))
x, y = hirschberg(a, b)
assert x.replace("-", "") == a and y.replace("-", "") == b and len(x) == len(y)
assert coste(x, y) == tabla_edicion(a, b)[-1][-1]
print("Hirschberg devuelve un alineamiento válido de coste mínimo en 200 pares aleatorios")
# ---------- diff: subsecuencia común más larga sobre líneas, frente a difflib ----------
def lcs_tabla(A, B):
T = [[0] * (len(B) + 1) for _ in range(len(A) + 1)]
for i in range(len(A) - 1, -1, -1):
for j in range(len(B) - 1, -1, -1):
T[i][j] = T[i + 1][j + 1] + 1 if A[i] == B[j] else max(T[i + 1][j], T[i][j + 1])
return T
def mi_diff(A, B):
T, i, j, sal = lcs_tabla(A, B), 0, 0, []
while i < len(A) or j < len(B):
if i < len(A) and j < len(B) and A[i] == B[j]:
sal.append(" " + A[i]); i += 1; j += 1
elif i < len(A) and (j == len(B) or T[i + 1][j] >= T[i][j + 1]):
sal.append("- " + A[i]); i += 1 # con empate, primero el borrado, como en diff
else:
sal.append("+ " + B[j]); j += 1
return sal
viejo = "def f(x):\n y = x + 1\n print(y)\n return y\n".splitlines()
nuevo = "def f(x):\n y = x + 2\n print(y)\n log(y)\n return y\n".splitlines()
print("\n".join(mi_diff(viejo, nuevo)))
def editar(A, rnd, k):
B = A[:]
for _ in range(k):
op, i = rnd.choice("bis"), rnd.randrange(len(B))
if op == "b": del B[i]
elif op == "i": B.insert(i, f"nueva {rnd.randrange(10**6)}")
else: B[i] = f"cambiada {rnd.randrange(10**6)}"
return B
def comparar(generar, total=100):
iguales = peor = 0
for _ in range(total):
A, B = generar()
L = lcs_tabla(A, B)[0][0]
comunes = sum(bl.size for bl in difflib.SequenceMatcher(None, A, B, autojunk=False).get_matching_blocks())
assert comunes <= L # difflib nunca supera al óptimo
iguales += comunes == L
peor = max(peor, L - comunes)
return iguales, total, peor
ruido = lambda: ([rnd.choice("abcde") for _ in range(rnd.randint(5, 40))], [rnd.choice("abcde") for _ in range(rnd.randint(5, 40))])
def ficheros():
A = [f"linea {x}" for x in rnd.sample(range(1000), 60)]
return A, editar(A, rnd, 6)
print("difflib iguala la LCS exacta (secuencias de ruido): %d de %d, peor diferencia %d elementos" % comparar(ruido))
print("difflib iguala la LCS exacta (ficheros con 6 ediciones): %d de %d, peor diferencia %d líneas" % comparar(ficheros))Three output observations. Hirschberg returns valid alignments with a different gap distribution from the full table (different optimal alignments) but identical cost. Homemade diff marks lines outside LCS as changes (a modified line appears as deletion plus addition), exactly as diff does. difflib does not compute exact LCS: its SequenceMatcher finds the longest common block and recurses on both sides, a heuristic never exceeding the optimum, usually matching it on files differing by few edits, and often falling short on sequences with many repeated symbols (output matches in 30 of 100 five-symbol noise sequences and 100 of 100 files with 6 edits). This benefits real files (faster in practice) and is a trap when exact distance is needed.
Lab 2: vectorize dynamic programming
The pure-Python double loop follows the recurrence faithfully but is slow. Tabulation can be vectorized after identifying cells independent of one another. In edit distance all cells with (an antidiagonal) depend only on antidiagonals and , so are computed simultaneously with NumPy operations: vector steps instead of scalar steps. In knapsack the loop over becomes an operation on a shifted array, and right-to-left behavior follows automatically because NumPy evaluates the entire right side using the previous row before assignment.
import random, time
import numpy as np
# ---------- distancia de edición: doble bucle en Python puro ----------
def edicion_python(a, b):
previa = list(range(len(b) + 1))
for i in range(1, len(a) + 1):
actual = [i] + [0] * len(b)
for j in range(1, len(b) + 1):
actual[j] = min(previa[j - 1] + (a[i - 1] != b[j - 1]), previa[j] + 1, actual[j - 1] + 1)
previa = actual
return previa[-1]
# ---------- por antidiagonales: todas las celdas con i + j = k dependen solo de las diagonales k-1 y k-2 ----------
def edicion_numpy(a, b):
m, n = len(a), len(b)
A = np.array([ord(c) for c in a], dtype=np.int32)
Br = np.array([ord(c) for c in b][::-1], dtype=np.int32) # b invertida: así los índices de b bajan al subir i
GRANDE = m + n + 5
anterior2 = np.full(m + 1, GRANDE, dtype=np.int32) # diagonal k - 2
anterior = np.full(m + 1, GRANDE, dtype=np.int32) # diagonal k - 1
anterior[0] = 0 # k = 0: solo la celda (0, 0)
for k in range(1, m + n + 1):
actual = np.full(m + 1, GRANDE, dtype=np.int32)
if k <= n:
actual[0] = k # primera fila: D[0][k] = k
if k <= m:
actual[k] = k # primera columna: D[k][0] = k
lo, hi = max(1, k - n), min(m, k - 1) # filas i con 1 <= i <= m y 1 <= j = k - i <= n
if lo <= hi:
sust = anterior2[lo - 1:hi] + (A[lo - 1:hi] != Br[n - k + lo:n - k + hi + 1])
actual[lo:hi + 1] = np.minimum(np.minimum(sust, anterior[lo - 1:hi] + 1), anterior[lo:hi + 1] + 1)
anterior2, anterior = anterior, actual
return int(anterior[m])
rnd = random.Random(5)
for _ in range(200):
a = "".join(rnd.choice("ACGT") for _ in range(rnd.randint(0, 12)))
b = "".join(rnd.choice("ACGT") for _ in range(rnd.randint(0, 12)))
assert edicion_numpy(a, b) == edicion_python(a, b), (a, b)
print("la versión por antidiagonales coincide con el doble bucle en 200 pares")
for L in (200, 800):
a = "".join(rnd.choice("ACGT") for _ in range(L))
b = "".join(rnd.choice("ACGT") for _ in range(L))
t0 = time.perf_counter(); d1 = edicion_python(a, b); t1 = time.perf_counter(); d2 = edicion_numpy(a, b); t2 = time.perf_counter()
print(f"{L} x {L}: distancia {d1} = {d2} | Python {1000 * (t1 - t0):6.0f} ms | NumPy {1000 * (t2 - t1):5.0f} ms | aceleración x{(t1 - t0) / (t2 - t1):.1f}")
# ---------- mochila 0/1 con desplazamientos de arrays ----------
def mochila_python(valores, pesos, W):
dp = [0] * (W + 1)
for v, p in zip(valores, pesos):
for w in range(W, p - 1, -1):
dp[w] = max(dp[w], dp[w - p] + v)
return dp[W]
def mochila_numpy(valores, pesos, W):
dp = np.zeros(W + 1, dtype=np.int64)
for v, p in zip(valores, pesos):
if p <= W:
# el lado derecho se evalúa entero con el dp ANTERIOR, así que cada objeto se usa una sola vez
dp[p:] = np.maximum(dp[p:], dp[:W + 1 - p] + v)
return int(dp[W])
n, W = 150, 6000
v = [rnd.randint(10, 99) for _ in range(n)]
p = [rnd.randint(50, 999) for _ in range(n)]
t0 = time.perf_counter(); r1 = mochila_python(v, p, W); t1 = time.perf_counter(); r2 = mochila_numpy(v, p, W); t2 = time.perf_counter()
print(f"mochila n = {n}, W = {W}: {r1} = {r2} | Python {1000 * (t1 - t0):6.0f} ms | NumPy {1000 * (t2 - t1):5.1f} ms | aceleración x{(t1 - t0) / max(t2 - t1, 1e-6):.0f}")Two lessons. Vectorization requires understanding the dependency graph: antidiagonals are levels of a topological order whose same-level entries compute simultaneously. Speedup depends on size: for small tables NumPy call overhead dominates and gain is small (in one typical run, factor 1.6 with and about 7 with ); as diagonals lengthen speedup grows. In knapsack each item is one vector operation on elements, with over an order-of-magnitude gain (about 30 times in the reference run). Exact times depend on machine and browser: measure them. Reconstruction is less convenient: store pointers or full table, or use Hirschberg.
Common mistakes
Exercises
Step 1 of 5. Base cases: why is ?
Step 1 of 5. Why is where defined?
contar_particiones(s, diccionario): the number of distinct ways to split string s into a sequence of dictionary words (a list of nonempty strings) whose concatenation is s. The empty string has one partition (no words). For example, with dictionary ['cat', 'cats', 'and', 'sand', 'dog'], string 'catsanddog' has 2 partitions: cat sand dog and cats and dog. Tests include long strings where recursion without memory never finishes: use dynamic programming with one state per prefix.def contar_particiones(s, diccionario):
# número de formas de partir s en palabras del diccionario
passdp[0..W], the inner loop traverses w left to right ( to ) for each item of weight and value . What does it calculate?Summary
- Recipe. Subproblem (state must contain everything needed), recurrence (try all last-decision options), base cases, topological order and answer with reconstruction. Cost: number of subproblems times work per subproblem, on the DAG.
- Memoization and tabulation. The former is recurrence plus table (and overflows Python’s stack); the latter uses topological loops, permits discarding rows and vectorization. Store pointers or recompute to recover the solution.
- LIS. with “ends at ”; with smallest tails and binary search (patience sorting), optimal in the comparison model (Fredman’s lower bound). Pile count is LIS length, yielding Erdős–Szekeres.
- 0/1 knapsack. is pseudopolynomial: exponential in bit length. With one row traverse right to left; left to right gives unbounded knapsack.
- Edit distance. -cell table with three candidates; with impossible substitution it is LCS (), with scores Needleman–Wunsch;
diffis LCS over lines. No algorithm is known unless SETH fails. - Hirschberg. With forward and backward middle rows, the minimum of gives a point on an optimal path: recurse on two half-height subrectangles, with time (about twice table time) and linear memory.