A naive recursive function that aligns two 14-character telemetry strings makes about 1010 calls, while a dynamic programming (DP) table of 225 cells gives the same answer. The idea behind the table is Mental Move #15, Tabulate Overlapping Subproblems Once: whenever exponential recursion repeatedly revisits the same small set of states, collapsing that call tree into a Directed Acyclic Graph (DAG) turns or brute force into polynomial shortest- or longest-path relaxation. In this lecture, you will see how one algorithmic blueprint—topological relaxation on an implicit state DAG with backpointers—unifies discrete 0/1 sensor-payload allocation (dynamic_optimality.knapsack_01_dp), noisy Needleman–Wunsch sequence alignment & Levenshtein edit distance (dynamic_optimality.sequence_alignment_dp, edit_distance_dp), and Avidan & Shamir’s (2007) 2-D content-aware seam carving (dynamic_optimality.seam_carving_min_energy).
Learning objectives¶
Quantify why naive divide-and-conquer grows exponentially when subproblems overlap, and collapse exponential call trees into polynomial DAG state tables via memoization and bottom-up tabulation.
Formulate exact 0/1 integer-capacity resource allocation (
dynamic_optimality.knapsack_01_dp) and bracket its optimal value between greedy value-density heuristics and Dantzig’s fractional LP relaxation.Cast Needleman–Wunsch global sequence alignment (
dynamic_optimality.sequence_alignment_dp) and Wagner–Fischer edit distance (dynamic_optimality.edit_distance_dp) as longest/shortest paths on an edit DAG.Compute minimum-energy 8-connected vertical seams (
dynamic_optimality.seam_carving_min_energy) to resize 2-D scientific fields without distorting high-gradient features, and compress DP memory via rolling two-row buffers.
Time: about 60 min
try: # use the installed package, or the copy in this repository
import engthink
except ImportError:
import pathlib, subprocess, sys
for _root in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents]:
if (_root / "engthink" / "__init__.py").exists():
sys.path.insert(0, str(_root))
break
else: # on Google Colab: install from GitHub
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"git+https://github.com/ktwyw/engthink.git"], check=True)
import engthink
import inspect
import math
import numpy as np
import matplotlib.pyplot as plt
from engthink import (constants_benchmarks, divide_spatial, dynamic_optimality, emergence_verification,
greedy_heuristic_search, information_streams, invariants_complexity, reductions_constraints,
representation_scaling)
from engthink.plotting import label_panels, log_ticks, panel_label, use_style
use_style()
def show_source(obj):
"""Return the source code of a library function or class."""
return inspect.getsource(obj)
def heading(text):
print(f"\n{text}\n" + "=" * len(text))1. Overlapping Subproblems: Exponential Call Trees vs. Polynomial State DAGs¶
Divide-and-conquer works well when subproblems are disjoint (like MergeSort splitting an array into two non-overlapping halves). When subproblems overlap, naive recursion recomputes the same states a very large number of times.
Consider aligning two prefixes of lengths where each state branches into three predecessors: (deletion), (insertion), and (match/substitution). Without memoization, the total number of recursive invocations obeys:
Along the diagonal , grows faster than the central Delannoy numbers . Yet how many distinct argument pairs can ever exist in ? Exactly .
Every dynamic program requires just two structural ingredients:
Optimal Substructure: An optimal path to state extends an optimal path to one of its incoming DAG predecessors .
Overlapping Subproblems: Many exponentially numerous paths funnel through the same polynomial vertex set .
heading("Demonstration 1: Exponential call trees against polynomial DAG tabulation")
mm15 = [m for m in constants_benchmarks.MENTAL_MOVES_DB if m["id"] == 15][0]
print(f"Mental Move #{mm15['id']} ({mm15['name']}): {mm15['invariant']}")
def count_naive_alignment_calls(m: int, n: int) -> int:
"""Actual recursive tree walk for small (m, n) to verify Equation (1.1) directly."""
if m == 0 or n == 0:
return 1
return (
1
+ count_naive_alignment_calls(m - 1, n)
+ count_naive_alignment_calls(m, n - 1)
+ count_naive_alignment_calls(m - 1, n - 1)
)
# Compute exact call-tree size C(n, n) up to n = 14 via the recurrence, and verify against actual recursion for n <= 8:
n_max = 14
call_dp = np.ones((n_max + 1, n_max + 1), dtype=np.int64)
for i in range(1, n_max + 1):
for j in range(1, n_max + 1):
call_dp[i, j] = 1 + call_dp[i - 1, j] + call_dp[i, j - 1] + call_dp[i - 1, j - 1]
for n_chk in range(1, 9):
assert count_naive_alignment_calls(n_chk, n_chk) == int(call_dp[n_chk, n_chk])
n_vals = np.arange(1, n_max + 1)
naive_diag = np.array([call_dp[k, k] for k in n_vals], dtype=float)
dag_states = (n_vals + 1.0) ** 2
assert call_dp[14, 14] > 10_000_000_000 # about 1.19e10 calls at N = 14
assert int(dag_states[-1]) == 225 # vs. just 225 unique DAG cells
print(f"{'Length N':>8s} | {'Naive Tree Calls C(N,N)':>24s} | {'DAG States (N+1)^2':>19s} | {'Redundancy Ratio':>18s}")
print("-" * 78)
for k in [2, 4, 6, 8, 10, 12, 14]:
c_val = int(call_dp[k, k])
s_val = (k + 1) ** 2
print(f"{k:8d} | {c_val:24,d} | {s_val:19d} | {c_val / s_val:17.1f}x")
fig, ax = plt.subplots(figsize=(7.4, 4.1))
ax.semilogy(n_vals, naive_diag, marker="o", lw=2.3, color="#C0392B", label=r"Naive recursive tree calls $C(N, N) \sim 5.83^N$")
ax.semilogy(n_vals, dag_states, marker="s", lw=2.3, color="#2166AC", label=r"Memoized / tabulated DAG states $(N + 1)^2$")
ax.set_xlabel(r"Sequence length $N$")
ax.set_ylabel("Subproblem evaluations (log scale)")
ax.set_title("Recursive calls against distinct states")
ax.legend(fontsize=8.8)
plt.show()
Demonstration 1: Exponential call trees against polynomial DAG tabulation
=========================================================================
Mental Move #15 (Tabulate Overlapping Subproblems Once): Each state is solved once, in topological order of the DAG
Length N | Naive Tree Calls C(N,N) | DAG States (N+1)^2 | Redundancy Ratio
------------------------------------------------------------------------------
2 | 19 | 9 | 2.1x
4 | 481 | 25 | 19.2x
6 | 13,483 | 49 | 275.2x
8 | 398,593 | 81 | 4920.9x
10 | 12,146,179 | 121 | 100381.6x
12 | 377,393,953 | 169 | 2233100.3x
14 | 11,885,772,379 | 225 | 52825655.0x

Figure 6.1. Calls of the naive three-way alignment recursion, , against the number of distinct states that a table has to fill. At the ratio is .
What Demonstration 1 shows. At length , the naive three-way recursion makes calls, whereas tabulation fills cells, a ratio of , obtained only by never solving a state twice.
2. Discrete 0/1 Knapsack Allocation vs. Greedy & Fractional Relaxation¶
Suppose an autonomous underwater vehicle (AUV) has an integer payload mass budget [kg] and candidate scientific instruments with integer masses and information values . Each instrument is indivisible (): you cannot saw a mass spectrometer in half.
Let denote the maximum value achievable using a subset of the first instruments within capacity . Conditioning on whether instrument is excluded () or included () yields Bellman’s recurrence:
How does exact 0/1 DP compare against two fast approximations?
Greedy Value-Density Heuristic: Sort items by descending and pack whole items that fit. Fast (), but a single bulky high-ratio item can strand unused capacity (packing fragmentation).
Dantzig’s Fractional Relaxation (): Take highest items plus a fractional slice of the boundary item to fill completely. Because , this gives a provable LP upper bound:
heading("Demonstration 2: 0/1 payload knapsack DP against greedy density and fractional LP bound")
sensor_names = ["Multibeam", "CTD-Pro", "MassSpec", "ADCP", "MagArray", "Optode", "BioCam"]
weights_auv = np.array([6, 5, 5, 4, 3, 3, 2], dtype=int)
values_auv = np.array([33.0, 26.5, 26.0, 17.0, 13.5, 12.6, 8.0], dtype=float)
cap_auv = 10
def greedy_density_01(weights: np.ndarray, values: np.ndarray, capacity: int) -> tuple[float, list[int]]:
order = np.argsort(-(values / weights))
rem = int(capacity)
val = 0.0
picked = []
for idx in order:
if int(weights[idx]) <= rem:
rem -= int(weights[idx])
val += float(values[idx])
picked.append(int(idx))
return val, sorted(picked)
def fractional_knapsack_lp(weights: np.ndarray, values: np.ndarray, capacity: int) -> float:
order = np.argsort(-(values / weights))
rem = float(capacity)
val = 0.0
for idx in order:
if rem <= 0.0:
break
take_w = min(rem, float(weights[idx]))
val += take_w * float(values[idx] / weights[idx])
rem -= take_w
return val
def bruteforce_01_oracle(weights: np.ndarray, values: np.ndarray, capacity: int) -> float:
n = weights.size
best = 0.0
for mask in range(1 << n):
bits = np.array([(mask >> k) & 1 for k in range(n)], dtype=int)
if int(bits @ weights) <= capacity:
best = max(best, float(bits @ values))
return best
dp_sol = dynamic_optimality.knapsack_01_dp(weights_auv, values_auv, capacity=cap_auv)
v_grd, idx_grd = greedy_density_01(weights_auv, values_auv, cap_auv)
v_frc = fractional_knapsack_lp(weights_auv, values_auv, cap_auv)
v_bf = bruteforce_01_oracle(weights_auv, values_auv, cap_auv)
assert np.isclose(dp_sol["max_value"], v_bf, atol=1e-12)
assert dp_sol["max_value"] > v_grd + 2.0 # Greedy stranded by picking w=6 item first
assert v_grd <= dp_sol["max_value"] <= v_frc + 1e-12
# Sweep all capacities W = 1..28 and verify V_greedy <= V_01 == V_bruteforce <= V_fractional everywhere:
caps_sweep = np.arange(1, int(np.sum(weights_auv)) + 1)
v_grd_arr = np.array([greedy_density_01(weights_auv, values_auv, int(c))[0] for c in caps_sweep])
v_dp_arr = np.array([dynamic_optimality.knapsack_01_dp(weights_auv, values_auv, int(c))["max_value"] for c in caps_sweep])
v_bf_arr = np.array([bruteforce_01_oracle(weights_auv, values_auv, int(c)) for c in caps_sweep])
v_lp_arr = np.array([fractional_knapsack_lp(weights_auv, values_auv, int(c)) for c in caps_sweep])
assert np.allclose(v_dp_arr, v_bf_arr, atol=1e-12)
assert np.all(v_grd_arr <= v_dp_arr + 1e-12)
assert np.all(v_dp_arr <= v_lp_arr + 1e-12)
print(f"Capacity W = {cap_auv} kg:")
print(f" Greedy (by v/w) : {v_grd:5.1f} pts -> {[sensor_names[i] for i in idx_grd]} (mass = {sum(weights_auv[i] for i in idx_grd)} kg)")
print(f" Exact 0/1 DP : {dp_sol['max_value']:5.1f} pts -> {[sensor_names[i] for i in dp_sol['selected_indices']]} (mass = {dp_sol['total_weight']} kg)")
print(f" Fractional LP UB : {v_frc:5.1f} pts (integrality gap = {v_frc - dp_sol['max_value']:.2f} pts)")
fig, ax = plt.subplots(figsize=(7.5, 4.2))
ax.plot(caps_sweep, v_lp_arr, lw=2.0, ls="--", color="#2E8B57", label=r"Fractional LP upper bound $V_{\mathrm{frac}}(W)$")
ax.plot(caps_sweep, v_dp_arr, marker="o", ms=4.5, lw=2.2, color="#2166AC", label=r"Exact 0/1 knapsack DP $V_{0/1}^*(W)$")
ax.plot(caps_sweep, v_grd_arr, marker="x", ms=5.0, lw=1.6, ls=":", color="#C0392B", label=r"Greedy value-density $V_{\mathrm{greedy}}(W)$")
ax.axvline(cap_auv, color="gray", ls="-.", lw=1.2)
ax.set_xlabel(r"Payload mass budget $W$ [kg]")
ax.set_ylabel("Total scientific value [pts]")
ax.set_title("0/1 knapsack between the greedy value and the fractional bound")
ax.legend(fontsize=8.5)
plt.show()
Demonstration 2: 0/1 payload knapsack DP against greedy density and fractional LP bound
=======================================================================================
Capacity W = 10 kg:
Greedy (by v/w) : 46.5 pts -> ['Multibeam', 'MagArray'] (mass = 9 kg)
Exact 0/1 DP : 52.5 pts -> ['CTD-Pro', 'MassSpec'] (mass = 10 kg)
Fractional LP UB : 54.2 pts (integrality gap = 1.70 pts)

Figure 6.2. Value of the instrument payload against the mass budget for the seven instruments of Demonstration 2. The exact 0/1 dynamic program (solid) lies between the greedy density rule (dotted) and the fractional upper bound (dashed); at (vertical line) the values are 46.5, 52.5 and 54.2.
What Demonstration 2 shows. At , Multibeam (, density ) is taken first by the greedy heuristic. That leaves , of which MagArray (, ) fits, for with unused, whereas knapsack_01_dp pairs CTD-Pro and MassSpec () for the optimum, . The fractional bound is . Note also that knapsack_01_dp runs in pseudo-polynomial time: polynomial in the numeric capacity , which is fast whenever is moderate.
3. Sequence Alignment & Edit Distance as Optimal Paths on a 2-D Grid DAG¶
From noisy deep-space telemetry packets to CRISPR off-target DNA screening, comparing two variable-length strings and means finding the highest-scoring alignment (or fewest single-character edits) transforming into .
Needleman & Wunsch (1970) cast global alignment as a longest-path problem on an grid DAG with match reward , mismatch penalty , and linear gap penalty :
with boundary conditions and . Setting turns maximization into minimization of Wagner–Fischer / Levenshtein edit distance: .
heading("Demonstration 3: Needleman-Wunsch alignment and edit-distance traceback")
seq_tx = "SYNC_HDR_A47F_CRC"
seq_rx = "SYN_HDRA49F_GCRC"
aln = dynamic_optimality.sequence_alignment_dp(
seq_tx, seq_rx, match_score=2.0, mismatch_penalty=-1.0, gap_penalty=-2.0
)
ed_dist = dynamic_optimality.edit_distance_dp(seq_tx, seq_rx)
al_a, al_b = aln["aligned_a"], aln["aligned_b"]
assert len(al_a) == len(al_b)
assert al_a.replace("-", "") == seq_tx
assert al_b.replace("-", "") == seq_rx
# Verify score decomposition directly from aligned columns:
n_mat = sum(1 for x, y in zip(al_a, al_b) if x == y and x != "-")
n_gap = sum(1 for x, y in zip(al_a, al_b) if x == "-" or y == "-")
n_mis = len(al_a) - n_mat - n_gap
assert np.isclose(aln["score"], 2.0 * n_mat - 1.0 * n_mis - 2.0 * n_gap, atol=1e-12)
assert ed_dist == 4 # Delete 'C', delete '_', substitute '7'->'9', insert 'G'
match_bars = "".join("|" if x == y else (" " if "-" in (x, y) else ".") for x, y in zip(al_a, al_b))
print(f"Transmitted : {al_a}")
print(f" {match_bars}")
print(f"Received : {al_b}")
print(f"NW Score : {aln['score']:.1f} ({n_mat} matches, {n_mis} mismatches, {n_gap} gaps) | Levenshtein Edit Distance = {ed_dist}")
# Reconstruct (i, j) coordinates along the aligned strings to overlay optimal path on dp_matrix:
path_i, path_j = [0], [0]
ci, cj = 0, 0
for x, y in zip(al_a, al_b):
if x != "-":
ci += 1
if y != "-":
cj += 1
path_i.append(ci)
path_j.append(cj)
fig, ax = plt.subplots(figsize=(7.4, 4.5))
im = ax.imshow(aln["dp_matrix"], cmap="viridis", aspect="auto", origin="upper")
ax.plot(path_j, path_i, color="#F2C744", lw=2.5, marker="o", ms=4.5, label="Optimal traceback path")
ax.set_xticks(range(len(seq_rx) + 1))
ax.set_xticklabels(["∅"] + list(seq_rx), fontsize=8)
ax.set_yticks(range(len(seq_tx) + 1))
ax.set_yticklabels(["∅"] + list(seq_tx), fontsize=8)
ax.set_xlabel("Received packet prefix $j$")
ax.set_ylabel("Transmitted packet prefix $i$")
ax.set_title("Needleman-Wunsch table and optimal alignment path")
ax.grid(False)
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.14), ncol=2, fontsize=8.5)
fig.colorbar(im, ax=ax, label="Alignment score $F(i, j)$")
plt.show()
Demonstration 3: Needleman-Wunsch alignment and edit-distance traceback
=======================================================================
Transmitted : SYNC_HDR_A47F_-CRC
||| |||| ||.|| |||
Received : SYN-_HDR-A49F_GCRC
NW Score : 21.0 (14 matches, 1 mismatches, 3 gaps) | Levenshtein Edit Distance = 4

Figure 6.3. Needleman–Wunsch score table for the transmitted and received packet headers, with the optimal traceback path. Horizontal and vertical steps are gaps, diagonal steps matches or substitutions.
What Demonstration 3 shows. Without alignment, comparing seq_tx and seq_rx character-by-character at fixed index makes almost every character after index 3 look corrupted because a single dropped 'C' shifted the entire frame. Dynamic programming separates phase/timing slips (insertions & deletions, horizontal/vertical DAG edges) from symbol noise (substitutions, diagonal edges).
4. Content-Aware 2-D Seam Carving Around High-Gradient Scientific Features¶
Suppose you want to narrow an 2-D physical scalar field (such as vorticity, temperature, or astronomical intensity) without cropping away boundary structures or squishing localized peaks via uniform interpolation. Avidan & Shamir (ACM SIGGRAPH, 2007) defined an 8-connected vertical seam as one pixel per row obeying , minimizing cumulative gradient energy :
Look at Equation (4.1): it is shortest-path relaxation on a layered row-by-row DAG in strictly operations ( comparisons). We compute the minimum-energy seam for a field with three localized vortex peaks and then several further seams, each penalised where an earlier one ran.
heading("Demonstration 4: Avidan-Shamir seam carving around localized vortex cores")
ny_s, nx_s = 44, 68
yy_s, xx_s = np.meshgrid(np.linspace(0.0, 1.0, ny_s), np.linspace(0.0, 1.0, nx_s), indexing="ij")
field_vort = (
1.25 * np.exp(-((xx_s - 0.25) ** 2 + (yy_s - 0.36) ** 2) / 0.0085)
+ 1.40 * np.exp(-((xx_s - 0.72) ** 2 + (yy_s - 0.64) ** 2) / 0.0095)
+ 0.95 * np.exp(-((xx_s - 0.48) ** 2 + (yy_s - 0.80) ** 2) / 0.0065)
)
def gradient_energy_2d(img: np.ndarray) -> np.ndarray:
gx = np.zeros_like(img)
gy = np.zeros_like(img)
gx[:, 1:-1] = 0.5 * (img[:, 2:] - img[:, :-2])
gx[:, 0] = img[:, 1] - img[:, 0]
gx[:, -1] = img[:, -1] - img[:, -2]
gy[1:-1, :] = 0.5 * (img[2:, :] - img[:-2, :])
gy[0, :] = img[1, :] - img[0, :]
gy[-1, :] = img[-1, :] - img[-2, :]
return np.abs(gx) + np.abs(gy) + 1e-4
e_map0 = gradient_energy_2d(field_vort)
seam0 = dynamic_optimality.seam_carving_min_energy(e_map0)
cols0 = seam0["seam_cols"]
# Verify 8-connectivity |c[r] - c[r-1]| <= 1 and exact energy sum:
assert cols0.shape == (ny_s,)
assert np.all(np.abs(np.diff(cols0)) <= 1)
assert np.isclose(seam0["min_total_energy"], float(np.sum(e_map0[np.arange(ny_s), cols0])), atol=1e-12)
# Compare DP seam energy against average straight vertical column energy:
col_energies = np.sum(e_map0, axis=0)
min_straight_col = float(np.min(col_energies))
mean_col_energy = float(np.mean(col_energies))
assert seam0["min_total_energy"] <= min_straight_col + 1e-12
assert seam0["min_total_energy"] < 0.15 * mean_col_energy
# Find 8 distinct low-energy seams sequentially (by adding a soft repulsion along already-plotted seams for visualization):
e_vis = e_map0.copy()
seams_overlay = []
for _ in range(8):
s_res = dynamic_optimality.seam_carving_min_energy(e_vis)
seams_overlay.append(s_res["seam_cols"])
e_vis[np.arange(ny_s), s_res["seam_cols"]] += 5.0
print(f"Optimal 8-connected DP seam energy : {seam0['min_total_energy']:.4f}")
print(f"Best straight vertical column : {min_straight_col:.4f}")
print(f"Mean column gradient energy : {mean_col_energy:.4f} ({mean_col_energy / seam0['min_total_energy']:.1f}x higher than DP seam)")
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9.4, 4.0))
im1 = ax1.imshow(field_vort, cmap="magma", aspect="auto")
for k_idx, s_cols in enumerate(seams_overlay):
ax1.plot(s_cols, np.arange(ny_s), color="#19D3C5", lw=1.4 if k_idx > 0 else 2.4, alpha=0.85)
ax1.set_title("Field and eight least-energy seams")
ax1.set_xlabel("Column $c$")
ax1.set_ylabel("Row $r$")
ax1.grid(False)
fig.colorbar(im1, ax=ax1, fraction=0.046, pad=0.04)
im2 = ax2.imshow(seam0["cumulative_energy_map"], cmap="viridis", aspect="auto")
ax2.plot(cols0, np.arange(ny_s), color="#C0392B", lw=2.4, label="Optimal seam $c^*(r)$")
ax2.set_title(r"Cumulative DP table $M(r, c)$")
ax2.set_xlabel("Column $c$")
ax2.set_ylabel("Row $r$")
ax2.grid(False)
ax2.legend(loc="upper center", bbox_to_anchor=(0.5, -0.14), ncol=2, fontsize=8)
fig.colorbar(im2, ax=ax2, fraction=0.046, pad=0.04)
label_panels(fig)
plt.show()
Demonstration 4: Avidan-Shamir seam carving around localized vortex cores
=========================================================================
Optimal 8-connected DP seam energy : 0.0088
Best straight vertical column : 0.0088
Mean column gradient energy : 1.8162 (206.6x higher than DP seam)

Figure 6.4. Seam carving of a synthetic field with three vortex cores. (a) The field and eight successive minimum-energy seams, each penalised once used; most follow the calm columns at the edges. (b) The cumulative energy table of the first seam, which runs down the right-hand edge.
What Demonstration 4 shows.
The best seam has energy 0.0088, the same as the best straight column: calm columns near the edges of this field already avoid all three vortices, and the dynamic program finds one of them. The mean column energy is 207 times higher. Seams that must pass between the vortices appear in the figure once the calm columns are penalised.
Inside the algorithm¶
The three dynamic programs share one practical point:
When we need full path reconstruction (which items were packed, which characters aligned, which column was carved), we store the or table (or Hirschberg divide-and-conquer split points).
When we only need the optimal scalar cost (such as Levenshtein edit distance across two -base sequences, where a full float64 table would demand of RAM), row depends only on row . By swapping strings so and maintaining two rolling 1-D rows, memory collapses from to .
We inspect seam_carving_min_energy and knapsack_01_dp, then implement and verify space_compressed_edit_distance_2row from scratch.
Check against the library¶
heading("Inside the algorithm: Seam carving, 0/1 knapsack and 2-row space-compressed DP")
print(show_source(dynamic_optimality.seam_carving_min_energy))
print(show_source(dynamic_optimality.knapsack_01_dp))
def space_compressed_edit_distance_2row(a: str, b: str) -> int:
"""Compute exact Levenshtein edit distance in O(M*N) time and O(min(M, N)) auxiliary space."""
if len(b) > len(a):
a, b = b, a
m, n = len(a), len(b)
prev = np.arange(n + 1, dtype=int)
curr = np.zeros(n + 1, dtype=int)
for i in range(1, m + 1):
curr[0] = i
ca = a[i - 1]
for j in range(1, n + 1):
cost_sub = 0 if ca == b[j - 1] else 1
curr[j] = min(
prev[j] + 1, # deletion
curr[j - 1] + 1, # insertion
prev[j - 1] + cost_sub,
)
prev, curr = curr, prev
return int(prev[n])
test_pairs = [
("", ""),
("", "TELEMETRY"),
("KITTEN", "SITTING"),
("INTENTION", "EXECUTION"),
("GATTACA_CRISPR_PAM", "GATACA_CRSPR_PAMX"),
(seq_tx, seq_rx),
("A" * 45 + "BCDE", "A" * 42 + "BXDE"),
]
for sa, sb in test_pairs:
d_2row = space_compressed_edit_distance_2row(sa, sb)
d_ref = dynamic_optimality.edit_distance_dp(sa, sb)
assert d_2row == d_ref, f"Mismatch on ({sa!r}, {sb!r}): {d_2row} != {d_ref}"
full_cells = (len(test_pairs[-1][0]) + 1) * (len(test_pairs[-1][1]) + 1)
two_row_cells = 2 * (min(len(test_pairs[-1][0]), len(test_pairs[-1][1])) + 1)
print(f"Verified 2-row edit distance across {len(test_pairs)} benchmark pairs with 0 discrepancies")
print(f"Pair #7 memory footprint: full table = {full_cells} ints vs. 2-row buffer = {two_row_cells} ints ({full_cells / two_row_cells:.1f}x smaller)")
Inside the algorithm: Seam carving, 0/1 knapsack and 2-row space-compressed DP
==============================================================================
def seam_carving_min_energy(energy_map: np.ndarray) -> dict:
"""Find the minimum-energy 8-connected top-to-bottom vertical seam in a 2-D field via Avidan-Shamir DP."""
e_map = np.asarray(energy_map, dtype=float)
if e_map.ndim != 2 or e_map.shape[0] < 2 or e_map.shape[1] < 2 or np.any(e_map < 0.0):
raise ValueError("Require non-negative 2-D energy_map with shape >= (2, 2).")
h, w = e_map.shape
cum = np.zeros_like(e_map)
back = np.zeros((h, w), dtype=int)
cum[0, :] = e_map[0, :]
for r in range(1, h):
prev = cum[r - 1, :]
for c in range(w):
c_lo = max(0, c - 1)
c_hi = min(w - 1, c + 1)
best_prev_c = c_lo + int(np.argmin(prev[c_lo : c_hi + 1]))
back[r, c] = best_prev_c
cum[r, c] = e_map[r, c] + prev[best_prev_c]
seam = np.zeros(h, dtype=int)
seam[-1] = int(np.argmin(cum[-1, :]))
min_e = float(cum[-1, seam[-1]])
for r in range(h - 1, 0, -1):
seam[r - 1] = back[r, seam[r]]
return {"seam_cols": seam, "min_total_energy": min_e, "cumulative_energy_map": cum}
def knapsack_01_dp(weights: np.ndarray, values: np.ndarray, capacity: int) -> dict:
"""Solve exact 0/1 integer-capacity knapsack via dynamic programming with subset backpointer reconstruction."""
w = np.asarray(weights, dtype=int).ravel()
v = np.asarray(values, dtype=float).ravel()
cap = int(capacity)
if w.size != v.size or cap < 0 or np.any(w <= 0):
raise ValueError("Require matching positive integer weights, values, and capacity >= 0.")
n = w.size
dp = np.zeros((n + 1, cap + 1), dtype=float)
for i in range(1, n + 1):
wi = int(w[i - 1])
vi = float(v[i - 1])
dp[i, :] = dp[i - 1, :]
if wi <= cap:
cand = dp[i - 1, : cap + 1 - wi] + vi
dp[i, wi:] = np.maximum(dp[i, wi:], cand)
chosen: list[int] = []
rem = cap
for i in range(n, 0, -1):
if dp[i, rem] > dp[i - 1, rem] + 1e-12:
chosen.append(i - 1)
rem -= int(w[i - 1])
chosen.reverse()
return {
"max_value": float(dp[n, cap]),
"selected_indices": chosen,
"total_weight": int(sum(w[idx] for idx in chosen)),
"dp_states_evaluated": n * (cap + 1),
}
Verified 2-row edit distance across 7 benchmark pairs with 0 discrepancies
Pair #7 memory footprint: full table = 2350 ints vs. 2-row buffer = 94 ints (25.0x smaller)
Exercises¶
Worked solutions are in 06_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Verify across a 10-sequence noisy DNA/telemetry corpus that
dynamic_optimality.edit_distance_dpobeys the metric axioms (non-negativity, identity , symmetry , and the triangle inequality across all ordered triples—and confirm exact Needleman–Wunsch scaling .Find how it fails. Verify all
ValueErrorinput guards onknapsack_01_dpandseam_carving_min_energy, then demonstrate quantitatively (a) why sweeping capacity forward in 1-D Knapsack DP corrupts 0/1 uniqueness into Unbounded Knapsack item cloning, and (b) why greedy local top-to-bottom seam stepping gets trapped by downstream barriers that global DP easily routes around.Implement it yourself. Implement
remove_k_vertical_seams(image_2d, k_seams)using centered finite-difference gradient energy anddynamic_optimality.seam_carving_min_energyat each step. On a two-plume scalar field withk_seams = 16, verify exact output shape(36, 48), exact preservation of both plume maxima, and better preservation of high-intensity plume mass than right-side cropping.
heading("Self-check for the exercises")
assert int(call_dp[8, 8]) == count_naive_alignment_calls(8, 8)
assert np.allclose(v_dp_arr, v_bf_arr, atol=1e-12) and np.all(v_grd_arr <= v_dp_arr + 1e-12)
assert ed_dist == 4 and space_compressed_edit_distance_2row(seq_tx, seq_rx) == 4
assert seam0["min_total_energy"] < 0.15 * mean_col_energy
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.