Dynamic Programming Questions
Solving problems with overlapping subproblems and optimal substructure by memoization (top-down) and tabulation (bottom-up). Covers recognizing DP-amenable problems, defining state, transition and base cases, 1D and 2D sequence and grid formulations (knapsack and its variants, coin change, LIS, LCS, edit distance, sequence alignment, regular-expression and wildcard matching, counting-ways problems), interval DP (matrix chain, palindrome partitioning), space optimization with rolling arrays, solution reconstruction, longest paths in a DAG, game and expected-value DP, bitmask and tree DP, speeding up a DP (monotone queue, convex hull trick, divide-and-conquer optimization, bitsets, meet in the middle), and judging greedy versus DP. Ground covered elsewhere: probabilistic model inference, production caching and debugging practice, and general graph shortest-path algorithms.
You have a working top-down memoized solution, say for edit distance or LCS. Convert it step by step into a bottom-up solution: how do you decide the loop order, the base cases and the table dimensions?
Sample Answer
The idea
Top-down memoization means "write the recursion, and cache each answer the first time it is computed". Bottom-up tabulation means "fill a table in an order where every cell's inputs already exist". The conversion is mechanical, because the memoized function already contains everything the table needs: its arguments are the table's axes, its non-recursive returns are the base cases, and its recursive calls say which cells each cell reads. The loop order is any order in which every read cell is filled before the cell that reads it (a topological order of the dependencies: an ordering of the cells in which every cell comes after all the cells it reads).
Conversion, step by step (edit distance)
- State = the arguments that change. In go(i, j) the strings a and b are fixed, so the state is (i, j): the cost to turn a[:i] (the first i characters) into b[:j].
- Table dimensions = the range of each argument. i takes the values 0 to m and j takes 0 to n, so the table is (m+1) by (n+1). Using m by n loses the empty prefix.
- Base cases = the branches that return without recursing: i == 0 returns j and j == 0 returns i. These become the first row and the first column, assigned directly.
- Dependencies = the recursive calls: (i-1, j-1), (i-1, j) and (i, j-1). Every one has a smaller i or a smaller j (or both), so a cell is safe to compute after its upper, left and upper-left neighbours.
- Loop order = any order that respects those dependencies. Ascending i with ascending j does. So does going down anti-diagonals: an anti-diagonal is the set of cells with the same i + j, a line running from bottom-left to top-right, and every cell on it reads only cells on earlier diagonals (the 3 x 3 grids in the output number the cells in each order). Descending i does not.
- Rewrite: each go(x, y) in the recurrence becomes table[x][y], each return becomes an assignment, and the answer is table[m][n].
- Check it: compare against the memoized version on random inputs, and check the loop order against the recorded dependencies. The shipped violations function does this: it records the position of every cell in the proposed order, then counts each (cell, cell it reads) pair where the cell it reads comes later. A count of 0 means the order is safe.
The direction depends on how the state is defined. If the state were suffixes (i is the index where the remaining text starts), the calls would read larger i and j and the loops would run downwards. Read the calls, do not memorise a direction.
Code
import random
import sys
from functools import lru_cache
def top_down(a, b):
"""Memoized edit distance. Returns (answer, cache stats, dependencies of every visited cell)."""
deps = {}
@lru_cache(maxsize=None)
def go(i, j): # cost to turn a[:i] into b[:j]
if i == 0:
deps[(i, j)] = []
return j
if j == 0:
deps[(i, j)] = []
return i
if a[i - 1] == b[j - 1]:
deps[(i, j)] = [(i - 1, j - 1)]
return go(i - 1, j - 1)
deps[(i, j)] = [(i - 1, j - 1), (i - 1, j), (i, j - 1)]
return 1 + min(go(i - 1, j - 1), go(i - 1, j), go(i, j - 1))
answer = go(len(a), len(b))
return answer, go.cache_info(), deps
def bottom_up(a, b):
"""Same recurrence, same answer. Returns (table, the order in which cells are filled)."""
m, n = len(a), len(b)
table = [[0] * (n + 1) for _ in range(m + 1)] # i runs 0..m and j runs 0..n, so (m+1) x (n+1)
order = []
for i in range(m + 1):
for j in range(n + 1):
order.append((i, j))
if i == 0:
table[i][j] = j # the memoized function's first return
elif j == 0:
table[i][j] = i # its second return
elif a[i - 1] == b[j - 1]:
table[i][j] = table[i - 1][j - 1]
else:
table[i][j] = 1 + min(table[i - 1][j - 1], table[i - 1][j], table[i][j - 1])
return table, order
def violations(order, deps):
"""How many (cell, dependency) pairs have the dependency filled AFTER the cell."""
when = {cell: k for k, cell in enumerate(order)}
return sum(1 for cell, ds in deps.items() for d in ds if when[d] > when[cell])
def plain(a, b, i, j):
if i == 0:
return j
if j == 0:
return i
if a[i - 1] == b[j - 1]:
return plain(a, b, i - 1, j - 1)
return 1 + min(plain(a, b, i - 1, j - 1), plain(a, b, i - 1, j), plain(a, b, i, j - 1))
a, b = "horse", "ros"
answer, info, deps = top_down(a, b)
table, order = bottom_up(a, b)
print(f"top-down {a!r} -> {b!r}: answer {answer}, distinct cells computed {info.misses}, cache hits {info.hits}, "
f"total calls {info.misses + info.hits}, table cells {(len(a) + 1) * (len(b) + 1)}")
print("bottom-up table (rows i = chars of a used, columns j = chars of b used):")
print(" " + " ".join(["'"] + list(b)))
for i, row in enumerate(table):
print(f"{(a[i - 1] if i else '-'):>2} {i} " + " ".join(str(v) for v in row))
print("bottom-up answer:", table[-1][-1])
print("\nfill order check: a cell must never be filled before a cell it reads")
print("rows ascending, columns ascending:", violations(order, deps), "violations")
descending_rows = [(i, j) for i in range(len(a), -1, -1) for j in range(len(b) + 1)]
print("rows descending, columns ascending:", violations(descending_rows, deps), "violations")
diagonals = sorted(order, key=lambda c: (c[0] + c[1], c[0]))
print("anti-diagonals (i + j ascending):", violations(diagonals, deps), "violations")
print("\nrecursion depth: the default limit is", sys.getrecursionlimit())
long_a, long_b = "a" * 1200, "b" * 1200
try:
top_down(long_a, long_b)
print("top-down on two 1200-char strings: finished")
except RecursionError:
print("top-down on two 1200-char strings: RecursionError")
print("bottom-up on the same strings:", bottom_up(long_a, long_b)[0][-1][-1])
print("\nstep number in which each cell of a 3 x 3 table is filled, for two orders")
grid_order = [(i, j) for i in range(3) for j in range(3)]
for name, cells in (("rows then columns", grid_order),
("anti-diagonals", sorted(grid_order, key=lambda c: (c[0] + c[1], c[0])))):
step = {cell: k for k, cell in enumerate(cells, 1)}
print(name + ":")
for i in range(3):
print(" " + " ".join(str(step[(i, j)]) for j in range(3)))
print("cells read by cell (1, 1) (h vs r differ):", deps[(1, 1)], "| by cell (2, 2) (o vs o match):", deps[(2, 2)])
rng = random.Random(45)
for _ in range(400):
x = "".join(rng.choice("ab") for _ in range(rng.randint(0, 6)))
y = "".join(rng.choice("ab") for _ in range(rng.randint(0, 6)))
td = top_down(x, y)[0]
bu = bottom_up(x, y)[0][-1][-1]
assert td == bu == plain(x, y, len(x), len(y)), (x, y)
print("checked 400 seeded random pairs (lengths 0 to 6 over 'ab', empty strings included): top-down, bottom-up and plain recursion agree")
Output and trace
top-down 'horse' -> 'ros': answer 3, distinct cells computed 18, cache hits 10, total calls 28, table cells 24
bottom-up table (rows i = chars of a used, columns j = chars of b used):
' r o s
- 0 0 1 2 3
h 1 1 1 2 3
o 2 2 2 1 2
r 3 3 2 2 2
s 4 4 3 3 2
e 5 5 4 4 3
bottom-up answer: 3
fill order check: a cell must never be filled before a cell it reads
rows ascending, columns ascending: 0 violations
rows descending, columns ascending: 19 violations
anti-diagonals (i + j ascending): 0 violations
recursion depth: the default limit is 1000
top-down on two 1200-char strings: RecursionError
bottom-up on the same strings: 1200
step number in which each cell of a 3 x 3 table is filled, for two orders
rows then columns:
1 2 3
4 5 6
7 8 9
anti-diagonals:
1 2 4
3 5 7
6 8 9
cells read by cell (1, 1) (h vs r differ): [(0, 0), (0, 1), (1, 0)] | by cell (2, 2) (o vs o match): [(1, 1)]
checked 400 seeded random pairs (lengths 0 to 6 over 'ab', empty strings included): top-down, bottom-up and plain recursion agree
The decorator lru_cache(maxsize=None) is Python's built-in memo: it stores each result keyed by the arguments, and cache_info() reports misses (calls that had to compute a new value) and hits (calls answered from the stored value). The top-down run on "horse" and "ros" makes 28 calls in total: 18 misses (each distinct cell computed once) plus 10 hits, while the table has 24 cells. Top-down only touches cells that are reachable from the top; bottom-up fills all of them. The order check records the dependencies of the memoized run and counts reads of cells that are filled later: ascending rows give 0 violations, descending rows give 19 (pairs, not cells), and the diagonal order gives 0. The last line before the check shows what the recorded dependencies look like: cell (1, 1) compares "h" with "r", which differ, so it reads its three neighbours; cell (2, 2) compares "o" with "o", which match, so it reads only the diagonal one. For the answer, the corner cell holds 3 (replace h with r, delete r, delete e).
Trade-offs
- Time: O(m * n) either way. Space: O(m * n) for the table. Top-down additionally uses stack depth up to about m + n.
- Recursion depth: with Python's default limit of 1000 (printed above), the top-down version raised RecursionError on two 1200-character strings, while the bottom-up version returned 1200. Raising the limit works up to a point, but the table needs no recursion at all.
- Tabulation allows rolling arrays (keeping only the last row or two instead of the whole table): because a row reads only itself and the row above, two rows (or one row plus a saved diagonal) are enough when you do not need to rebuild the alignment. Interviews typically ask for the conversion and the row-by-row loops; anti-diagonal order and rolling arrays are deeper material that comes up when the interviewer pushes on space or on parallel evaluation.
- Memoization is easier to write when the reachable states are a sparse subset or the order is awkward.
- At the smallest sizes: for m = n = 0 the table is a single cell holding 0.
Edge cases and common mistakes
- Looping range(m) instead of range(m + 1), which drops the last row or column.
- Filling the base row and column after the main loop, so interior cells read zeros.
- A loop direction that does not match the dependencies, as the descending-rows check shows.
- Forgetting that the memoized function took i and j as lengths, so the characters inside the loop are a[i - 1] and b[j - 1].
- Not returning the corner cell, or returning table[m - 1][n - 1].
The shipped check runs top-down, bottom-up and plain recursion on 400 seeded random pairs (lengths 0 to 6 over "a" and "b", empty strings included) and they agree. The same conversion works for longest common subsequence: the state is (i, j) again, the base cases are the zero row and column, and the same ascending loops apply.
Running the code
Save the code as memo_to_table.py and run python memo_to_table.py with Python 3.12 (standard library only; the 1200-character case relies on the default recursion limit of 1000). It finishes in a few seconds and is deterministic (seed 45).
In a tree whose node weights can be negative, find the maximum sum of weights along any path between two nodes (the path may be a single node). Describe what each node returns to its parent versus what it records as the global best, and give the complexity.
Sample Answer
The idea
Each node carries a number, its weight (it may be negative). A path here is any chain of connected nodes that never revisits a node, and its sum is the total of the weights on it. Its highest node (the one closest to the root) is the one place where it may bend, meaning turn from going up to going down: at that node it can use the left branch, the right branch, both, or neither. So the best path whose highest node is v is v's weight plus the best downward branch on each side, and the answer is the maximum of that quantity over all nodes v. The trap is that only one of the two branches can be extended upward past v, because a path that continues to v's parent can only arrive through one child. That is why each node reports one number to its parent and records a different number globally.
What each node returns versus records
For a node v with weight w:
- Meaning of the state:
down(v)is the largest sum of a path that starts at v and only goes downward (it always contains v). It is what v returns to its parent. - Transition:
left = max(0, down(v.left))andright = max(0, down(v.right)), thendown(v) = w + max(left, right). Themax(0, ...)drops a branch whose best sum is negative, because skipping a branch is allowed and is then at least as good. This is correct because any downward path from v is v followed by a downward path in exactly one child, or by nothing. - What v records globally:
through(v) = w + left + right, the best path that bends at v. The global best is the maximum ofthroughover all nodes. The parent cannot use this number: a path cannot go down one child, up through v and down the other child while also continuing to v's parent. - Base case: a missing child contributes 0, and the global best starts at negative infinity, not 0. A tree whose weights are all negative must answer with its largest single weight, so the empty path must not count.
- Fill order and answer: post-order (visit the left child, then the right child, then the node itself, because
down(v)needs both children's values). The answer is the global best after the root has been processed.
The brute force that follows the definition recomputes the two downward sums from scratch at every node, which re-walks everything below each node. An even blunter one tries every pair of nodes and sums the path between them. The second is the reference the random check below uses; the first is counted in the output.
Code
The driver prints the per-node trace, the call counts of the naive and one-pass versions on chains of 0 to 6 nodes (the root call and the calls on missing children are both counted), the edge cases, a comparison against the all-pairs reference on random trees, and what happens on a very deep chain.
import random
import sys
from collections import deque
class Node:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def build(level_order):
"""Build a tree from a level-order list; None marks a missing child."""
if not level_order or level_order[0] is None:
return None
root = Node(level_order[0])
queue, i = deque([root]), 1
while queue and i < len(level_order):
node = queue.popleft()
if i < len(level_order) and level_order[i] is not None:
node.left = Node(level_order[i])
queue.append(node.left)
i += 1
if i < len(level_order) and level_order[i] is not None:
node.right = Node(level_order[i])
queue.append(node.right)
i += 1
return root
def max_path_sum(root, trace=None):
"""Return (best path sum, number of calls). Empty tree -> (None, 1)."""
best = float("-inf")
calls = 0
def down(node):
# down(node) = best sum of a path that starts at node and only goes downward
nonlocal best, calls
calls += 1
if node is None:
return 0
left = max(0, down(node.left)) # a negative branch is never worth extending into
right = max(0, down(node.right))
through = node.val + left + right # path that bends at this node: recorded globally
best = max(best, through)
up = node.val + max(left, right) # path that continues to the parent: one side only
if trace is not None:
trace.append((node.val, left, right, through, up, best))
return up
down(root)
return (None if root is None else best), calls
def max_path_sum_naive(root):
"""Same answer, but every node recomputes its two downward sums from scratch."""
calls = 0
def down(node):
nonlocal calls
calls += 1
if node is None:
return 0
return node.val + max(0, down(node.left), down(node.right))
best = float("-inf")
stack = [root] if root else []
while stack:
node = stack.pop()
through = node.val + max(0, down(node.left)) + max(0, down(node.right))
best = max(best, through)
stack += [c for c in (node.left, node.right) if c]
return (None if root is None else best), calls
def max_path_sum_iterative(root, events=None):
"""Post-order with an explicit stack: no Python recursion limit.
Each node is pushed twice: first with seen=False (go and handle the children),
then with seen=True, which pops only after both children are finished."""
if root is None:
return None
best, up = float("-inf"), {}
stack = [(root, False)]
while stack:
node, seen = stack.pop()
if not seen:
stack.append((node, True))
stack += [(c, False) for c in (node.left, node.right) if c]
if events is not None:
events.append(f"pop {node.val} first time: push it again as 'seen', then its children")
continue
left = max(0, up[node.left]) if node.left else 0
right = max(0, up[node.right]) if node.right else 0
best = max(best, node.val + left + right)
up[node] = node.val + max(left, right)
if events is not None:
events.append(f"pop {node.val} second time: left={left} right={right} "
f"through={node.val + left + right} up={up[node]} best={best}")
return best
def max_path_sum_wrong_zero(root):
"""Common bug: best starts at 0, so an all-negative tree 'finds' an empty path."""
best = 0
def down(node):
nonlocal best
if node is None:
return 0
left, right = max(0, down(node.left)), max(0, down(node.right))
best = max(best, node.val + left + right)
return node.val + max(left, right)
down(root)
return best
def all_pairs_reference(root):
"""Brute force: try every pair of nodes, sum the nodes on the path between them."""
parent, depth, nodes = {root: None}, {root: 0}, []
stack = [root]
while stack:
node = stack.pop()
nodes.append(node)
for child in (node.left, node.right):
if child:
parent[child], depth[child] = node, depth[node] + 1
stack.append(child)
best = float("-inf")
for u in nodes:
for v in nodes:
a, b, total = u, v, 0
while a is not b: # climb the deeper one until they meet
if depth[a] >= depth[b]:
total += a.val
a = parent[a]
else:
total += b.val
b = parent[b]
best = max(best, total + a.val) # a is the lowest common ancestor
return best
# 1. Worked trace
tree = build([-10, 9, 20, None, None, 15, 7])
trace = []
print("answer, calls:", max_path_sum(tree, trace))
print("val left right through up best")
for row in trace:
print("%3d %5d %5d %7d %4d %6d" % row)
def count_nodes(node):
return 0 if node is None else 1 + count_nodes(node.left) + count_nodes(node.right)
def count_missing(node):
if node is None:
return 1
return count_missing(node.left) + count_missing(node.right)
real, gaps = count_nodes(tree), count_missing(tree)
print(f"calls on the example tree: {real} real nodes + {gaps} calls on missing children = {real + gaps}")
small = build([2, -1, 3])
events = []
print("iterative post-order on [2, -1, 3]:", max_path_sum_iterative(small, events))
print("\n".join(" " + e for e in events))
# 2. Calls on skewed trees: root counted, missing children counted
print("n naive_calls one_pass_calls")
for n in range(0, 7):
chain = None
for _ in range(n):
chain = Node(1, chain, None)
print(n, max_path_sum_naive(chain)[1], max_path_sum(chain)[1])
# 3. Edge cases
for name, t in [("single negative", build([-3])), ("two negatives", build([-2, -1])),
("empty", None), ("bend beats chain", build([2, -1, 3]))]:
print(name, "->", max_path_sum(t)[0])
print("all-negative with best=0 bug:", max_path_sum_wrong_zero(build([-3])), "(correct: -3)")
# 4. Random trees against the all-pairs reference
random.seed(11)
distinct = set()
for _ in range(400):
size = random.randint(1, 12)
values = [random.randint(-9, 9) if random.random() < 0.85 else None for _ in range(size)]
values[0] = random.randint(-9, 9)
t = build(values)
want = all_pairs_reference(t)
assert max_path_sum(t)[0] == max_path_sum_naive(t)[0] == max_path_sum_iterative(t) == want
distinct.add(tuple(values))
print("random trees checked:", len(distinct), "distinct level-order lists")
# 5. Deep trees: recursion limit versus the explicit stack
depth = 3000
chain = None
for _ in range(depth):
chain = Node(1, chain, None)
print("recursion limit:", sys.getrecursionlimit())
try:
max_path_sum(chain)
except RecursionError:
print("recursive version on a chain of", depth, "-> RecursionError")
print("iterative version on the same chain:", max_path_sum_iterative(chain))
Output:
answer, calls: (42, 11)
val left right through up best
9 0 0 9 9 9
15 0 0 15 15 15
7 0 0 7 7 15
20 15 7 42 35 42
-10 9 35 34 25 42
calls on the example tree: 5 real nodes + 6 calls on missing children = 11
iterative post-order on [2, -1, 3]: 5
pop 2 first time: push it again as 'seen', then its children
pop 3 first time: push it again as 'seen', then its children
pop 3 second time: left=0 right=0 through=3 up=3 best=3
pop -1 first time: push it again as 'seen', then its children
pop -1 second time: left=0 right=0 through=-1 up=-1 best=3
pop 2 second time: left=0 right=3 through=5 up=5 best=5
n naive_calls one_pass_calls
0 0 1
1 2 3
2 6 5
3 12 7
4 20 9
5 30 11
6 42 13
single negative -> -3
two negatives -> -1
empty -> None
bend beats chain -> 5
all-negative with best=0 bug: 0 (correct: -3)
random trees checked: 388 distinct level-order lists
recursion limit: 1000
recursive version on a chain of 3000 -> RecursionError
iterative version on the same chain: 3000
Reading the output
The trace columns are: val the node's weight; left and right the clipped downward sums from its children (0 when a child is missing or negative); through = val + left + right, the best path bending at this node; up = val + the larger of left and right, what the node returns to its parent; best the running global maximum after this node. The trace lists nodes in the order they finish (post-order). Node 20 has children 15 and 7, so it records through = 20 + 15 + 7 = 42, the best path overall, but returns only 20 + max(15, 7) = 35 to the root. The root -10 can bend over 9 and 35 for 34, which is less than 42, so the global best stays 42.
The tree is [-10, 9, 20, None, None, 15, 7] in level order, so only 5 nodes exist: -10 at the root, 9 and 20 below it, and 15 and 7 below 20. Each real node makes one call, and the code also calls down on every missing child: 9 has two, 15 has two and 7 has two, 6 in all. The run prints 5 + 6 = 11, which is the 11 in answer, calls.
On a chain of n nodes the one-pass version makes 2n + 1 calls (1, 3, 5, 7, ... in the table), one per node plus one per missing child. The naive version makes n(n + 1) calls on a chain (0, 2, 6, 12, 20, ...), which is quadratic.
The two-node case [-2, -1] answers -1 and the single node answers -3, which is why best starts at negative infinity. The best = 0 variant printed in the output returns 0 for the single node -3, a path with no nodes at all.
How the code is organised
max_path_sum defines the helper down inside it so that down can read and update two counters that belong to the outer function. Python needs the nonlocal best, calls line for that: without it, the assignments calls += 1 and best = max(best, through) make those names local to down, and the first one to run raises UnboundLocalError because the name is read before it has a value. The trace list is an optional argument that, when given, collects one row per node as it finishes, which is what the printed table shows.
The iterative version replaces the call stack with a list of (node, seen) pairs. Each node is pushed twice. The first pop (seen is False) pushes the node back as seen=True and then pushes its children on top of it, so the children are processed first. The second pop (seen is True) happens only after both children are finished, so their up values are ready. On [2, -1, 3] the run prints that sequence: node 2 first time, node 3 first time and second time, node -1 first and second time, and finally node 2 second time with left=0 right=3, giving through=5.
The all-pairs reference tries every pair (u, v) and sums the nodes on the path between them. It finds that path by climbing: whichever of the two nodes is deeper steps up to its parent, adding its weight, until both are the same node. That meeting node is their lowest common ancestor (the deepest node that has both u and v below it, possibly u or v itself), and its weight is added once at the end. This is slow (about n^2 pairs times a climb) but obviously correct, which is why it checks the fast code.
Complexity
Time: n states, constant work each (two max calls and an addition), so O(n). Space: the recursion depth is the tree height h (the number of nodes on the longest root-to-leaf chain), so O(h). A balanced tree is one where the two sides of every node have nearly equal height, so h is about log2(n); on a chain every node has one child, so h = n. CPython's default recursion limit is 1000 frames, and the output shows the recursive version raising RecursionError on a 3000-node chain. The iterative post-order version has no such limit; it keeps an explicit stack and a dictionary with one entry per node, so it uses O(n) memory.
Common mistakes
- Returning
through(v)to the parent. That lets a parent extend a path that has already bent, which builds a branching shape (a node with three neighbours on the chain) that is not a path, and it can overestimate the answer. - Not clipping negative branches with
max(0, ...), which forces a harmful subtree into the sum. - Starting the global best at 0 (shown above), which returns 0 for an all-negative tree. Starting it at
-1fails the same way whenever the true answer is below -1, as for the single node -3. - Forgetting that a path may be a single node, so a lone node is treated as invalid.
Running the code
Save the listing as tree_path.py (standard library only) and run:
docker run --rm -v "$PWD":/w -w /w python:3.12 python tree_path.py
Return an actual longest common subsequence of two strings, not just its length. Fill the table, walk back through it to build the string, and say what you do when several answers tie.
Sample Answer
The idea
The length table already contains the decisions that produced every cell. To get the string, start at the bottom-right cell and walk back to the top-left, asking at each cell "how was this value produced?". A match means the character is part of the answer and you step diagonally. A non-match means the value was copied from the cell above or the cell to the left (whichever holds the larger value), so you step there and add nothing. Collect the matched characters on the way and reverse them at the end, because you meet them last-to-first.
The five things to state
- What one cell means.
dp[i][j]is the LCS length of the first i characters ofaand the first j characters ofb. - The transition. Equal last characters give
dp[i-1][j-1] + 1; otherwisemax(dp[i-1][j], dp[i][j-1]). - Base cases. Row 0 and column 0 are all 0 (an empty prefix matches nothing).
- Fill order. Row by row, left to right, so the three neighbours a cell reads are already filled.
- Where the answer is. The length is
dp[n][m]; the string is read by the walk back from that cell, which reads the cells in the reverse of the fill order.
Walking back
At cell (i, j) with i, j > 0:
- If
a[i-1] == b[j-1]: record that character and move to (i-1, j-1). Taking the match is safe because the cell's value came from the diagonal plus one. - Otherwise compare
dp[i-1][j](up) anddp[i][j-1](left). Move toward the larger one; that neighbour holds the same value as the current cell, so no length is lost. - Stop when i or j reaches 0.
The run below prints the table for ABCBDAB and BDCABA and the real path the code takes, one line per step.
When several answers tie
Often more than one string achieves the maximum length. For this input there are three: BCAB, BCBA and BDAB. The tie shows up in the walk as a cell where up == left (the first line of the trace, cell (7,6)). Both moves are valid and lead to different, equally long strings: sending ties up gives BCBA, sending ties left gives BDAB. So the right behaviour is to pick a fixed rule so the output is deterministic, and to say so. If the problem asks for a specific one, such as the lexicographically smallest (dictionary order), a walk back on the prefix table does not give it directly, because it builds the string from the end and cannot see which later characters will be chosen. Lexicographically smallest means the first in dictionary order: compare first characters, and on a tie compare the second, and so on, so BCAB comes before BDAB because C is before D at the second position.
A typical interview asks for the table, the walk back and a stated tie rule. The lexicographically smallest string, Hirschberg's method and the substring variant below are follow-ups and deeper material.
To build the smallest one, fill a second table over suffixes (suf[i][j] is the LCS of a[i:] and b[j:]) and build forward, one character at a time, in three moves:
- Say you still need
rcharacters (r = suf[i][j]). - Try the candidate characters in alphabetical order. For a candidate
c, find its first occurrence ina[i:]and inb[j:](the earliest match leaves the most room behind it). - Accept
cif the two strings after those occurrences still contain an LCS of lengthr - 1; otherwiseccannot start any longest answer from here, so try the next letter.
That is lcs_lex_smallest, and the run prints every step for ABCBDAB and BDCABA: with 4 characters needed, A is skipped because only 2 would remain after it, B is taken (3 remain, as required); with 3 needed, A and B are skipped, C is taken; then A, then B, giving BCAB. It equals the minimum of the brute-force set on all 300 random pairs.
The code
import random
from itertools import combinations
def build_table(a, b):
"""dp[i][j] = LCS length of a[:i] and b[:j]."""
dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
if a[i - 1] == b[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp
def walk_back(a, b, dp, prefer_up=True, trace=None):
"""Rebuild one LCS from the bottom-right cell. Ties go up or left by rule."""
i, j, picked = len(a), len(b), []
while i > 0 and j > 0:
if a[i - 1] == b[j - 1]:
if trace is not None:
trace.append(f"({i},{j}) match {a[i - 1]!r}, go diagonal")
picked.append(a[i - 1])
i, j = i - 1, j - 1
else:
up, left = dp[i - 1][j], dp[i][j - 1]
go_up = up > left or (up == left and prefer_up)
if trace is not None:
tie = " (tie)" if up == left else ""
trace.append(f"({i},{j}) up={up} left={left}{tie}, go {'up' if go_up else 'left'}")
if go_up:
i -= 1
else:
j -= 1
return "".join(reversed(picked))
def lcs_lex_smallest(a, b, trace=False):
"""Smallest LCS in dictionary order, using a table over suffixes."""
n, m = len(a), len(b)
suf = [[0] * (m + 1) for _ in range(n + 1)] # suf[i][j] = LCS of a[i:], b[j:]
for i in range(n - 1, -1, -1):
for j in range(m - 1, -1, -1):
if a[i] == b[j]:
suf[i][j] = suf[i + 1][j + 1] + 1
else:
suf[i][j] = max(suf[i + 1][j], suf[i][j + 1])
i = j = 0
out = []
while suf[i][j] > 0:
for c in sorted(set(a[i:]) & set(b[j:])):
i2, j2 = a.index(c, i), b.index(c, j) # earliest match leaves most room
ok = suf[i2 + 1][j2 + 1] == suf[i][j] - 1
if trace:
print(f" need {suf[i][j]} more; try {c!r}: earliest at a[{i2}], b[{j2}], "
f"{suf[i2 + 1][j2 + 1]} left after it -> {'take' if ok else 'skip'}")
if ok:
out.append(c)
i, j = i2 + 1, j2 + 1
break
return "".join(out)
cells = 0
def last_row(a, b):
"""LCS(a, b[:j]) for every j, using two rows."""
global cells
prev = [0] * (len(b) + 1)
for ch in a:
cur = [0] * (len(b) + 1)
for j in range(1, len(b) + 1):
cells += 1
cur[j] = prev[j - 1] + 1 if ch == b[j - 1] else max(prev[j], cur[j - 1])
prev = cur
return prev
def hirschberg(a, b):
"""Actual LCS with only rows of length len(b)+1 alive at a time."""
if not a or not b:
return ""
if len(a) == 1:
return a if a in b else ""
mid = len(a) // 2
left = last_row(a[:mid], b)
right = last_row(a[mid:][::-1], b[::-1])
k = max(range(len(b) + 1), key=lambda k: left[k] + right[len(b) - k])
return hirschberg(a[:mid], b[:k]) + hirschberg(a[mid:], b[k:])
def longest_common_substring(a, b):
"""Contiguous version: a mismatch resets the cell to 0."""
best, end = 0, 0
prev = [0] * (len(b) + 1)
for i in range(1, len(a) + 1):
cur = [0] * (len(b) + 1)
for j in range(1, len(b) + 1):
if a[i - 1] == b[j - 1]:
cur[j] = prev[j - 1] + 1
if cur[j] > best:
best, end = cur[j], i
prev = cur
return a[end - best:end]
def all_lcs(a, b):
"""Reference: every longest common subsequence, by trying all subsequences of a."""
def is_subseq(s, t):
it = iter(t)
return all(ch in it for ch in s)
found, best = set(), 0
for k in range(len(a) + 1):
for idx in combinations(range(len(a)), k):
s = "".join(a[i] for i in idx)
if is_subseq(s, b):
if k > best:
best, found = k, set()
if k == best:
found.add(s)
return found
a, b = "ABCBDAB", "BDCABA"
dp = build_table(a, b)
print(" " + " ".join(["-"] + list(b)))
for i, row in enumerate(dp):
print(f"{'-' if i == 0 else a[i - 1]} " + " ".join(str(v) for v in row))
print("length:", dp[-1][-1])
trace = []
print("\nwalk back, ties go up:", walk_back(a, b, dp, True, trace))
print("\n".join(" " + line for line in trace))
print("walk back, ties go left:", walk_back(a, b, dp, False))
print("all LCS strings:", sorted(all_lcs(a, b)))
print("lexicographically smallest, step by step:")
print("lexicographically smallest:", lcs_lex_smallest(a, b, trace=True))
mid = len(a) // 2
left_row = last_row(a[:mid], b)
right_row = last_row(a[mid:][::-1], b[::-1])
sums = [left_row[k] + right_row[len(b) - k] for k in range(len(b) + 1)]
print("Hirschberg split of", a[:mid], "|", a[mid:], "against", b)
print(" left row (LCS of", a[:mid], "with b[:k]):", left_row)
print(" right row (LCS of", a[mid:], "with b[k:]):", [right_row[len(b) - k] for k in range(len(b) + 1)])
print(" sums:", sums, " best k:", sums.index(max(sums)), "-> halves", repr(b[:sums.index(max(sums))]), "and", repr(b[sums.index(max(sums)):]))
print("Hirschberg:", hirschberg(a, b))
print("longest common substring:", longest_common_substring(a, b),
"| LCS length:", dp[-1][-1])
# Check every method against the brute-force set on seeded random inputs.
rng = random.Random(11)
ties = 0
for _ in range(300):
x = "".join(rng.choice("abc") for _ in range(rng.randint(0, 8)))
y = "".join(rng.choice("abc") for _ in range(rng.randint(0, 8)))
table, want = build_table(x, y), all_lcs(x, y)
n_best = table[-1][-1]
ties += len(want) > 1
for got in (walk_back(x, y, table, True), walk_back(x, y, table, False),
hirschberg(x, y)):
assert got in want and len(got) == n_best
assert lcs_lex_smallest(x, y) == min(want)
print("\n300 random pairs checked against all_lcs; pairs with more than one LCS:", ties)
# Hirschberg does about twice the table work (cell updates), with rows instead of the table.
rng = random.Random(5)
s = "".join(rng.choice("ACGT") for _ in range(200))
t = "".join(rng.choice("ACGT") for _ in range(200))
cells = 0
h = hirschberg(s, t)
print("n*m =", len(s) * len(t), "| Hirschberg cell updates =", cells,
"| length matches table:", len(h) == build_table(s, t)[-1][-1])
Output
- B D C A B A
- 0 0 0 0 0 0 0
A 0 0 0 0 1 1 1
B 0 1 1 1 1 2 2
C 0 1 1 2 2 2 2
B 0 1 1 2 2 3 3
D 0 1 2 2 2 3 3
A 0 1 2 2 3 3 4
B 0 1 2 2 3 4 4
length: 4
walk back, ties go up: BCBA
(7,6) up=4 left=4 (tie), go up
(6,6) match 'A', go diagonal
(5,5) up=3 left=2, go up
(4,5) match 'B', go diagonal
(3,4) up=1 left=2, go left
(3,3) match 'C', go diagonal
(2,2) up=0 left=1, go left
(2,1) match 'B', go diagonal
walk back, ties go left: BDAB
all LCS strings: ['BCAB', 'BCBA', 'BDAB']
lexicographically smallest, step by step:
need 4 more; try 'A': earliest at a[0], b[3], 2 left after it -> skip
need 4 more; try 'B': earliest at a[1], b[0], 3 left after it -> take
need 3 more; try 'A': earliest at a[5], b[3], 1 left after it -> skip
need 3 more; try 'B': earliest at a[3], b[4], 1 left after it -> skip
need 3 more; try 'C': earliest at a[2], b[2], 2 left after it -> take
need 2 more; try 'A': earliest at a[5], b[3], 1 left after it -> take
need 1 more; try 'B': earliest at a[6], b[4], 0 left after it -> take
lexicographically smallest: BCAB
Hirschberg split of ABC | BDAB against BDCABA
left row (LCS of ABC with b[:k]): [0, 1, 1, 2, 2, 2, 2]
right row (LCS of BDAB with b[k:]): [4, 3, 2, 2, 2, 1, 0]
sums: [4, 4, 3, 4, 4, 3, 2] best k: 0 -> halves '' and 'BDCABA'
Hirschberg: BDAB
longest common substring: AB | LCS length: 4
300 random pairs checked against all_lcs; pairs with more than one LCS: 65
n*m = 40000 | Hirschberg cell updates = 79719 | length matches table: True
LCS versus longest common substring
A substring must be contiguous; a subsequence may skip characters. The substring table has the same shape but a different rule: on a match, cur[j] = prev[j-1] + 1; on a mismatch the cell is 0 (the run is broken), and the answer is the largest cell anywhere, not the bottom-right one. For the same two strings the longest common substring has length 2 (AB and BD tie; the code returns the first it finds, AB), while the LCS has length 4. The substring is always a valid common subsequence, so its length is at most the LCS length.
Reconstruction without the full table
The table costs O(nm) memory. Hirschberg's method (hirschberg above) finds the actual string using only rows: split a in half, compute the last row of the LCS table for the first half against b, and the same for the reversed second half against reversed b. The split point k in b that maximizes left[k] + right[len(b) - k] is where an optimal alignment crosses the middle row, so the two halves are solved recursively on their own pieces. Worked on the example (the printed split lines): ABCBDAB is cut into ABC and BDAB. The left row holds the LCS of ABC with each prefix b[:k] of BDCABA, the right row the LCS of BDAB with each suffix b[k:], and the sums for k = 0 to 6 are 4, 4, 3, 4, 4, 3, 2. The largest sum, 4, is the LCS length, and it is reached at k = 0, 1, 3 and 4: each of those is a valid place for an optimal answer to cross the middle (k = 3 corresponds to BC from the left half and AB from the right half, which is the BCAB answer). The code takes the first maximum, k = 0, which hands the empty prefix to the left half and the whole of b to the right half, and the recursion returns BDAB. On the 200 by 200 input it does 79,719 cell updates against n*m = 40,000, about twice the table, because the first level costs about n*m and the work halves at each level below it (1 + 1/2 + 1/4 + ...). The recursion is about log2(n) deep. This listing is not memory-tight: every call keeps its two rows and its slices alive while it recurses, and the slices copy, so in the worst case it holds up to about m cells for each of about log2(n) levels. The textbook form of the method passes index ranges instead of slices and discards the rows before recursing, which needs only linear space.
Complexity
- Table plus walk back: time O(nm) to fill (nm states, O(1) each) and O(n + m) to walk back, since every step reduces i or j. Space O(nm) for the table.
- Hirschberg: time O(nm), about twice the table work as measured above; linear space in the textbook form, a little more in the listing for the reason given above.
Edge cases and common mistakes
- If either string is empty the loop never runs and the result is the empty string.
- Forgetting to reverse the collected characters, which yields the answer backwards.
- Walking back with the wrong index: with prefix lengths i and j the characters compared are
a[i-1]andb[j-1]. - Claiming the answer is unique. Unless the problem says "the" lexicographically smallest or "any", state which rule you used for ties.
- Trying to reconstruct from the two-row length-only version: the old rows are gone, so use the full table or Hirschberg.
Running the code
Save the listing as lcs_string.py and run python lcs_string.py (Python 3.12, standard library only).
Houses form a binary tree, and you cannot take from two directly connected houses. Return the maximum amount you can take. Define what each node returns and how a parent combines its children.
Sample Answer
The idea in plain words
Picture the houses as nodes of a binary tree. Robbing a node blocks its parent and its two children. The key move is to let every node report two numbers to its parent instead of one: the best total for its subtree if the node itself is taken, and the best total if it is not. With both numbers, the parent never has to look at its grandchildren directly.
The DP, stated before any code
- State and meaning: for each node,
takeis the best total inside that node's subtree when the node is robbed, andskipis the best total inside the subtree when the node is not robbed. A "cell" is this pair, one per node. - Recurrence:
take = node.val + left.skip + right.skip(a robbed node forces both children to be skipped).skip = max(left.take, left.skip) + max(right.take, right.skip)(a skipped node leaves each child free to choose whichever is better). - Base case: an empty child (
None) returns(0, 0). - Fill order: children before parents, that is a post-order walk (left, right, then the node). The recursion does this naturally, and the answer is
max(take, skip)at the root. - Why
skipusesmaxand notskipalone: skipping a house does not force its neighbours to be skipped, it only frees them.
The brute force and its cost
The textbook recursion has no pair: brute(node) takes the node and jumps to its four grandchildren, or skips it and recurses on its two children. The same subtree is reached once through the child route and again through the grandchild route, so the work grows like the Fibonacci numbers. The run counts every call, None calls included, on a chain of n houses. The counts follow calls(n) = calls(n-1) + calls(n-2) + 3 for n >= 2 (with calls(0) = 1, calls(1) = 3), which the printed column matches. The pair version makes one call per node and one per missing child, 2n + 1 calls for any tree with n nodes; the last printed column counts the pair version's own calls and matches that formula (1, 3 and 5 for n = 0, 1, 2, against 1, 3 and 7 for the brute force).
Code
import random
import sys
class Node:
def __init__(self, val, name=""):
self.val, self.name = val, name
self.left = self.right = None
def build(level_order):
"""Build a tree from a level-order list where None marks a missing child."""
if not level_order or level_order[0] is None:
return None
nodes = [Node(v, f"n{i}") if v is not None else None for i, v in enumerate(level_order)]
kids = iter(nodes[1:])
for node in nodes:
if node is not None:
node.left, node.right = next(kids, None), next(kids, None)
return nodes[0]
def rob_tree(root, log=None, broken=False, counter=None):
"""Return the best total. Each node returns (take, skip)."""
def go(node):
if counter is not None:
counter[0] += 1 # counts every call, empty children included
if node is None:
return (0, 0) # an empty subtree gives nothing either way
lt, ls = go(node.left)
rt, rs = go(node.right)
take = node.val + ls + rs # taking this node forces both children to be skipped
if broken:
skip = ls + rs # wrong: assumes skipping a node also skips its children
else:
skip = max(lt, ls) + max(rt, rs) # skipping frees each child to do whatever is best
if log is not None:
log.append((node.name, node.val, take, skip))
return (take, skip)
return max(go(root))
calls = 0
def brute(node):
"""Textbook recursion without memo: take this node (jump to grandchildren) or skip it."""
global calls
calls += 1
if node is None:
return 0
take = node.val
for child in (node.left, node.right):
if child is not None:
take += brute(child.left) + brute(child.right)
return max(take, brute(node.left) + brute(node.right))
def path_tree(n):
root = cur = None
for i in range(n):
new = Node(1)
if root is None:
root = new
else:
cur.left = new
cur = new
return root
def subset_reference(vals, parent):
"""Try every subset of nodes; keep those with no parent-child pair both chosen."""
best = 0
for mask in range(1 << len(vals)):
if all(not (mask >> i & 1 and mask >> parent[i] & 1) for i in range(1, len(vals))):
best = max(best, sum(v for i, v in enumerate(vals) if mask >> i & 1))
return best
def random_tree(rng, n):
nodes = [Node(rng.randint(-3, 9), f"n{i}") for i in range(n)]
parent = [0] * n
free = [(0, "left"), (0, "right")] if n else []
for i in range(1, n):
slot = free.pop(rng.randrange(len(free)))
setattr(nodes[slot[0]], slot[1], nodes[i])
parent[i] = slot[0]
free += [(i, "left"), (i, "right")]
return (nodes[0] if n else None), [x.val for x in nodes], parent
# 1. Per-node (take, skip) values on a small tree
tree = build([3, 2, 3, None, 3, None, 1])
log = []
print("answer:", rob_tree(tree, log))
print("node value take skip (children are listed before their parent)")
for row in log:
print(*row)
print("with the wrong skip rule:", rob_tree(tree, broken=True))
# 2. Counted calls on a chain of n houses, each worth 1
print("n brute-force calls pair-DP calls")
for n in range(0, 13):
calls = 0
brute(path_tree(n))
pair_calls = [0]
rob_tree(path_tree(n), counter=pair_calls)
print(n, "", calls, "", pair_calls[0])
# 3. Skewed tree depth under CPython's default recursion limit
try:
rob_tree(path_tree(2000))
except RecursionError:
print("2000-node chain: RecursionError at limit", sys.getrecursionlimit())
# 3b. How subset_reference reads a mask: bit i of the number is 1 when node i is chosen
print("masks over 3 nodes (binary written with bit 0 on the right):")
for mask in (0, 1, 5, 7):
print(f" mask {mask} = {mask:03b} -> chosen nodes {[i for i in range(3) if mask >> i & 1]}")
# 4. Check against the subset reference on 400 distinct random trees (n = 0..12, values -3..9)
rng = random.Random(50)
seen = set()
while len(seen) < 400:
n = rng.randint(0, 12)
root, vals, parent = random_tree(rng, n)
key = (tuple(vals), tuple(parent))
if key in seen:
continue
seen.add(key)
got = rob_tree(root)
assert got == brute(root), key
assert got == subset_reference(vals, parent), key
print("checked", len(seen), "distinct trees")
Output (complete, unedited):
answer: 7
node value take skip (children are listed before their parent)
n4 3 3 0
n1 2 2 3
n6 1 1 0
n2 3 3 1
n0 3 7 6
with the wrong skip rule: 3
n brute-force calls pair-DP calls
0 1 1
1 3 3
2 7 5
3 13 7
4 23 9
5 39 11
6 65 13
7 107 15
8 175 17
9 285 19
10 463 21
11 751 23
12 1217 25
2000-node chain: RecursionError at limit 1000
masks over 3 nodes (binary written with bit 0 on the right):
mask 0 = 000 -> chosen nodes []
mask 1 = 001 -> chosen nodes [0]
mask 5 = 101 -> chosen nodes [0, 2]
mask 7 = 111 -> chosen nodes [0, 1, 2]
checked 400 distinct trees
Worked trace on the tree [3, 2, 3, None, 3, None, 1]
The printed rows come from the instrumented run, children before parents. Names n0..n6 are positions in the level-order list.
n4(value 3, a leaf) givestake = 3,skip = 0.n6(value 1) givestake = 1,skip = 0.n1(value 2, right childn4) givestake = 2 + 0 + 0 = 2andskip = 0 + max(3, 0) = 3.n2(value 3, right childn6) givestake = 3 + 0 + 0 = 3andskip = max(1, 0) = 1.- Root
n0(value 3) givestake = 3 + n1.skip + n2.skip = 3 + 3 + 1 = 7andskip = max(2, 3) + max(3, 1) = 6. The answer ismax(7, 6) = 7: housesn0(3),n4(3) andn6(1).
Complexity
- Time: O(n), one constant-time combine per node and one per missing child.
- Space: O(h) for the call stack, where
his the tree height: O(log n) for a balanced tree and O(n) for a chain. No table is stored, because the pair travels up as a return value. - The run shows the practical limit: a 2000-node chain raises
RecursionErrorat CPython's default limit of 1000 frames (CPython is the standard Python interpreter; every active function call occupies one frame, a record on the call stack, and the default allows 1000 of them nested at once). Deep trees need an iterative post-order or a raised limit.
Edge cases and common mistakes
- Empty tree:
go(None)returns(0, 0), the answer is 0. A single node returns its own value. Zero-value houses never change the total. Negative values (not realistic for money, but the check includes them) are handled becauseskipalways allows taking nothing. - The common wrong rule is
skip = left.skip + right.skip. It treats a skipped parent as if it blocked its children. On the traced tree the run returns 3 instead of 7. - The reference check
subset_referencetries every subset of nodes using a bitmask: a whole number whose binary digits stand for the nodes, where bit i is 1 exactly when node i is chosen. With 3 nodes, mask 5 is101in binary, so nodes 0 and 2 are chosen (the output prints four such masks). The testmask >> i & 1shifts the mask right by i places, so bit i lands in the lowest place (in Python>>binds tighter than&), and then keeps only that lowest bit; it is 1 when node i is chosen. Theall(...)line then rejects a mask when some node i and its parentparent[i]are both chosen. Bitmasks over every subset are a brute-force tool for small inputs, not something an interviewer expects in the tree solution itself. - The shipped check compares
rob_treewith a brute-force over every subset of nodes, and with thebruterecursion, on 400 distinct random trees with 0 to 12 nodes and values from -3 to 9, so empty, single-node, zero and negative values are included.
Follow-ups
- Return the chosen houses as well as the total: keep the winning branch for each state and walk down from the root.
- Replace the recursion with an explicit stack in post-order to survive a 200,000-node chain.
- Generalise from binary trees to any tree: the sums run over all children. The problem is then called a maximum weighted independent set on a tree (pick nodes, with no two connected by an edge, so that the total value is as large as possible).
Running the code
python3 house_robber_tree.py
Save the code block as house_robber_tree.py. Python 3.12, standard library only, finishes in well under a second.
Extend your edit-distance solution so that it also returns one sequence of edit operations that achieves the minimum, or shows the two strings aligned. How do you recover it, and what does that do to your space optimization?
Sample Answer
The idea
The table of distances already records which choice won in every cell, so the edits come from walking the table backwards. Start at the bottom-right cell. At each cell, find a neighbour that explains its value: the diagonal cell (a match for free, or a substitution for +1), the cell above (a deletion, +1) or the cell to the left (an insertion, +1). Step there, write down the column of the alignment (a column pairs one character of each string, or a character with a gap -), and repeat until you reach the top-left corner. Reading the columns from the corner gives the alignment, and every column that is not a match is one edit. A gap is a - standing where the other string has a character: a gap in the top row is an insertion, a gap in the bottom row is a deletion.
The five things to state
- What one cell means.
dp[i][j]is the fewest edits that turn the first i characters ofainto the first j characters ofb. - The transition.
dp[i][j] = min(dp[i-1][j] + 1, dp[i][j-1] + 1, dp[i-1][j-1] + cost)wherecostis 0 for equal characters and 1 otherwise. - Base cases.
dp[i][0] = ianddp[0][j] = j. - Fill order. Row by row, left to right.
- Where the answer is. The distance is
dp[n][m]; the edits come from walking back from that cell todp[0][0], the reverse of the fill order.
Recovering the alignment
The move at cell (i, j) is valid when it reproduces the cell's value:
- diagonal when
dp[i][j] == dp[i-1][j-1] + cost: the pair(a[i-1], b[j-1])is a column (a match or a substitution); - up when
dp[i][j] == dp[i-1][j] + 1: deletea[i-1], so the column is(a[i-1], -); - left when
dp[i][j] == dp[i][j-1] + 1: insertb[j-1], so the column is(-, b[j-1]).
On the top row only left is possible and on the first column only up. The code walks back using the values alone, with no pointers stored, and the trace below it prints each cell, the valid moves at that cell and the one taken. For sunday to saturday the walk gives s--unday over saturday: two insertions (a, t) and one substitution (n becomes r), for a distance of 3. show prints the alignment with a middle row of marks: | under two equal characters (a match, free), * under two different characters (a substitution, one edit) and a blank wherever either row has a gap (an insertion or a deletion, one edit each). In the output below, s--unday over saturday has marks | |*|||: s and s match, the two gaps are blank, then u, n over u, r gives | and *, and d, a, y match. script_from_alignment turns the columns into positional edits on the original string, and apply_script applies them right to left so earlier positions are not shifted; the result is saturday.
When several answers tie
If more than one move is valid at a cell, each leads to a different but equally cheap alignment. For abc to acb there are three: one with two substitutions, and two with one deletion and one insertion. The walk's preference order picks one: diagonal first gives abc over acb, up first gives a-bc over acb-, left first gives abc- over a-cb. count_optimal counts them with a second table (ways[i][j] sums the ways of every valid predecessor) and the 300-pair check compares that count and the set of alignments against a brute-force enumeration. State the rule you used; unless the problem names one, any optimal alignment is a correct answer.
The code
import random
def edit_table(a, b):
"""dp[i][j] = fewest edits turning a[:i] into b[:j]."""
dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
for i in range(len(a) + 1):
dp[i][0] = i
for j in range(len(b) + 1):
dp[0][j] = j
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
cost = 0 if a[i - 1] == b[j - 1] else 1
dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost)
return dp
def align(a, b, dp, order=("diag", "up", "left"), trace=None):
"""Walk back from the corner. At each cell take the first move in `order`
that reproduces the cell's value. Returns two equal-length strings, '-' = gap."""
i, j, top, bottom = len(a), len(b), [], []
while i > 0 or j > 0:
cost = 0 if i > 0 and j > 0 and a[i - 1] == b[j - 1] else 1
valid = []
if i > 0 and j > 0 and dp[i][j] == dp[i - 1][j - 1] + cost:
valid.append("diag")
if i > 0 and dp[i][j] == dp[i - 1][j] + 1:
valid.append("up")
if j > 0 and dp[i][j] == dp[i][j - 1] + 1:
valid.append("left")
move = next(m for m in order if m in valid)
if trace is not None:
trace.append(f"({i},{j}) value {dp[i][j]}, valid {valid}, take {move}")
if move == "diag":
top.append(a[i - 1]); bottom.append(b[j - 1]); i -= 1; j -= 1
elif move == "up":
top.append(a[i - 1]); bottom.append("-"); i -= 1
else:
top.append("-"); bottom.append(b[j - 1]); j -= 1
return "".join(reversed(top)), "".join(reversed(bottom))
def show(top, bottom):
marks = "".join(" " if "-" in (x, y) else ("|" if x == y else "*")
for x, y in zip(top, bottom))
return f"{top}\n{marks}\n{bottom}"
def script_from_alignment(top, bottom):
"""Turn aligned rows into edits that use positions in the ORIGINAL first string."""
ops, pos = [], 0
for x, y in zip(top, bottom):
if x == "-":
ops.append(("insert", pos, y))
elif y == "-":
ops.append(("delete", pos, x)); pos += 1
else:
if x != y:
ops.append(("replace", pos, y))
pos += 1
return ops
def apply_script(a, ops):
s = list(a)
for kind, pos, ch in reversed(ops): # right to left keeps positions valid
if kind == "replace":
s[pos] = ch
elif kind == "delete":
del s[pos]
else:
s.insert(pos, ch)
return "".join(s)
def count_optimal(a, b, dp):
"""ways[i][j] = number of different optimal alignments of a[:i] and b[:j]."""
ways = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
ways[0][0] = 1
for i in range(len(a) + 1):
for j in range(len(b) + 1):
if i == j == 0:
continue
total = 0
if i > 0 and j > 0:
cost = 0 if a[i - 1] == b[j - 1] else 1
if dp[i][j] == dp[i - 1][j - 1] + cost:
total += ways[i - 1][j - 1]
if i > 0 and dp[i][j] == dp[i - 1][j] + 1:
total += ways[i - 1][j]
if j > 0 and dp[i][j] == dp[i][j - 1] + 1:
total += ways[i][j - 1]
ways[i][j] = total
return ways[-1][-1]
def all_optimal(a, b):
"""Reference: enumerate every alignment of minimum cost by plain recursion."""
best, found = [10 ** 9], set()
def go(i, j, top, bottom, cost):
if cost > best[0]:
return
if i == len(a) and j == len(b):
if cost < best[0]:
best[0] = cost
found.clear()
found.add((top, bottom))
return
if i < len(a) and j < len(b):
go(i + 1, j + 1, top + a[i], bottom + b[j], cost + (a[i] != b[j]))
if i < len(a):
go(i + 1, j, top + a[i], bottom + "-", cost + 1)
if j < len(b):
go(i, j + 1, top + "-", bottom + b[j], cost + 1)
go(0, 0, "", "", 0)
return best[0], found
cells = 0
def last_row(a, b):
"""Edit distances from a to every prefix of b, keeping one row at a time."""
global cells
prev = list(range(len(b) + 1))
for i in range(1, len(a) + 1):
cur = [i] + [0] * len(b)
for j in range(1, len(b) + 1):
cells += 1
cost = 0 if a[i - 1] == b[j - 1] else 1
cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost)
prev = cur
return prev
def hirschberg_align(a, b):
"""Optimal alignment using only rows of length len(b)+1 for the split search."""
if not a:
return "-" * len(b), b
if not b:
return a, "-" * len(a)
if len(a) == 1: # tiny table: 2 rows
return align(a, b, edit_table(a, b))
mid = len(a) // 2
front = last_row(a[:mid], b)
back = last_row(a[mid:][::-1], b[::-1])
k = min(range(len(b) + 1), key=lambda k: front[k] + back[len(b) - k])
t1, b1 = hirschberg_align(a[:mid], b[:k])
t2, b2 = hirschberg_align(a[mid:], b[k:])
return t1 + t2, b1 + b2
def cost_of(top, bottom):
return sum(x != y for x, y in zip(top, bottom))
a, b = "sunday", "saturday"
dp = edit_table(a, b)
print(" " + " ".join(["-"] + list(b)))
for i, row in enumerate(dp):
print(f"{'-' if i == 0 else a[i - 1]} " + " ".join(str(v) for v in row))
trace = []
top, bottom = align(a, b, dp, trace=trace)
print("\ndistance:", dp[-1][-1], "\nwalk back (diagonal preferred):")
print("\n".join(" " + line for line in trace))
print(show(top, bottom))
ops = script_from_alignment(top, bottom)
print("edits:", ops, "->", apply_script(a, ops))
print("\nsunday -> saturday has", count_optimal(a, b, dp), "optimal alignment")
x, y = "abc", "acb"
tie_dp = edit_table(x, y)
print(x, "->", y, "has", count_optimal(x, y, tie_dp), "optimal alignments, distance", tie_dp[-1][-1])
for order in [("diag", "up", "left"), ("up", "left", "diag"), ("left", "up", "diag")]:
print(f"order {order}:")
print(show(*align(x, y, tie_dp, order)))
print("all optimal alignments:", sorted(all_optimal(x, y)[1]))
mid = len(a) // 2
front = last_row(a[:mid], b)
back = last_row(a[mid:][::-1], b[::-1])
sums = [front[k] + back[len(b) - k] for k in range(len(b) + 1)]
print(f"\nsplit search: a[:{mid}] = {a[:mid]!r}, a[{mid}:] = {a[mid:]!r}")
print("front[k] (first half vs b[:k]): ", front)
print("back[m-k] (second half vs b[k:], k=0..m):", [back[len(b) - k] for k in range(len(b) + 1)])
print("sum per k: ", sums)
print("best k:", sums.index(min(sums)), "-> b splits into", repr(b[:sums.index(min(sums))]), "and", repr(b[sums.index(min(sums)):]))
ht, hb = hirschberg_align(a, b)
print("row-only alignment:", ht, "/", hb, "| cost", cost_of(ht, hb))
# Check against brute force on seeded random inputs.
rng = random.Random(21)
multi = 0
for _ in range(300):
x = "".join(rng.choice("abc") for _ in range(rng.randint(0, 5)))
y = "".join(rng.choice("abc") for _ in range(rng.randint(0, 5)))
table = edit_table(x, y)
best, found = all_optimal(x, y)
assert best == table[-1][-1] and count_optimal(x, y, table) == len(found)
multi += len(found) > 1
for order in [("diag", "up", "left"), ("left", "up", "diag"), ("up", "diag", "left")]:
t, bt = align(x, y, table, order)
assert (t, bt) in found
assert apply_script(x, script_from_alignment(t, bt)) == y
ht, hb = hirschberg_align(x, y)
assert cost_of(ht, hb) == best and ht.replace("-", "") == x and hb.replace("-", "") == y
print("\n300 random pairs: alignments, edit scripts and row-only alignments are optimal;",
"pairs with more than one optimal alignment:", multi)
# Work done by the row-only method on two random strings of length 300.
rng = random.Random(8)
s = "".join(rng.choice("ACGT") for _ in range(300))
t = "".join(rng.choice("ACGT") for _ in range(300))
cells = 0
ht, hb = hirschberg_align(s, t)
print("n*m =", len(s) * len(t), "| row-only cell updates =", cells,
"| cost matches table:", cost_of(ht, hb) == edit_table(s, t)[-1][-1])
Output
- s a t u r d a y
- 0 1 2 3 4 5 6 7 8
s 1 0 1 2 3 4 5 6 7
u 2 1 1 2 2 3 4 5 6
n 3 2 2 2 3 3 4 5 6
d 4 3 3 3 3 4 3 4 5
a 5 4 3 4 4 4 4 3 4
y 6 5 4 4 5 5 5 4 3
distance: 3
walk back (diagonal preferred):
(6,8) value 3, valid ['diag'], take diag
(5,7) value 3, valid ['diag'], take diag
(4,6) value 3, valid ['diag'], take diag
(3,5) value 3, valid ['diag'], take diag
(2,4) value 2, valid ['diag'], take diag
(1,3) value 2, valid ['left'], take left
(1,2) value 1, valid ['left'], take left
(1,1) value 0, valid ['diag'], take diag
s--unday
| |*|||
saturday
edits: [('insert', 1, 'a'), ('insert', 1, 't'), ('replace', 2, 'r')] -> saturday
sunday -> saturday has 1 optimal alignment
abc -> acb has 3 optimal alignments, distance 2
order ('diag', 'up', 'left'):
abc
|**
acb
order ('up', 'left', 'diag'):
a-bc
| |
acb-
order ('left', 'up', 'diag'):
abc-
| |
a-cb
all optimal alignments: [('a-bc', 'acb-'), ('abc', 'acb'), ('abc-', 'a-cb')]
split search: a[:3] = 'sun', a[3:] = 'day'
front[k] (first half vs b[:k]): [3, 2, 2, 2, 3, 3, 4, 5, 6]
back[m-k] (second half vs b[k:], k=0..m): [5, 4, 3, 2, 1, 0, 1, 2, 3]
sum per k: [8, 6, 5, 4, 4, 3, 5, 7, 9]
best k: 5 -> b splits into 'satur' and 'day'
row-only alignment: s--unday / saturday | cost 3
300 random pairs: alignments, edit scripts and row-only alignments are optimal; pairs with more than one optimal alignment: 138
n*m = 90000 | row-only cell updates = 179559 | cost matches table: True
What this does to the space optimization
Keeping only one or two rows throws away exactly the cells the walk back needs, so the plain rolling-row version can give you the distance but not the edits. There are three ways out:
- Keep the whole table. Time O(nm), space O(nm). For two strings of length 2000 that is about four million cells. Storing one small direction code per cell instead of the number is still O(nm) cells, only smaller ones.
- Divide and conquer (Hirschberg's method).
hirschberg_aligncomputes, with rolling rows only, the cost of aligning the first half ofawith every prefix ofb(front) and the cost of aligning the second half with every suffix (back, computed on the reversed strings). An optimal alignment crosses the middle ofaat some column k ofb, and the best k minimizesfront[k] + back[len(b) - k]. Recurse on the two halves. Time stays O(nm) but is about twice the plain table: on two random strings of length 300 it made 179,559 cell updates againstn*m= 90,000, because the first level costs about nm and the work halves at each level below it (1 + 1/2 + 1/4 + ...). The recursion is about log2(n) deep. The split search itself uses two rows of length m + 1 at a time, but this listing is not memory-tight: every call keeps its rows and its copied slices alive while it recurses, so in the worst case it holds up to about m cells for each of about log2(n) levels. The textbook form passes index ranges instead of slices and discards the rows before recursing, which needs only linear space.
A worked split on sunday to saturday (the split search lines in the output): the middle of a cuts it into sun and day. front[k] is the cost of turning sun into the first k characters of saturday, and the second row is the cost of turning day into the remaining characters from k on. Adding the two for every k gives [8, 6, 5, 4, 4, 3, 5, 7, 9], and the smallest sum, 3, is at k = 5. Reading it as a cell: at k = 5, sun against satur costs 3 (insert a and t, substitute n with r) and day against day costs 0, so 3 + 0 = 3, which equals the distance. So some optimal alignment pairs sun with satur and day with day, and each half is then solved on its own with the same method. Hirschberg's method is deeper material than most coding rounds ask for; a typical interview wants the full-table walk back and the observation that rolling rows lose the path.
3. Recompute only when needed. If you need edits for very few pairs, run the cheap length-only version for all of them and reconstruct for the pairs that matter.
Complexity
- Table and walk back: time O(nm) to fill, O(n + m) to walk (every step lowers i or j); space O(nm).
- Row-only alignment: time O(nm) (about 2nm updates); linear space in the textbook form, a little more in the listing for the reason given above.
Edge cases and common mistakes
- If
ais empty the alignment is all insertions, and ifbis empty it is all deletions; thewhile i > 0 or j > 0loop handles both with no special case, since only the left or only the up move is valid there. - Forgetting to reverse the collected columns, which prints the alignment backwards.
- Applying the edits left to right with original positions, which shifts every later position after an insert or delete. Apply right to left, or track an offset.
- Treating a substitution of equal characters as an edit: only columns where the two characters differ count.
- Assuming the alignment is unique when
count_optimalcan be greater than 1.
Running the code
Save the listing as edit_alignment.py and run python edit_alignment.py (Python 3.12, standard library only).
Unlock Full Question Bank
Get access to all Dynamic Programming interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.