Skip to content
Tech Interview Prep
Technical interview guide

2-D Dynamic Programming

DP where the subproblem needs two indices: grid paths, two-string comparisons, and knapsack-style capacity constraints.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v8
Editorial status
Reviewed

Scope: Language-neutral, with memoisation and recursion behaviour cited from CPython 3.14.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

When does a dynamic program need a second state dimension, and how do you decide what the second index should encode?

Answer

A DP needs a second dimension when the index you have does not fully determine the subproblem: two subproblems at the same index can still be asking different questions. That is the test. Fix every index you already have, and ask whether the answer can still vary. If it can, you are missing a dimension.

LCS is the clean case. "The LCS of s up to position i" is ambiguous, because the answer also depends on how much of t you have consumed. So the state is dp[i][j] = length of the LCS of s[:i] and t[:j]. Edit distance has the same shape. Zero-one knapsack after i items depends on how much capacity is left, so dp[i][w]. A grid path depends on both coordinates, so dp[i][j]. In each case the second index is exactly the quantity the first index does not pin down: position in the second sequence, remaining budget, the other coordinate.

Before writing any recurrence I write one sentence: dp[i][j] is ____. Base cases are then the zero edges (i = 0 or j = 0), and the state count is the product of the ranges: two length-1000 strings give 1001 x 1001, about 1.0M cells.

Storage is a separate decision from state. Rolling the table changes memory, not meaning:

Python
# LCS, rolling: prev is row i-1 while cur is row i
prev = [0] * (m + 1)
for i in range(1, n + 1):
    cur = [0] * (m + 1)
    for j in range(1, m + 1):
        if s[i - 1] == t[j - 1]:
            cur[j] = prev[j - 1] + 1
        else:
            cur[j] = max(prev[j], cur[j - 1])
    prev = cur

Still dp[i][j] conceptually, but memory falls from roughly 4 MB to 8 KB for a 1000x1000 table of 4-byte ints. You can drop the table, never the index.

The failure this invites is specific: collapse the table and then walk it in an order that reads a cell after it has been overwritten. In 0/1 knapsack the capacity loop must go downward, or every item becomes usable infinitely often; edit distance needs one saved scalar for the diagonal before it is clobbered. Both bugs pass the sample input and surface only on data that reuses an item.

In practice: name the state in words, write the base cases, then pick storage and say the overwrite order out loud. Rolling is correct only while the transition reads a bounded number of earlier rows.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

When you formulate a 2-D DP, when do you index states by input indices (prefix/suffix) versus by an auxiliary parameter like remaining capacity or budget?

Answer

Index by input positions when the subproblem is 'the best answer on a piece of the input'; index by an auxiliary parameter when the subproblem is 'the best answer under a constraint the input itself does not delimit'. The test is whether the constraint shrinks as you consume input: if it does, it is a state variable; if it does not, it is not.

Mechanically, a state must capture everything the future depends on that the past can still change. In LCS, the future depends only on how much of each string remains, so (i, j) as prefix lengths is complete. In 0/1 knapsack, the future depends on which items remain and how much weight budget is left: the budget is not derivable from the item index, so it must be a dimension. The classic failure is omitting it: a state like 'best value using the first i items' is not well-defined, because two different selections of those items leave different budgets, and the recurrence silently merges them into a wrong answer that is too optimistic.

The two shapes, side by side:

prefix/suffix indicesauxiliary parameter
ExampleLCS dp[i][j], edit distanceknapsack dp[i][w], partition dp[i][s]
Table size(m+1)(n+1), bounded by input(n+1)(W+1), pseudo-polynomial in the parameter
Base casesempty prefix row/columnbudget 0 or budget exhausted
Answer celldp[m][n]max over w of dp[n][w] (or a fixed cell)
Python
# LCS: both dimensions are input prefixes; answer at dp[m][n].
dp[i][j] = max(dp[i-1][j], dp[i][j-1], dp[i-1][j-1] + (a[i-1] == b[j-1]))

# 0/1 knapsack: second dimension is remaining capacity, not an input index.
dp[i][w] = max(dp[i-1][w],                       # skip item i-1
             dp[i-1][w - wt[i-1]] + val[i-1])    # take it, if it fits

The knapsack recurrence only works because w - wt[i-1] is a state that exists in the table; that is the signature of an auxiliary dimension: transitions move along it by input-dependent amounts rather than by 1.

The trap this choice invites is specific: treating the parameter as if it were bounded like an input length. Knapsack is O(nW), which is exponential in the bit-length of W: fine at W = 10^5, hopeless at W = 10^12, where the DP is the wrong tool and you fall back to greedy-by-ratio or branch and bound. Conversely, forcing a constraint problem into pure prefix indices (say, tracking 'items used so far' instead of budget) does not shrink the state space; it just hides the parameter inside an exponential set of reachable configurations.

In practice, write down what the future needs to know, check each candidate variable actually changes across transitions, and prefer the auxiliary dimension whenever a constraint is consumed rather than merely observed. The senior answer stays conditional: the formulation is correct either way only if the state is complete, and completeness is argued from the recurrence, not from the shape of the table.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

How do you derive the grid-path counting recurrence, and how far can you reduce the space? Walk me through the state, the recurrence, the base cases, one small grid you compute by hand, and what the loop order must preserve when you go to O(n).

Answer

Every path into (i,j) ends with exactly one move, and that observation is the whole derivation.

State. dp[i][j] = the number of distinct paths from (0,0) to (i,j) moving only right or down. It is a count, so nothing else has to be carried: no remaining budget, no mode flag.

Recurrence. Look at the final step of any path that reaches (i,j). It came from (i-1,j) moving down, or from (i,j-1) moving right. Those two groups are disjoint, a path cannot end with both moves, so

dp[i][j] = dp[i-1][j] + dp[i][j-1]

The disjointness is the part worth saying out loud. It is exactly what fails when you add a diagonal move and have to decide whether the three predecessor groups overlap.

Base cases. dp[0][0] = 1 (the empty path), and dp[0][j] = dp[i][0] = 1: each border cell has exactly one monotone route to it.

Hand check, 3×4 grid.

1 1 1 1
1 2 3 4
1 3 6 10

dp[2][3] = dp[1][3] + dp[2][2] = 4 + 6 = 10. Cross-check: 2 down-moves and 3 right-moves in any order, C(5,2) = 10. In general the answer is C(m+n-2, m-1), which is a cheap oracle for tests.

Space. The recurrence reads only the row above and the cell to the left, so one array of length n suffices:

Python
def count_paths(m: int, n: int) -> int:
    dp = [1] * n                 # dp[j] = count for cell (i, j)
    for i in range(1, m):
        for j in range(1, n):
            dp[j] += dp[j - 1]   # dp[j]: row i-1; dp[j-1]: already row i
    return dp[n - 1]

What the loop order must preserve: rows outer, columns inner in ascending order. Left-to-right is what guarantees dp[j-1] is already the current row while dp[j] is still the previous one. Sweeping j descending silently computes dp[i][j] = dp[i-1][j] + dp[i-1][j-1] instead: wrong counts, no exception.

The floor is O(mn) time and O(n) space. Going to O(1) means using the closed form, which drops obstacle support and needs big integers: a 35×35 grid already gives C(68,34) ≈ 2.5×10^19, past 2^63−1. Reconstruction also wants the full table or a second pass.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Walk through obstacles and unreachable cells, including where engineers most often get it wrong.

Answer

Assume an m-by-n grid where 1 marks an obstacle and the only moves are right and down. dp[i][j] is the number of monotone paths from (0,0) to that cell. Two rules carry the whole answer.

First: an obstacle takes zero paths. dp[i][j] = 0 there, and it never enters a sum.

Second, the one most solutions get wrong: an obstacle in the first row makes every cell to its right unreachable, because row 0 is only reachable by moving right along it. Same for a first-column obstacle and the cells below it. So border initialisation must break at the first obstacle, not skip it.

Say this part out loud: a 0 in the table is overloaded. It means "blocked" or "free but unreachable": a free cell with no monotone path in has none out either. Counting does not care, since neither contributes to a downstream sum. The border loop is the only place the difference changes the code, which is why the break is not cosmetic.

Python
def unique_paths(grid):            # Python 3
    m, n = len(grid), len(grid[0])
    if grid[0][0] == 1:
        return 0
    dp = [[0] * n for _ in range(m)]
    dp[0][0] = 1
    for j in range(1, n):          # first row
        if grid[0][j] == 1:
            break                  # the rest of the row stays 0
        dp[0][j] = 1
    for i in range(1, m):          # first column
        if grid[i][0] == 1:
            break
        dp[i][0] = 1
    for i in range(1, m):
        for j in range(1, n):
            if grid[i][j] == 0:
                dp[i][j] = dp[i-1][j] + dp[i][j-1]
    return dp[m-1][n-1]

Obstacles at (0,2) and (1,1), 3 rows by 4 columns:

grid         dp        j=0  j=1  j=2  j=3
0 0 1 0      i=0        1    1    0    0
0 1 0 0      i=1        1    0    0    0
0 0 0 0      i=2        1    1    1    1

Running it: dp[0][0] = 1. Row loop, j=1 sees grid[0][1] = 0 and sets dp[0][1] = 1; j=2 sees 1 and breaks, leaving dp[0][2] = dp[0][3] = 0. Column loop gives dp[1][0] = 1 and dp[2][0] = 1. Interior, i=1: dp[1][1] stays 0 (blocked); dp[1][2] = dp[0][2] + dp[1][1] = 0; dp[1][3] = dp[0][3] + dp[1][2] = 0. i=2: dp[2][1] = dp[1][1] + dp[2][0] = 1; dp[2][2] = dp[1][2] + dp[2][1] = 1; dp[2][3] = dp[1][3] + dp[2][2] = 1. Answer 1, the path down, down, right, right, right.

Change that break to a continue and row 0 initialises to 1, 1, 0, 1. Nothing throws. The same grid now returns 2: dp[1][3] = dp[0][3] + dp[1][2] = 1 + 0 = 1, counting routes through a cell that cannot be entered, and dp[2][3] = dp[1][3] + dp[2][2] = 1 + 1 = 2. No exception, no out-of-range: just one extra path per unreachable border run.

Other places it goes wrong:

  • A blocked start. dp[0][0] = 1 seeds the table with paths leaving an obstacle; guard it. A blocked destination needs no extra check, since a cell never assigned stays 0.
  • A sentinel of -1 for "blocked" and then adding it into a sum. Keep it out of the arithmetic or carry a separate visited flag.
  • Top-down memoisation using 0 for "not computed". A blocked cell legitimately stores 0, so the memo never hits and the recursion re-explores subtrees, going exponential on a grid that should be linear.

Choice depends on the grid. Bottom-up 2D is the default and the easiest to defend. A single rolling array of n counters cuts memory from mn cells to n (4,000,000 down to 2000 on a 2000-by-2000 grid) but with no border loop to break, column 0 has to be zeroed by hand the first time an obstacle appears in it. If the grid is enormous and obstacles are few, the DP is the wrong shape: sort k obstacles by row+column and use inclusion-exclusion, each term a binomial C(a+b, a), for O(k^2) time. A 10^9-by-10^9 grid with 20 obstacles is a few hundred operations that way, impossible by DP. Dense obstacles invert it: as k approaches mn, the O(k^2) pass is the slower one.

Keep a brute-force DFS on a 4-by-4 grid around. The break-versus-skip bug shows up there in seconds.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

What does minimum-cost paths guarantee, and what does it deliberately leave open?

Answer

Assume a directed graph G = (V, E) with edge weights w(e), a source s and a target t, and path cost = sum of edge weights. Under those assumptions a minimum-cost path guarantees exactly two things, and nothing else.

The guarantee. (1) Optimality of the total: no other s→t path has a lower sum. (2) Optimal substructure: every subpath of a minimum-cost path is itself a minimum-cost path between its own endpoints. (2) is why the DP recurrence and Dijkstra are correct at all: you can build the answer from optimal pieces instead of enumerating paths.

What it leaves open. The path. The guarantee is about a number, not a route. Ties are unresolved: when two paths share the minimum cost, the algorithm returns whichever its tie-breaking rule picks, and that choice is not part of the guarantee. Hop count is unresolved: the minimum-cost path is not the fewest-edge path. And the cost model is unresolved: weights are inputs, so the algorithm guarantees nothing about whether they encode what you actually care about.

A trace makes the split concrete. Edges: A→B(1), A→C(4), A→D(3), B→C(1), B→D(5), C→D(1). Dijkstra from A:

dist[A]=0, rest inf
pop A(0):  B=1, C=4, D=3
pop B(1):  C=min(4, 1+1)=2, D=min(3, 1+5)=3
pop C(2):  D=min(3, 2+1)=3   # tie, no update
pop D(3):  done

dist[D]=3 is the guarantee: A→B→C→D costs 3 and A→D costs 3, and nothing beats 3. What is left open is which one you get. D's predecessor was set to A when dist[D] first hit 3, so the returned path is A→D, one edge, while A→B→C→D, three edges, is equally optimal and never surfaces. Same cost, different route, and the algorithm is not wrong either way.

Which algorithm you reach for is a separate decision, driven by weight signs and graph shape:

AlgorithmWeightsTime
Dijkstra, binary heapnon-negativeO((V+E) log V)
Bellman-Fordnegative edges allowedO(V·E)
DP on a DAGanyO(V+E)
Floyd-Warshallany, all pairsO(V³)

Failure modes worth naming. A negative cycle reachable from s means no minimum exists, cost is unbounded below, and Bellman-Ford flags it on the V-th relaxation pass. Dijkstra on a negative edge fails silently: with A→B(1), A→C(2), C→B(−2), it finalizes B at 1 and never revisits, reporting 1 when the true minimum is 0. Ties produce nondeterministic output across runs if the tie-break depends on iteration order. And a cost model that omits a term you care about yields a provably optimal path that is still the wrong one to ship.

So: the guarantee is a minimal total plus optimal substructure. The route, the tie-break, the hop count, and the fidelity of the weights are all left open, and each has to be decided by you, not by the algorithm.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

When a 2-D DP transition carries a cost (a weight, penalty or per-move charge) where in the recurrence should it be applied, and what characteristic wrong answer do you get if it's counted twice or left out?

Answer

Assume the cost is additive and non-negative: every move or operation carries its own cost and the objective is the total along a sequence of decisions. If the cost depends on anything beyond the move just taken (a discount after k moves, a penalty for revisiting a cell) it is no longer a transition cost, and no placement of the term will fix it; it has to become part of the state.

The rule: charge the cost on the edge, inside the recurrence, at the moment the move is taken, exactly once per move. The state value is the best total including the cost of the move that produced it, and nothing is added when the answer is read out of the table.

Take minimum-cost paths in a grid where entering a cell costs its weight and you may only move right or down:

Python
dp[i][j] = w[i][j] + min(dp[i-1][j], dp[i][j-1])
dp[0][0] = w[0][0]

The base case is the only cell with no incoming edge, and it is where the convention has to be settled. If entering the start cell counts toward the total, charge w[0][0] there once. If the cost is per move instead, dp[0][0] = 0 and every move pays. What you cannot do is charge the start in the base case and then charge it again on the first move out: that is the double count.

Worked check on

1 2 3
4 8 2
1 5 1
j=0j=1j=2
i=0136
i=1578
i=26119

The answer is 9, and the path 1→2→3→2→1 sums to exactly 9: five cells, five charges. The counting invariant is the check I actually use. A path from (0,0) to (n-1,m-1) visits n+m-1 cells and takes n+m-2 moves, so the DP total must equal the weight sum of exactly n+m-1 cells: here 3+3-1 = 5. If the table returns something that is not the cost of any real path, a term is being charged twice or not at all.

Characteristic wrong answers:

  • Double count. dp[i][j] = w[i][j] + min(dp[i-1][j] + w[i-1][j], dp[i][j-1] + w[i][j-1]): charging both endpoints of the edge. Row 0 becomes 1, 4, 9 instead of 1, 3, 6. The reported total is higher than the cost of every real path, and the error grows with path length: k moves means k extra charges. That proportionality is the signature. A constant offset points at a base case; an error that scales with path length says a cost sits on both ends of an edge.
  • Omit. Dropping w[i][j] from the transition, or setting dp[0][0] = 0 under the convention that charges the start. The table returns a lower bound no path achieves: here 8 instead of 9, off by exactly w[0][0]. Omission is the more dangerous bug because the number still looks plausible and still ranks paths against each other.

Edit distance with weighted operations has the same shape: the substitution, deletion and insertion costs go on the operation edge, dp[i][j] = min(dp[i-1][j-1] + sub, dp[i-1][j] + delete, dp[i][j-1] + insert), and the base cases dp[i][0] = i*delete, dp[0][j] = j*insert charge one edge per step, which is exactly why they are linear in i and j rather than zero.

How I would catch this in review: one test where every weight is 1, so the answer must be exactly n+m-1 (or n+m-2 under the per-move convention) and any double charge shows up as arithmetic; and a brute-force enumeration of all paths on a random 4×4 grid compared against the DP. Both are cheap and neither needs a production incident to be worth writing.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

How do you build the LCS table, reconstruct one actual subsequence from it, and handle ties, and what changes for longest common substring?

Answer

State: dp[i][j] is the length of the longest common subsequence of s[:i] and t[:j], for 0 ≤ i ≤ m, 0 ≤ j ≤ n. Both indices are prefix lengths, so cell (i, j) compares s[i-1] against t[j-1]: that off-by-one is where most bugs live. Base cases: dp[0][j] = dp[i][0] = 0, since an empty prefix shares nothing.

Python
for i in range(1, m + 1):
    for j in range(1, n + 1):
        if s[i-1] == t[j-1]:
            dp[i][j] = dp[i-1][j-1] + 1            # extend the best run ending here
        else:
            dp[i][j] = max(dp[i-1][j], dp[i][j-1]) # drop one char from either side

dp[m][n] is the answer because that cell is the LCS of the two complete prefixes s[:m] and t[:n]: the whole strings. Any fill order that leaves (i-1,j-1), (i-1,j) and (i,j-1) ready works; row-major does.

Reconstruction walks backwards from (m, n):

Python
i, j, out = m, n, []
while i > 0 and j > 0:
    if s[i-1] == t[j-1]:
        out.append(s[i-1]); i -= 1; j -= 1
    elif dp[i-1][j] >= dp[i][j-1]:
        i -= 1
    else:
        j -= 1
return "".join(reversed(out))

On s = "ABCBDAB", t = "BDCABA" the table ends at 4. The walk goes (7,6) → left → (7,5) match B → (6,4) match A → (5,3) mismatch where dp[4][3] = dp[5][2] = 2, a tie → up → (4,3) up → (3,3) match C → (2,2) left → (2,1) match B, giving "BCBA". Taking the other branch at that tie gives "BDAB": same length, different subsequence. Ties are real: the table stores a length, not a choice, so the tie-break rule decides which optimal answer you get. Fix it (prefer up, or prefer left) so output is deterministic; both are correct.

Longest common substring is the same table with contiguity forced: dp[i][j] = dp[i-1][j-1] + 1 on a match, 0 on a mismatch. No max over neighbours, because a mismatch breaks the run. The answer is the max over all cells, and you keep the argmax cell and walk diagonally back while characters still match.

Cost is O(mn) time and O(mn) space. The length alone fits in O(min(m, n)) with two rows; reconstruction then needs the full table or Hirschberg's split.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

How do you derive the edit-distance recurrence, and how do you cut the table to two rows? Walk me through the state, the insert/delete/replace branches, the base cases, one small worked example, and what has to be carried across iterations.

Answer

State. dp[i][j] is the minimum number of insert, delete and replace operations turning word1[0..i) into word2[0..j). Both indices are prefix lengths, so the table is (m+1)×(n+1) and the answer sits at dp[m][n].

Derivation. Take an optimal script for the pair (i, j) and look at the operation that consumed a[i-1]:

  • delete a[i-1]: the rest is an optimal script for (i-1, j), so dp[i-1][j] + 1
  • insert b[j-1]: dp[i][j-1] + 1
  • replace a[i-1] with b[j-1]: dp[i-1][j-1] + 1
  • nothing, when a[i-1] == b[j-1]: dp[i-1][j-1]

Those four exhaust the possibilities, and each leaves a strictly smaller prefix pair, so the subproblems are optimal and the recurrence is dp[i][j] = min(...). The match case is not a fourth candidate to be minimised, when the characters are equal, dp[i][j] = dp[i-1][j-1] exactly, because any script that pays to touch a matched pair can be rewritten to leave it alone. Dropping that branch is why people misremember the recurrence as "three neighbours plus one".

Base cases. dp[i][0] = i (delete the whole prefix of a), dp[0][j] = j (insert the whole prefix of b), dp[0][0] = 0.

Worked example, "ab" → "ba":

      ""  b  a
  ""   0  1  2
  a    1  1  1
  b    2  1  2

dp[2][1] = 1 comes from the match branch (b matches b, cost 0), not from a +1. dp[2][2] = 1 + min(dp[1][2], dp[2][1], dp[1][1]) = 1 + min(1, 1, 1) = 2.

Cutting to two rows. Row i reads only row i-1 and the cell to its left, so one previous row plus the row being written is enough:

Python
def edit_distance(a: str, b: str) -> int:      # Python 3.12
    prev = list(range(len(b) + 1))             # dp[0][j] = j
    for i in range(1, len(a) + 1):
        cur = [i] + [0] * len(b)               # dp[i][0] = i, reset every row
        for j in range(1, len(b) + 1):
            if a[i-1] == b[j-1]:
                cur[j] = prev[j-1]
            else:
                cur[j] = 1 + min(prev[j], cur[j-1], prev[j-1])
        prev = cur
    return prev[len(b)]

Trace on a="ab", b="ba":

stepprev beforecur after
i=1 ('a')[0,1,2][1,1,1]: j=1 mismatch → 1+min(1,1,0)=1; j=2 match → prev[1]=1
i=2 ('b')[1,1,1][2,1,2]: j=1 match → prev[0]=1; j=2 mismatch → 1+min(1,1,1)=2

Returns prev[2] = 2. Loop order is fixed: i outer, j inner, left to right.

What has to be carried. The whole previous row; the left neighbour cur[j-1], already written this row; the diagonal prev[j-1], which must be read before cur[j] is overwritten; and i itself, for the cur[0] = i base case. If you swap the arguments so the shorter string is b, the row length is min(m, n) and space is O(min(m, n)).

Failure modes. Writing one row in place without saving the diagonal destroys dp[i-1][j-1] one iteration early. It survives casual testing because short strings and strings with long matching runs still come out right. Detect it with a differential test: run the two-row version against a full-table version on random strings over a 2–3 letter alphabet, lengths up to 8, and assert equality; cheap invariants catch the rest. d(a,b) == d(b,a), d(a,b) >= abs(len(a)-len(b)), and d(a,a) == 0. The other cost of two rows is that the edit script is gone. If you need the operations, keep the full table, or use Hirschberg's divide-and-conquer, which recovers the script in O(mn) time and O(min(m,n)) space. For unit costs and a small alphabet, Myers' bit-parallel algorithm runs in O(ceil(m/64)·n); for a bounded distance k, a banded (Ukkonen) table is O(k·min(m,n)). If replace is disallowed or costs 2, drop the diagonal branch and the recurrence becomes the LCS distance.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

Walk me through the 2-D DP for wildcard matching with '?' and '*' (LeetCode 44): the state dp[i][j], the literal/'?' transition, both '*' branches, the empty-string and empty-pattern base cases including a leading run of '*', the off-by-one convention, and the O(mn) cost.

Answer

Take s as the text and p as the pattern: '?' matches any single character, '*' matches any sequence including empty. The table is (n+1) x (m+1) and dp[i][j] is true exactly when s[:i] matches p[:j]. The convention that keeps the indices straight is that i and j count consumed characters, so cell (i, j) reads s[i-1] and p[j-1], and dp[0][0] is empty against empty.

Transitions, filling i from 0..n and j from 1..m:

  • p[j-1] is a literal or '?': dp[i][j] = dp[i-1][j-1] and (p[j-1] == '?' or p[j-1] == s[i-1]). Both sides consume one character, so the dependency is the diagonal; at i == 0 there is nothing to consume and the cell is false.
  • p[j-1] is '*': dp[i][j] = dp[i][j-1] or dp[i-1][j]. The first branch consumes zero characters of s and moves past the star; the second consumes one more character of s and stays on the same pattern cell, which is what lets a star swallow a run. The asymmetry is the point: the consume-one branch is dp[i-1][j], not dp[i-1][j-1], because the pattern index does not move.

Base cases: dp[0][0] = true; dp[i][0] = false for i >= 1 (an empty pattern matches only the empty string); and dp[0][j] is true if and only if p[:j] is all '', filled as dp[0][j] = dp[0][j-1] when p[j-1] == '' else false. That last row is where implementations break. Setting it true for every j makes "a" match ""; leaving it false makes "***" fail against "". The answer is read at dp[n][m].

s = "ab", p = "a*":

        ""   a   *
   ""    T   F   F
   a     F   T   T
   ab    F   F   T

Cell dp[1][2] takes the zero-consume branch: dp[1][1] = T. Cell dp[2][2] = dp[2][1] or dp[1][2] = F or T = T: the star took the 'b' through dp[i-1][j].

Cost is O(nm) time and O(nm) space for the full table. Space rolls to O(m): a cell needs dp[i-1][j] (same column, previous row), dp[i][j-1] (current row, left) and dp[i-1][j-1] (diagonal). Run j left to right so the left neighbour already holds the new row's value, and keep the diagonal in a temp before overwriting it. Run j right to left and the star's zero-consume branch reads a stale cell.

Two failure modes worth naming. Writing dp[i-1][j-1] for the star's consume-one branch makes '' match exactly one character: "abc" against "a" then returns false at dp[3][2] = dp[3][1] or dp[2][1], both false. And a wrong empty-string row shows up only on empty text, which unit tests rarely cover.

When the table is not needed, the greedy two-pointer matcher with backtracking to the last star does one pass over s with O(1) extra space; its worst case is still O(nm) on adversarial pairs such as s = "aaaa...ab" against p = "aa*...a", so the table stays the defensible default when you want the table for other queries too. Collapsing runs of '' in the pattern first shrinks m at no cost.

LeetCode 10 has the same table shape but different star semantics: '*' binds to the preceding element, so the branches are "zero occurrences of p[j-2]" (dp[i][j-2]) and "one more occurrence" (dp[i-1][j] when p[j-2] matches s[i-1]).

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Where does weighted edit operations matter, and where is it irrelevant?

Answer

Direct answer. Weighted edit distance matters wherever the cost of an error is not uniform, where the application's notion of "wrong" is graded or directional. It is irrelevant when every operation costs the same, or when you only ever compare in one fixed direction and never need a metric.

Where it matters

DomainWhat carries the weight
Spell correction / OCRSubstitution cost from a confusion matrix: rn→m, l→1, keyboard-adjacent keys cheaper than random letters.
BioinformaticsBLOSUM62 / PAM250 substitution scores plus affine gap penalties. BLAST's default for BLOSUM62 protein searches is gap existence 11, extension 1.
Speech / ASR rescoringPhoneme confusion weights.
Record linkageField-level weights; a wrong digit in a postcode costs more than a wrong letter in a name.

Where it is irrelevant

  • Unit-cost Levenshtein: all three operations cost 1, so weighting degenerates to the plain recurrence.
  • Fixed-direction comparison: if you always compute d(query, dictionary_entry) and never the reverse, asymmetry never bites.
  • Threshold-only decisions with uniform costs: a Levenshtein automaton answers "is distance ≤ k" without ever materialising a weighted score.

Why the recurrence survives. Weighting changes the constants, not the structure:

d[i][j] = min(d[i-1][j] + del,
              d[i][j-1] + ins,
              d[i-1][j-1] + (0 if s[i]==t[j] else sub))

With insert=1, delete=5, substitute=2:

  • d("ab","abc") = 1: one insertion.
  • d("abc","ab") = 5: one deletion.

Same code, same O(nm) table, different answer per direction. That asymmetry is the whole point: the result is no longer a metric, so anything assuming symmetry. A cache keyed on an unordered pair, a BK-tree, a VP-tree, a triangle-inequality pruning bound. Is now wrong.

Where weighting changes the algorithm, not just the constants.

  • Damerau-Levenshtein: adding transposition as a first-class operation adds a fourth term d[i-2][j-2] + transposition_cost and needs last-seen-row bookkeeping. The recurrence itself changes.
  • Affine gap penalties: gap_open + (n-1)·gap_extend cannot be expressed in one table. Gotoh's algorithm carries three matrices (match, gap-in-x, gap-in-y). This is the standard in sequence alignment precisely because one long gap should cost less than many short ones.
  • Banded DP / Ukkonen cutoff: with unit costs the band is width k; with weighted costs the band is k / min_cost, and any A* heuristic must be scaled by the cheapest operation or it stops being admissible.

Deciding criteria. Ask two questions. Is the cost model symmetric? If yes, unit-cost code and symmetric caches are fine. If no, key every cache by the ordered pair and drop any metric-space index. Second: does the weighting change the operation set (transposition, affine gaps)? If yes, you need a different recurrence, not a different constant.

Failure modes. A cache keyed on frozenset({a, b}) under asymmetric costs silently returns the wrong direction's value; it survives casual testing because the happy path hides it. A BK-tree built on a weighted distance returns wrong neighbours once the triangle inequality fails. Both are caught by property tests that assert d(a,b) == d(b,a) only when the cost model is symmetric, and assert it fails when it is not.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Teach the zero-one knapsack table to an engineer who has only seen it as a rule of thumb.

Answer

The state. dp[i][w] is the best total value achievable using only the first i items with a capacity budget of at most w. Two dimensions because the answer depends on both how many items you're allowed to consider and how much room is left. The recurrence is take-or-skip:

dp[i][w] = max(dp[i-1][w], dp[i-1][w - wt[i-1]] + val[i-1])   if wt[i-1] <= w
dp[i][w] = dp[i-1][w]                                          otherwise

The skip term reads the previous row at the same capacity. The take term reads the previous row at w - wt[i-1]. Both read row i-1, never row i. That is the whole trick: item i is added to a solution built from items 1..i-1, so it cannot be counted twice. Optimal substructure holds because the best solution for (i, w) either uses item i or does not; either way the remainder is an optimal solution to a smaller subproblem.

Worked trace. Items as (weight, value): (1,1), (3,4), (4,5), (5,7). Capacity W = 7. Rows i = 0..4, columns w = 0..7:

i=0:  0 0 0 0 0 0 0 0
i=1:  0 1 1 1 1 1 1 1
i=2:  0 1 1 4 5 5 5 5
i=3:  0 1 1 4 5 6 6 9
i=4:  0 1 1 4 5 7 8 9

Cell (3,7): skip = dp[2][7] = 5; take = dp[2][7-4] + 5 = dp[2][3] + 5 = 4 + 5 = 9. So 9. The answer is dp[4][7] = 9, from items 2 and 3 (weight 3+4 = 7, value 4+5 = 9).

Rolling to 1D. You only ever read row i-1, so keep one array dp[w] and update in place, but iterate w from W down to wt[i]:

Python
dp = [0] * (W + 1)
for i in range(n):
    for w in range(W, wt[i] - 1, -1):
        dp[w] = max(dp[w], dp[w - wt[i]] + val[i])

Descending order matters: dp[w - wt[i]] must still hold the previous row's value. Ascending would let item i be taken again from an already-updated cell: that is the unbounded knapsack, not this one.

Cost. O(nW) time. O(nW) space for the 2D table, O(W) for the rolling array. W is a magnitude, not a count, so O(nW) is pseudo-polynomial: linear in the numeric value of the capacity, exponential in the bits used to write it. A capacity of 10^9 is fine; 10^9 items is not.

Memoisation vs tabulation. Top-down recursion with a memo visits only reachable (i, w) states, which wins when few states are reachable or when you want the chosen items back by walking the recursion. Tabulation is iterative, avoids the recursion limit at large n, and has better cache locality on the row-major table.

Failure modes. Reading row i instead of i-1 in the 2D version silently solves unbounded knapsack: it passes small tests where reuse does not help. Ascending the 1D loop does the same. And a large W blows memory before time; if W is huge and n small, memoisation or meet-in-the-middle is the right call.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

How do you collapse the 0/1 knapsack table to a single array? Walk me through what dp[w] means, why the capacity loop runs backwards for 0/1 items and forwards for unbounded, what breaks if you flip it, and the resulting complexity.

Answer

The 2-D state is dp[i][w] = best value from a subset of the first i items with capacity w, and the transition is dp[i][w] = max(dp[i-1][w], dp[i-1][w - wt[i-1]] + val[i-1]). Row i reads nothing but row i-1, so the whole table collapses to one array of length W+1: as long as the read of dp[w - wt[i]] still comes from the previous row. That is the entire trick; the loop direction is what enforces it.

The invariant to hold in your head: after the pass for item i, dp[w] equals the 2-D dp[i][w] for every w. Iterating w from W down to wt[i] gives you that, because dp[w - wt[i]] sits below w and descending order means it has not been written yet in this pass, so it still holds the item-(i-1) value. Iterating ascending writes dp[w - wt[i]] first, so the take branch reads a cell that already includes item i: the item can be used any number of times and you have silently solved the unbounded knapsack.

Python
def knapsack_01(wt, val, W):
    dp = [0] * (W + 1)
    for i in range(len(wt)):
        for w in range(W, wt[i] - 1, -1):   # descending: dp[w - wt[i]] is still the previous row
            dp[w] = max(dp[w], dp[w - wt[i]] + val[i])
    return dp[W]

def knapsack_unbounded(wt, val, W):
    dp = [0] * (W + 1)
    for i in range(len(wt)):
        for w in range(wt[i], W + 1):       # ascending: item i may be reused
            dp[w] = max(dp[w], dp[w - wt[i]] + val[i])
    return dp[W]

The two disagree on a two-item instance. wt = [2, 3], val = [3, 4], W = 6: the 0/1 optimum is both items for 7, the unbounded optimum is three copies of the 2-weight item for 9.

passw=0w=1w=2w=3w=4w=5w=6
start0000000
item 1 (wt 2, val 3), descending0033333
item 2 (wt 3, val 4), descending0034477
item 1, ascending (wrong)0033669
item 2, ascending (wrong)0034679

Three things follow from the collapse. dp[w] means best value with capacity at most w, not weight exactly w: a variant that demands an exact weight needs dp[0] = 0 and -inf everywhere else. The lower bound matters in Python: a bare range(W, -1, -1) lets dp[w - wt[i]] go negative and silently index from the end of the list, returning a plausible number instead of raising. And the single array reports the value, not the chosen set; recovering which items were taken costs the 2-D table back, a per-item choice bitmap of n*W bits, or a backward re-scan that re-derives each decision.

Time is unchanged at O(nW) and space drops from O(nW) to O(W). Both are pseudo-polynomial in W: with n = 50 and W = 10^9 that loop is never finishing, and the fix is meet-in-the-middle or a DP over total value at O(n * sum(val)).

In practice, name which variant you are solving before writing the loop, keep the explicit lower bound in the descending range, and test with an instance where reuse would win: that one case is what separates the two programs.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

Given an array of positive integers, can it be partitioned into two subsets with equal sum? Walk me through the 2-D DP state, the take/skip recurrence, base cases, where the answer is read, the complexity, and how you report that no equal partition exists.

Answer

Assume the elements are positive and the caller wants a yes/no; recovering the two subsets is a second pass. Let S = sum(a). If S is odd, answer no immediately: T = S/2 is not an integer and no partition can exist. Set T = S // 2, and also reject when max(a) > T, because that element cannot land in either half. Both checks are O(n) and they dispose of most inputs before a single cell is written.

State. dp[i][s] is True exactly when some subset of the first i elements sums to s. i is the prefix length (0..n), s runs 0..T. Two dimensions because the decision about element i-1 depends on both how far through the array you are and how much sum you still need.

Recurrence, take or skip.

dp[i][s] = dp[i-1][s]  or  (s >= a[i-1] and dp[i-1][s - a[i-1]])

Base row: dp[0][0] = True, dp[0][s] = False for s > 0. The answer is dp[n][T]. If you leave dp[0][0] False the entire table comes out False and you will spend an hour hunting a bug that isn't there.

Python
def can_partition(a):
    S = sum(a)
    if S % 2:                       # odd total: no equal partition
        return False
    T = S // 2
    if max(a) > T:                  # that element cannot fit in either half
        return False
    dp = [False] * (T + 1)
    dp[0] = True
    for x in a:
        for s in range(T, x - 1, -1):   # descending: dp[s-x] is still the previous row
            dp[s] = dp[s] or dp[s - x]
    return dp[T]

Trace for [1, 5, 11, 5], S = 22, T = 11: reachable sums after each element:

i=0  ()           -> 0
i=1  (1)          -> 0 1
i=2  (1,5)        -> 0 1 5 6
i=3  (1,5,11)     -> 0 1 5 6 11
i=4  (1,5,11,5)   -> 0 1 5 6 10 11

dp[4][11] is True; walking the decisions back gives {11} against {1, 5, 5}. That instance is 4 x 11 = 44 cell updates on the rolling array, or a 5 x 12 table if you keep every row.

Complexity. O(nT) time. The full table is (n+1)(T+1) booleans: O(nT) space, and it is what you want if the subsets must be reconstructed. Row i reads only row i-1, so one array of length T+1 suffices: O(T) space, at the cost of losing the reconstruction path. The descending s loop is what keeps dp[s-x] holding the previous row's value; ascending lets an element be used twice.

The family it belongs to. Give each element weight = value = a[i] and capacity T. The 0/1-knapsack optimum equals T exactly when a partition exists; the boolean table is the feasibility shadow of the max table, and the transition reads the same cell at the reduced index. That is why the rolling reduction carries over unchanged.

Failure modes. The ascending loop is the expensive one: [4, 6, 6] has S = 16, T = 8, max = 6 <= 8 so both pre-checks pass, and no subset sums to 8, but 4 + 4 does, so the unbounded version reports a partition that does not exist. Decide the empty-array convention up front: S = 0 gives T = 0 and dp[0] = True, i.e. two empty subsets. And report a miss as False (or a result object), not an exception: "no equal partition exists" is a normal answer, not an error.

Finally, this is pseudo-polynomial: the work tracks the numeric value of the sum, not the length of the input. n = 10^4 with S = 10^4 is about 5 x 10^7 updates: comfortable in C++ or Rust, slow in pure Python. n = 60 with S = 10^9 is 3 x 10^10 updates and will not finish; the problem is NP-complete in general, so at that scale you move to meet-in-the-middle over two halves of 2^(n/2) or an ILP/SAT solver.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

Explain interval dynamic programming on matrix chain multiplication: what is the state, what is the transition, and in what order do you fill the table?

Answer

Interval DP indexes a state by a contiguous range and splits that range at a point where the two halves stop interacting. Matrix chain multiplication is the textbook case.

Setup: n matrices, matrix i is dims[i-1] × dims[i], so dims has n+1 entries. Multiplying a p×q by a q×r costs p·q·r scalar multiplications, and the cost of a parenthesization is the sum over its merges. The result dimensions never change with the order: only the cost does.

State: dp[i][j] = the minimum number of scalar multiplications needed to compute the product M_i…M_j, 1-indexed, i ≤ j. Base case dp[i][i] = 0: a single matrix is already computed.

Transition: the last merge in computing M_i…M_j splits the range at some k with i ≤ k < j, producing (M_i…M_k)(M_{k+1}…M_j). The left factor is dims[i-1] × dims[k], the right is dims[k] × dims[j], so that final merge costs dims[i-1]*dims[k]*dims[j]:

dp[i][j] = min over i ≤ k < j of  dp[i][k] + dp[k+1][j] + dims[i-1]*dims[k]*dims[j]

The answer is dp[1][n].

Fill order: by increasing interval length L. Both dp[i][k] and dp[k+1][j] cover strictly shorter ranges than [i,j], so length order guarantees both are already computed. That dependency is the whole reason for the loop shape.

Python
# Python 3.12
def matrix_chain(dims):
    n = len(dims) - 1
    dp = [[0] * (n + 1) for _ in range(n + 1)]
    split = [[0] * (n + 1) for _ in range(n + 1)]
    for L in range(2, n + 1):            # interval length, short first
        for i in range(1, n - L + 2):
            j = i + L - 1
            best, best_k = float("inf"), -1
            for k in range(i, j):        # last merge splits at k
                cost = dp[i][k] + dp[k + 1][j] + dims[i - 1] * dims[k] * dims[j]
                if cost < best:
                    best, best_k = cost, k
            dp[i][j], split[i][j] = best, best_k
    return dp[1][n], split

Worked example: dims = [10, 30, 5, 60], so A1 is 10×30, A2 is 30×5, A3 is 5×60.

lengthcellvaluehow
2dp[1][2]150010·30·5
2dp[2][3]900030·5·60
3dp[1][3]4500k=2: 1500 + 0 + 10·5·60 = 4500, beats k=1: 0 + 9000 + 10·30·60 = 27000

So (A1A2)A3 costs 4500 and A1(A2A3) costs 27000: a 6× spread on three matrices, which is why greedy is not a shortcut.

Complexity: n(n+1)/2 states, and the split evaluations sum to Σ_{L=2..n} (n-L+1)(L-1) = n(n²-1)/6 ≈ n³/6. At n = 100 that is 166,650 inner iterations: trivial. Space is O(n²) for dp, plus another O(n²) for the split table if you want the parenthesization back. Unlike knapsack or edit distance, this table does not roll to one array or two rows: dp[i][j] reads every shorter interval, not just a previous row.

Traps worth naming. Filling row-major (i ascending, then j ascending) reads dp[k+1][j] from a row you have not written yet; with a zero-initialised table that silently returns too-small costs instead of crashing. Greedy "merge the cheapest adjacent pair first" is wrong: the example above already beats any adjacent-first rule. And the off-by-one in the merge cost is the most common bug: it is dims[i-1]*dims[k]*dims[j], with dims indexed one ahead of the matrices.

Burst Balloons transfers the shape directly. Pad nums with 1 at both ends; define dp[i][j] as the maximum coins from bursting every balloon strictly between i and j while i and j remain. Take k to be the last balloon burst in that interval: it is then flanked exactly by i and j, so it yields nums[i]*nums[k]*nums[j], and the rest splits into two independent open intervals:

dp[i][j] = max over i < k < j of  nums[i]*nums[k]*nums[j] + dp[i][k] + dp[k][j]

Same length-ascending fill, same O(n³) time and O(n²) space. The reason to define the split point as the last balloon rather than the first is precisely that the reward depends on the interval's boundary values: the first balloon's neighbours are whatever the original array had, which the state does not carry, while the last balloon's neighbours are the boundaries the state already holds.

How I'd check it: for n ≤ 8, enumerate all Catalan(n-1) parenthesizations and compare against dp[1][n]; assert dp[i][i] == 0 and dp[i][j] ≥ 0 everywhere; and sanity-check one hand-computed instance like the three-matrix one above before trusting the table.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

Count the palindromic substrings of a string with a 2-D DP and reuse the same table for the longest palindromic substring. Walk me through the state, recurrence, base cases, loop order, complexity, and when expand-around-centre is the better answer.

Answer

Start with the state, because the rest follows from it: dp[i][j] is true exactly when s[i..j] is a palindrome, for 0 <= i <= j < n. Only the upper triangle is meaningful.

The recurrence is one line:

Python
dp[i][j] = s[i] == s[j] and (j - i < 2 or dp[i + 1][j - 1])

The outer comparison is the two ends matching; the inner term says the middle is already known to be a palindrome. The j - i < 2 guard is the base cases: length 1 (i == j) is always a palindrome, and length 2 is a palindrome iff the two characters are equal. That guard is load-bearing, not stylistic. For length 2 it would otherwise read dp[i+1][j-1], which is dp[j][i], a lower-triangle cell you never fill, and every double letter like "aa" stops counting. For length 1 it indexes out of range. Python's short-circuit or is what keeps the code legal.

Loop order is the correctness-critical part: length outermost, then the left endpoint, so dp[i+1][j-1] (length L-2) is final when it is read.

Python
def palindromic_substrings(s: str):
    n = len(s)
    dp = [[False] * n for _ in range(n)]
    count, best = 0, (0, 0)
    for length in range(1, n + 1):
        for i in range(n - length + 1):
            j = i + length - 1
            if s[i] == s[j] and (j - i < 2 or dp[i + 1][j - 1]):
                dp[i][j] = True
                count += 1
                if j - i > best[1] - best[0]:
                    best = (i, j)
    return count, s[best[0]:best[1] + 1]

Iterating i ascending and j ascending reads a row that is still all False, so you silently count only lengths 1 and 2. On "aaa" that returns 5 instead of 6.

Counting: every true cell is one palindromic substring, identified by its bounds, so count = sum(dp[i][j] for i <= j). Longest: track max(j - i + 1) over the same true cells and keep (i, j). One pass answers both.

Worked trace, s = "abba", n = 4:

lengthtrue cellsrunning count
1(0,0) (1,1) (2,2) (3,3)4
2(1,2) "bb"5
3none5
4(0,3) "abba"6

Longest is (0,3), length 4. Note the count is by bounds: "aaa" has 6 palindromic substrings but only 3 distinct strings. If the question wants distinct strings, the DP supplies candidates and a set does the deduplication.

Complexity: O(n^2) cells at O(1) each, so O(n^2) time and O(n^2) space. Space is what decides the answer in practice. At n = 10^4 that is 10^8 cells: about 12.5 MB as a bitset in C++, 100 MB as boolean[][] in Java, and roughly 800 MB as a Python list of lists of bools (10^8 pointers at 8 bytes). In a managed runtime the table is realistic up to a few thousand characters.

Expand-around-centre is the better interview answer when you only need the count and the longest substring and memory or simplicity matters: 2n-1 centres, expand while the ends match, O(n^2) worst-case time, O(1) space, and no table to get wrong. The table earns its O(n^2) space only when callers also need O(1) is_palindrome(i, j) queries after preprocessing, or you must emit every palindromic substring. Push past that (n in the 10^5 range, or streaming input) and name Manacher: O(n) time, O(n) space, radii from which both answers fall out.

Failure modes worth naming: ascending-i loop order (undercounts length >= 3, survives small tests that only contain short palindromes); dropping the j - i < 2 guard (loses every double letter); and counting distinct strings when the question asked for substrings by position.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

How does matrix-chain multiplication change if the workload grows by two orders of magnitude?

Answer

Clarify first. "Two orders of magnitude" is ambiguous: 100x more matrices in one chain, or 100x more chains. If it's more chains, nothing changes: each chain's DP is independent, so you parallelize across chains and the per-chain cost is untouched. I'll assume the chain length n grows 100x, which is the case that actually hurts.

The DP is O(n³) time and O(n²) space, so n → 100n is 10⁶x time and 10⁴x space. Time breaks first, then memory.

The recurrence, and a trace.

Python
def matrix_chain(p):                      # p = [p0, p1, ..., pn]
    n = len(p) - 1
    m = [[0]*(n+1) for _ in range(n+1)]   # m[i][j] = min cost for A_i..A_j
    s = [[0]*(n+1) for _ in range(n+1)]   # s[i][j] = best split
    for L in range(2, n+1):               # interval length
        for i in range(1, n-L+2):
            j = i + L - 1
            m[i][j] = float('inf')
            for k in range(i, j):
                q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j]
                if q < m[i][j]:
                    m[i][j], s[i][j] = q, k
    return m, s

Run it on p = [10, 30, 5, 60], i.e. A1 is 10×30, A2 is 30×5, A3 is 5×60:

  • L=2, i=1, j=2, k=1: q = m[1][1] + m[2][2] + p[0]·p[1]·p[2] = 0 + 0 + 10·30·5 = 1500 → m[1][2]=1500, s[1][2]=1
  • L=2, i=2, j=3, k=2: q = 0 + 0 + 30·5·60 = 9000 → m[2][3]=9000, s[2][3]=2
  • L=3, i=1, j=3, k=1: q = m[1][1] + m[2][3] + p[0]·p[1]·p[3] = 0 + 9000 + 10·30·60 = 27000
  • L=3, i=1, j=3, k=2: q = m[1][2] + m[3][3] + p[0]·p[2]·p[3] = 1500 + 0 + 10·5·60 = 4500 → m[1][3]=4500, s[1][3]=2

Answer 4500, split at 2, i.e. (A1A2)A3. By hand: A1A2 is 10×5 at cost 1500, then (10×5)(5×60) at cost 3000. The other order costs 9000 + 18000 = 27000. The DP is doing exactly this comparison, once per interval per split.

Why cubic, and what 100x buys you. There are ~n²/2 intervals and ~n splits each, so ~n³/6 inner iterations.

nintervalsinner iterationscost table @8B+ split table
1005×10³1.7×10⁵80 KB160 KB
1,0005×10⁵1.7×10⁸8 MB16 MB
10,0005×10⁷1.7×10¹¹800 MB1.6 GB

At n=10,000 that's 1.7×10¹¹ inner iterations. At a nominal 10⁹ iterations/s that's ~3 minutes; each iteration does two dependent table lookups that miss cache at this size, so budget 10–100x that: tens of minutes to hours on one core.

Alternatives.

  • Cost only, no parenthesization: you still need the O(n²) cost table, but you can drop the split table and halve memory.
  • Hu–Shing gives the exact optimum in O(n log n), but it's intricate and rarely implemented; reach for it only if this is genuinely hot.
  • Approximate is acceptable: greedily multiply the pair with the smallest dimension product, O(n log n) with a heap. It can be suboptimal, so bound the loss on your own data before shipping it.
  • Parallelism: intervals of the same length are independent, so length L gives n−L+1-way parallelism. Up to O(n) early, collapsing to 1 at the last level. Keeping wall time flat under 100x work needs ~100x the cores, and the shrinking frontier caps the speedup.

Failure modes. Memory blow-up: the O(n²) table stops fitting in RAM somewhere in the low tens of thousands of n. Cache: m[i][k] and m[k+1][j] live in different rows and columns, so locality is poor and the miss rate climbs as the table outgrows L2/L3. Detect both by timing and RSS on a sweep of n and finding the knee; if n is past a few thousand, the plain DP is the wrong tool.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Given a filled 2-D DP table, how do you reconstruct one optimal solution from it, and what changes when you need every optimal solution, or only the value?

Answer

The table holds values, not answers. To recover one optimal solution you walk backwards from the terminal cell, and at every cell you take any predecessor whose transition cost plus that predecessor's value equals the current cell's value. That equality test is the entire rule; the rest is bookkeeping about where the predecessor's value comes from.

Take edit distance between horse and ros. The filled table ends at dp[5][3] = 3:

        ""  r  o  s
""       0  1  2  3
h        1  1  2  3
ho       2  2  1  2
hor      3  2  2  2
hors     4  3  3  2
horse    5  4  4  3

Backtrack from (5,3): dp[4][3] + 1 = 2 + 1 = 3, so delete e, move to (4,3). There dp[3][2] + 0 = 2 because s matches s, move to (3,2). There dp[2][2] + 1 = 2, delete r, move to (2,2). Match o to (1,1); substitute h→r to (0,0). Reversed, the script is substitute h→r, match o, delete r, match s, delete e: three edits, and replaying it costs exactly dp[5][3].

Python
# Python 3.12; dp is the filled (m+1) x (n+1) edit-distance table.
def backtrack(dp, a, b):
    ops, i, j = [], len(a), len(b)
    while i or j:
        if i and j and dp[i][j] == dp[i-1][j-1] + (a[i-1] != b[j-1]):
            ops.append("match" if a[i-1] == b[j-1] else f"sub {a[i-1]}->{b[j-1]}")
            i, j = i-1, j-1
        elif i and dp[i][j] == dp[i-1][j] + 1:
            ops.append(f"del {a[i-1]}"); i -= 1
        elif j and dp[i][j] == dp[i][j-1] + 1:
            ops.append(f"ins {b[j-1]}"); j -= 1
        else:
            raise AssertionError(f"no predecessor at {(i, j)}")
    return ops[::-1]

Two ways to get the predecessor. Re-derive it from the recurrence, as above: three comparisons per step, O(m+n) total, no extra space. Or store a choice table while filling (one small index per cell, O(mn) extra space) and the walk becomes pure lookup. Re-derivation is fine when a transition is a couple of arithmetic ops. It is not fine when the transition was an argmin over a range: re-scanning k = 0..i at every step turns an O(m+n) walk into O(n²), so store the argmin as you fill. And it is impossible once the table has been rolled to two rows: the predecessor's value is gone, so the equality test has nothing to compare against. That is the real price of the rolling-row reduction: you keep the value or the solution, not both, unless you store choices or split the problem (Hirschberg).

Ties: at (4,2) here both dp[3][1] + 1 and dp[3][2] + 1 give 3. The optimum value is unique; the optimal solution is not. Fix a priority order (match, substitute, delete, insert) and say so, otherwise the same input yields different scripts across runs and golden-file tests flake. If you need every optimal solution, never materialise them: the count can be exponential in m+n (all-equal grid paths), so walk the predecessor DAG lazily with DFS, or count solutions with a second DP over that DAG and enumerate on demand.

If you only the value is needed, skip all of this: two rolling rows, O(min(m,n)) space, no walk.

Failure modes worth naming: walking forward greedily, which commits to a locally cheap transition no optimal path uses; reconstructing against a rolled table; and a cost-convention mismatch where the replayed script disagrees with dp[m][n]. Assert the replay.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

When you reconstruct the optimal choices from a filled 2-D DP table, when do you re-derive the transition on the walk back instead of storing parent pointers, and what does each approach cost?

Answer

Re-deriving the transition on the walk back costs O(1) extra memory per cell and a constant factor of recomputation; parent pointers cost a whole second table but make the walk a pure pointer chase. The right choice turns on whether you kept the full table at all.

Mechanically, reconstruction walks from dp[m][n] backwards. Re-derivation re-evaluates the recurrence at each cell: for LCS, if a[i-1] == b[j-1] the cell must have come from the diagonal, otherwise you compare dp[i-1][j] against dp[i][j-1] and step toward the larger. No extra storage exists because the filled table already contains everything the recurrence needs. Parent pointers instead record, at fill time, which predecessor produced each cell, an m×n table of two-bit directions, and the walk back just follows them.

Python
# LCS reconstruction by re-derivation, table already filled (m+1) x (n+1)
i, j, out = m, n, []
while i > 0 and j > 0:
    if a[i-1] == b[j-1]:            # forced: only the diagonal explains this cell
        out.append(a[i-1]); i -= 1; j -= 1
    elif dp[i-1][j] >= dp[i][j-1]:  # tie broken upward arbitrarily
        i -= 1
    else:
        j -= 1
''.join(reversed(out))

The failure this invites is specific: re-derivation silently assumes the walk-back test matches the fill-time recurrence exactly. If the table was filled with a different tie-break, or the recurrence had a third branch (edit distance has insert, delete, and replace), a cell can satisfy the test for a predecessor that did not actually produce it: the reconstructed sequence is still optimal in length, but it is not a sequence the table's own history supports, and with weighted costs it can be outright wrong. It survives casual testing because any valid optimal answer passes a length check; only diffing two reconstructions exposes it. Parent pointers cannot drift this way, which is their real argument, not speed.

The trade-off is concrete. Parent pointers add an (m+1)×(n+1) table: for two 100k-character sequences that is 10^10 cells, which is why reconstruction-by-re-derivation is the default when the table is kept and the only option once it has been rolled to two rows. But re-derivation is incompatible with rolling: a two-row edit distance no longer holds dp[i-1][j-1] when you need it, so if you must both roll memory and reconstruct, you re-run the DP over shrinking subproblems (the Hirschberg trick) or checkpoint rows. Ties deserve a stated policy: every tie-break yields a different but equally optimal answer, so pick one at fill time and reuse the identical comparison on the walk back.

In practice, re-derive when the full table is retained and the recurrence is cheap to re-evaluate; store parents when the recurrence is expensive, has many branches, or the walk must be reproducible bit-for-bit across runs. The senior answer stays conditional rather than absolute: establish that the walk-back test mirrors the fill-time recurrence first, and treat the memory figures, not the style, as the deciding measurement.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

In a 2-D DP over a large sparse state space, when does top-down memoisation stop being the convenient choice, and what are the concrete remedies?

Answer

Assume Python 3.14 with functools.lru_cache, and a state like dp[i][j] where i runs to 2,000 and j to 2,000 but only a few percent of that rectangle is ever reachable. Top-down is the convenient choice while three things hold: the dependency chain is shallower than the recursion limit, the reachable set fits as a hash cache, and states get re-read often enough to pay for the cache. When one of those breaks, memoisation is not wrong: it is expensive in a way that shows up at runtime, not in the analysis.

Depth. A grid recurrence recursing on (i+1, j) and (i, j+1) nests up to i+j frames deep. On a 2,000 x 2,000 grid that is 4,000 frames against CPython's default limit of 1,000 (sys.getrecursionlimit). You get a clean RecursionError. sys.setrecursionlimit(10_000) moves the Python-level limit, but the C stack underneath is still finite and the docs warn that too high a limit crashes the interpreter: a segfault, not an exception you can catch. Raising the limit is a stopgap for depth 1,500, not a fix for depth 100,000.

Cache cost. A memo entry is a hashed tuple key in a dict; a table entry is one pointer slot in a preallocated list.

lru_cache dictdense dp[n][m]
lookuphash + probe, O(1) averageindex arithmetic, O(1)
per state~100 B (tuple key + slot + int)8 B slot (+ int object)
10^6 states~100 MB~8 MB plus the ints
unreachable statesnot allocatedallocated
call framesone per recursion levelnone

Byte figures are order-of-magnitude for 64-bit CPython; measure your own workload. The dict also defeats prefetch: every lookup is a pointer chase to a scattered address.

Retention. maxsize=None keeps every state computed until the function object dies. States visited once and never re-read still occupy memory. The converse trap is just as real: bottom-up over the full rectangle allocates n*m slots for states that are never reached, which is exactly the memory the sparse problem was supposed to save.

Remedies, in the order I reach for them:

  1. Iterative fill over a topological order of the reachable states. BFS the reachable set first, order it, then fill with a dict or an index-compressed array. Keeps the sparsity, drops the frames and the per-call hashing.
  2. Bottom-up tabulation when the state space is dense and the fill order is plain nested loops: contiguous lists, no hashing, predictable memory.
  3. State pruning. Band the second index (|i-j| <= k), dominance, bounding: cut the reachable set before choosing an implementation.
  4. Bounded cache. lru_cache(maxsize=...) never returns a wrong answer, but a bad eviction pattern turns O(states) into exponential recomputation. Watch the hit rate.

The failure I'd inject: convert to bottom-up "for speed" on a sparse problem and OOM, where the memo cache fit comfortably. The second is shipping a raised recursion limit and getting a segfault under a deeper input.

In practice, measure reachable-state count and maximum dependency depth before choosing. Depth past ~1,000 or a reachable set too large for a hash cache means go iterative; a dense rectangle means go tabular.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

When is top-down memoization preferred over bottom-up tabulation in 2-D DP, and how does sparsity in the state space change memory and time complexity?

Answer

Both compute the same recurrence; the only difference is which states get visited and what the call machinery costs. Bottom-up fills every cell in a fixed loop order. Top-down computes a state only when the recurrence reaches it. That decides the choice.

Top-down wins when the reachable set is a small or irregular subset of the grid. 0/1 knapsack with 10 items, weights in the hundreds, capacity 100,000. The table is 10 × 100,001 cells. From (10, 100000) the recursion only lands on capacities of the form 100000 minus a subset sum of the remaining items, so at level i there are at most 2^(10−i) distinct capacities, and the total reachable set is at most sum over k = 0..10 of 2^k = 2,047 states: usually fewer, since subset sums collide. Bottom-up touches 10^6 cells; top-down touches about 2,000.

Python
# Python 3.12
from functools import lru_cache

@lru_cache(maxsize=None)
def knap(i, cap):
    if i == 0:
        return 0
    best = knap(i - 1, cap)                          # skip item i
    w, v = items[i - 1]
    if w <= cap:
        best = max(best, knap(i - 1, cap - w) + v)   # take item i
    return best

Time is O(reachable states × branching): here roughly 4,000 calls against 10^6 inner iterations. Memory is O(reachable states) for the cache plus O(depth) for the stack. Depth here is at most m + 1 = 11, because i strictly decreases on every call, so there is no recursion-limit problem. Grid recurrences are different: edit distance recurses m + n deep, and a DP that walks one coordinate at a time goes as deep as that coordinate's range. That is where CPython's default limit of 1000 bites, not the cache.

The memory comparison is not the one people assume. Bottom-up knapsack does not need the full table: iterating capacity downward over a single array of cap + 1 ints gives the same answer in O(cap) memory. So:

Bottom-up, full tableBottom-up, rolling arrayTop-down, sparseTop-down, dense
States10^610^6~2,00010^6
Memory8 MB800 KB~200 KB + stack~100 MB + stack
Per statearray storearray storetuple key, dict lookup, framesame

A cached entry costs roughly 100 bytes in CPython (tuple key, two int objects, dict slot) against 8 bytes per array slot: about 12×. So the cache wins on memory only while reachable states stay under roughly cap/12; past that the rolling array is smaller and the cache is strictly worse. The sparsity win is mostly time.

Dense state spaces. Edit distance on two 1,000-character strings: every (i, j) pair is reachable, 10^6 states. Top-down pays a cached call per state: tuple construction, dict lookup, frame setup, an order of magnitude above an array store, and holds ~100 MB of cache. Bottom-up holds two rows of 1,001 ints, 16 KB, and does 10^6 array stores. Top-down buys nothing on state count and loses on both axes.

The second real advantage: dependency order. Bottom-up forces you to find a loop order where every dependency is already filled. For interval DP (matrix chain) that is diagonal by diagonal and easy to get wrong; top-down cannot have a cycle problem because it only returns once its children have. When the order is subtle, or the state space is defined by reachability rather than index ranges (digit DP, DP over subsets), top-down is the safer formulation. It also lets you prune: a bound check at the top of the function skips whole subtrees, which bottom-up cannot do.

When not to use it: dense state spaces, deep recursions where the stack dominates, and hot paths you want to vectorize. Bottom-up maps onto numpy or a GPU, a memoized recursion does not.

The standard hybrid: keep the top-down formulation as the specification, test it against small inputs, then port to bottom-up once the loop order is known. Same recurrence, same answers.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

What is the smallest experiment that would change your mind about recursion depth in two dimensions?

Answer

The experiment

Instrument the recursion to record the deepest frame it reaches, run it at three sizes, and read the slope. That one number decides the question: if peak depth grows one-for-one with input size, top-down is depth-limited and you switch to iteration; if it grows logarithmically or plateaus, recursion is safe and you keep it.

Python
import sys

def peak_depth(m, n):
    peak = 0
    def rec(i, j, d):
        nonlocal peak
        peak = max(peak, d)
        if i == 0 and j == 0:
            return 1
        if i == 0:
            return rec(i, j - 1, d + 1)
        if j == 0:
            return rec(i - 1, j, d + 1)
        return rec(i - 1, j, d + 1) + rec(i, j - 1, d + 1)
    rec(m, n, 1)
    return peak

print(sys.getrecursionlimit())                 # 1000
for m, n in ((10, 10), (100, 100), (500, 500)):
    print(m, n, peak_depth(m, n))

Trace the (10,10) case by hand. rec(10,10,1) records depth 1 and calls rec(9,10,2). That branch keeps decrementing i until rec(0,10,11), which records 11 and hands off to rec(0,9,12). From there j walks down to rec(0,0,21). Peak is 21 = m + n + 1. The (100,100) case prints 201. The (500,500) case never prints: its chain needs 1001 frames and the default limit is 1000, so it raises RecursionError.

That is the result that changes the decision. Depth is the longest dependency chain, not the number of states. Each call depends on (i-1,j) and (i,j-1), so the deepest path decrements one coordinate at a time and visits m + n + 1 frames. A 5,000×5,000 grid needs 10,001 frames; the default limit is crossed at roughly 500×500. The exact constant depends on where the base case sits: an LCS-style recurrence that stops at i == 0 or j == 0 has a longest chain of max(m,n)+1, not m+n+1, but the slope is 1 either way, and the slope is what the experiment is testing.

What does not fix it

sys.setrecursionlimit(10_000) moves the failure rather than removing it. CPython's recursion limit is a guard in front of the C stack; raise it far enough and the process segfaults instead of raising a catchable exception. Memoisation does not help either: it cuts the number of calls, but the first evaluation of (m,n) still walks the full chain, so peak depth is unchanged.

What does

Bottom-up tabulation fills the table row by row with no call stack, and rolling two rows keeps space at O(min(m,n)). If you need to keep the top-down shape, drive it with an explicit stack you own, which puts the depth on the heap where it is bounded by memory rather than by the C stack.

So the experiment is three lines of instrumentation and a slope. Linear slope: rewrite iteratively. Flat or logarithmic: leave it alone.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

Memory is the binding constraint on a 2-D DP: how do you decide which dimension to roll away, which loop direction keeps the surviving row valid, and when must you keep the full table?

Answer

A 2-D table can be rolled whenever the dependency band is one row wide: every cell reads only the current and previous value of the other index. Keep the axis the recurrence reads backwards from, roll the other one, and when both axes are rollable keep the shorter one so the surviving array is O(min(m,n)). Rolling buys memory only: the time is still O(mn).

For LCS and edit distance a cell reads dp[i-1][j], dp[i][j-1] and dp[i-1][j-1]. That is one array of size n+1 plus a scalar holding the diagonal before it gets overwritten. The direction is forced, not stylistic: i outer, j inner ascending, because dp[i][j-1] must already hold this row's value when you read it.

Python
def lcs_len(a, b):
    if len(b) > len(a):
        a, b = b, a                    # keep the shorter axis
    row = [0] * (len(b) + 1)
    for x in a:
        diag = 0                       # dp[i-1][j-1]
        for j, y in enumerate(b, 1):
            above = row[j]             # dp[i-1][j], not yet overwritten
            row[j] = diag + 1 if x == y else max(row[j], row[j - 1])
            diag = above
    return row[-1]

0/1 knapsack is the same move along the item axis. dp[w] means best value at capacity w using the items seen so far, and w runs from W down to w_i so that dp[w - w_i] is still the previous item's row. Run it forwards and the item can be taken twice: the table silently becomes the unbounded knapsack. Space drops from O(nW) to O(W).

ProblemFull tableRolledDirection that keeps it validWhat you lose
LCS / edit distanceO(mn)O(min(m,n))i outer, j ascendingthe path
0/1 knapsackO(nW)O(W)w descending per itemwhich items were taken
Interval DP (matrix chain, palindromes)O(n^2)nonelength ascendingband is O(n) wide

What you give up is the walk-back. Reconstruction follows the argmin or argmax from dp[m][n]; a rolled array leaves only the last row. The escapes each cost something. Hirschberg's divide and conquer keeps O(min(m,n)) space and roughly doubles the work with two passes per level. Checkpointing every k rows costs O(kn) memory and a recompute per block. Per-cell decision arrows are O(mn) bits: a smaller constant, not a better bound.

Keep the full table when the dependency band is wider than one row: interval DPs such as matrix chain or palindrome tables read dp[i][k] and dp[k+1][j] for every k, so there is nothing to roll. Keep it when the answer path is the deliverable and you will not pay Hirschberg's constant, when the table is queried after the run (prefix/suffix or range questions), or when you want to dump it during an incident.

The failure modes are directional. Flipping the knapsack loop passes tests where each weight is large relative to W and fails where items are small. Choosing the longer axis because the loop reads more cleanly costs O(max) instead of O(min): at m = 100,000 and n = 100 that is 1000x the memory. And reconstructing greedily from the recurrence after rolling yields a path that is optimal in cost but may not be the one the spec wants once ties are broken differently.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

How does index conventions interact with rollback, and where do people ignore that?

Answer

Read the question as: how index naming and creation conventions in schema migrations interact with rollback, the down path, and where teams get burned. Two conventions decide it: how the index name is derived, and whether the index is built concurrently.

The answer: a rollback drops an index by name. When that name is derived by convention rather than written into the migration, the convention becomes part of your rollback contract. Change the convention, rename a column, or add a naming_convention later, and the down migration either fails with "index does not exist" or (worse, in a shared schema) drops a same-named index belonging to another table.

Mechanism. Rails derives index_<table>_on_<column>, joining composite columns with _and_. Alembic applies no convention at all unless you set MetaData(naming_convention=...); the recipe in its docs is ix_%(column_0_label)s. Postgres requires index names to be unique per schema, not per table, so any convention keyed on the column alone collides as soon as two tables share a column name.

The concurrent case is where rollback actually breaks. CREATE INDEX CONCURRENTLY cannot run inside a transaction block. Rails wraps each migration in a transaction by default, so you need disable_ddl_transaction!; Django needs atomic = False; Alembic needs autocommit_block(). Without that, the migration errors before it does anything. And a concurrent build that fails partway leaves an INVALID index behind: it still occupies its pages and still has to be dropped, and DROP INDEX CONCURRENTLY also cannot run in a transaction.

ConventionWhat it does to rollback
Auto-derived nameDown migration must reproduce the derivation; a column rename makes the drop miss
Explicit name in the migrationSurvives renames; two migrations can still pick the same name
CREATE INDEX CONCURRENTLYNot allowed in a transaction; a failed build leaves an INVALID index
Plain CREATE INDEX / DROP INDEXTakes ACCESS EXCLUSIVE on the table: writes block for the duration
Unique constraint (not unique: true index)DROP INDEX refuses; you must drop the constraint
RUBY
# Rails 7.x
class AddEmailIndexToUsers < ActiveRecord::Migration[7.0]
  disable_ddl_transaction!  # CREATE INDEX CONCURRENTLY cannot run in a transaction

  def up
    add_index :users, :email, name: "ix_users_email", algorithm: :concurrently
  end

  def down
    execute "DROP INDEX CONCURRENTLY IF EXISTS ix_users_email"
  end
end

Where people ignore it. Three places, all common:

  1. The down migration drops by derived name, and someone later renames the column or introduces a naming convention. Staging fails loudly; production, where the old index still exists under the old name, fails quietly or drops the wrong object.
  2. The down path rebuilds the index non-concurrently. Rolling back a migration that dropped a 200 GB index re-creates it with a plain CREATE INDEX, taking a write lock on a table that was healthy a minute earlier.
  3. A unique index created via add_index unique: true is droppable; the same uniqueness declared as a constraint is not. Teams discover this during an incident, not in review.

Decision criterion. Ask whether the index name is a contract or an implementation detail. If rollback has to run unattended, write the name explicitly and keep both directions concurrent. If you can take a maintenance window, derived names and plain CREATE/DROP are simpler and the convention can stay implicit.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

When can a 2-D DP transition be accelerated with a monotonic deque, and how do you argue the optimisation preserves the exact optimum? What is the structural condition on the transition, how is the deque maintained across one dimension, and what counterexample shows it is invalid?

Answer

Two structural conditions, and both have to hold before a deque is legal.

The candidate set is a contiguous window of previous-row states whose endpoints move monotonically. The transition must be writable as

dp[i][j] = C(i, j) + min over k in [L(j), R(j)] of dp[i-1][k]

with L(j) and R(j) non-decreasing in j. Contiguous means the live candidates form an interval of k; monotone endpoints mean that advancing j only adds candidates at the right and expires them at the left. If the transition filters candidates by a j-dependent predicate, "only k where a[k] < a[j]", the live set is not an interval and front-eviction is wrong.

Dominance between candidates must not change as j advances. In the form above the minimised value dp[i-1][k] does not depend on j at all, so if k1 < k2 and dp[i-1][k1] <= dp[i-1][k2], then k2 can never be the answer while k1 is alive: k1 is both cheaper and expires later. That is the licence to throw k2 away. When the transition is dp[i-1][k] + W(k, j), you need the argmin to be non-decreasing in j, the Monge / quadrangle-inequality condition, or the deque is invalid.

Mechanics: the deque holds indices k of the previous row, with dp[i-1][k] increasing front to back. Per j: push k = j-1 at the back, popping the back while its value is >= the newcomer's (dominated for every future j); then pop the front while its index is < L(j) (expired). The front is the argmin over the live window. Each index is pushed once and popped at most once, so a row costs O(n) instead of O(nW) and the table drops from O(nmW) to O(nm).

Python
# Python 3.12
from collections import deque

def slide(prev, cost, W):
    """cur[j] = cost[j] + min(prev[k] for k in [j-W, j-1]); j == 0 is a base case."""
    n = len(prev)
    cur = [0] * n
    dq = deque()                      # indices k, prev[k] increasing front -> back
    for j in range(n):
        k = j - 1                     # newest state that enters the window
        if k >= 0:
            while dq and prev[dq[-1]] >= prev[k]:
                dq.pop()              # dominated for every future j
            dq.append(k)
        while dq and dq[0] < j - W:
            dq.popleft()              # expired: no future j can see it
        cur[j] = cost[j] + (prev[dq[0]] if dq else 0)
    return cur

Trace with W = 2, prev = [3, 1, 4, 1, 5], cost = 0:

jlive window kdeque after stepwindow mincur[j]
0— (base case)[ ]—0
1{0}[0]33
2{0,1}[1]11
3{1,2}[1,2]11
4{2,3}[3]11

Why the optimum survives: the invariant is that after the pops the deque holds exactly the live window's indices in increasing value order, so the front is the true window min. Nothing is discarded that could still win. The back pop drops k2 only when an equal-or-better k1 with a later expiry is already queued; the front pop drops only indices no future j can see. The recurrence is untouched: only its evaluation cost fell.

Where it breaks. Take dp[i][j] = min over k of (dp[i-1][k] + (k - j)^2) with two candidates: k = 0 with dp = 0, k = 10 with dp = 5. At j = 0: 0 + 0 = 0 versus 5 + 100 = 105, so k = 0 wins. At j = 20: 0 + 400 = 400 versus 5 + 100 = 105, so k = 10 wins. The winner flips. A deque that keeps the smaller raw dp value and discards k = 10 returns 400 where the optimum is 105. The window is fine here, every k is live, it is the dominance relation that fails. The fix is a different structure: convex hull trick for this quadratic, divide-and-conquer DP when you can prove the argmin is monotone but cannot express the pops.

Failure modes worth naming. Rolling the table to one array and pushing dp[j] after it has been updated mixes row i into a deque that must hold only row i-1; it is silently wrong and only randomised comparison against the O(nmW) brute force catches it. Off-by-one in L(j) (admitting k = j, or dropping k = j - W) shows up immediately at W = 1. Ties: >= keeps the newest index, > keeps the oldest; the values agree, the reconstruction does not.

When not to bother: if the transition is already O(1) there is nothing to win, and if W is a small constant the deque's bookkeeping can cost more than the loop it replaces. State the invariant and prove the dominance rule before writing the deque: that proof is the answer, the code is transcription.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

What trade-off does hirschberg's reduction force that a junior answer usually skips?

Answer

The trade-off: roughly 2x the time to buy linear space. Hirschberg keeps Needleman–Wunsch's O(mn) time but pays about double the constant factor, dropping memory from O(mn) to O(min(m,n)). A junior answer says "it saves memory" and stops; the senior answer names what that memory costs and when the trade is wrong.

Where the 2x comes from. To align A[1..m] with B[1..n], the recursion runs two passes over the full B: forward scores for A[1..m/2] against all of B, backward scores for A[m/2+1..m] against all of B. Each pass is O(mn/2), so the split costs O(mn), one full table's worth, then you recurse on two half-size subproblems:

T(m,n) = 2·T(m/2, n/2) + O(mn).

Level k has 2^k subproblems of size (m/2^k, n/2^k) costing mn/4^k each, so mn/2^k per level; summing the geometric series over log m levels gives 2mn.

Why the split point is exact, not a heuristic. Any optimal alignment path from (0,0) to (m,n) crosses the middle row of A at exactly one column j. The forward pass gives the best score to reach (m/2, j); the backward pass gives the best score from (m/2, j) to (m,n). The j maximizing the sum lies on some optimal path, so the halves solve independently.

Code (Python 3.11):

Python
def row(a, b):
    """Edit distance from a to every prefix of b."""
    prev = list(range(len(b) + 1))
    for i, ca in enumerate(a, 1):
        cur = [i]
        for j, cb in enumerate(b, 1):
            cur.append(min(prev[j] + 1,                    # delete
                           cur[j - 1] + 1,                 # insert
                           prev[j - 1] + (ca != cb)))      # match/sub
        prev = cur
    return prev

def split(a, b):
    """Column j where an optimal path crosses the middle row of a."""
    mid = len(a) // 2
    fwd = row(a[:mid], b)                       # fwd[j] = d(a[:mid], b[:j])
    bwd = row(a[mid:][::-1], b[::-1])[::-1]     # bwd[j] = d(a[mid:], b[j:])
    return min(range(len(b) + 1), key=lambda j: fwd[j] + bwd[j])

def align(a, b):
    if not a: return [('ins', c) for c in b]
    if not b: return [('del', c) for c in a]
    if len(a) == 1:
        c = a[0]
        if c in b:
            k = b.index(c)
            return [('ins', x) for x in b[:k]] + [('match', c)] + [('ins', x) for x in b[k+1:]]
        return [('sub', c, b[0])] + [('ins', x) for x in b[1:]]
    j = split(a, b)
    mid = len(a) // 2
    return align(a[:mid], b[:j]) + align(a[mid:], b[j:])

Worked trace. Edit distance (match 0, substitution/insert/delete 1), A = "AGCT", B = "ACT". Split A after row 2:

j0123
fwd: d("AG", B[:j])2112
bwd: d("CT", B[j:])1012
sum3124

Minimum at j=1, so "AG" pairs with "A" and "CT" pairs with "CT". Recurse: "AG" vs "A" splits at j=1 into "A"/"A" (0) and "G"/"" (1); "CT" vs "CT" splits into "C"/"C" and "T"/"T" (0 each). Total distance 1, delete the G, matching the full-table answer.

The arithmetic. For 10,000 × 10,000 with 4-byte cells: full table 10^8 cells × 4 B = 400 MB. Hirschberg holds two rows of length n: 2 × 10,000 × 4 B = 80 KB. Cell updates go from ~10^8 to ~2×10^8. You trade 2x time for a 5,000x memory cut.

Failure modes.

  • Time-bound workloads. If the DP already dominates runtime and memory isn't the constraint, Hirschberg makes it worse. Detect by profiling: if peak RSS is far below the table size, you didn't need it.
  • Split-point bugs. An off-by-one in the split column yields a suboptimal alignment that still looks plausible. Detect by comparing the score against a full-table DP on small inputs in tests.
  • Cache effects. Both passes are row-wise and cache-friendly, so 2x the operations is often less than 2x wall-clock. Measure rather than assume.

When not to use it. If the table fits in memory, use it: simpler and half the time. If you need only the score, use rolling-row DP: O(min(m,n)) space, O(mn) time, no doubling. Hirschberg is for when you need the alignment and memory is tight. If the alignment is near-diagonal, banded DP (band width k) is O(mk) time and space and beats both.

Curated: · Written: · Reviewed:

Difficulty: Hard