Q&A-1Explain the two conditions for dynamic programming and how it changes a production decision.
Answer
Two conditions, and they do different jobs. Optimal substructure: the best answer to the whole problem is assembled from best answers to subproblems. That is what makes a recurrence correct. Overlapping subproblems: the naive recursion reaches the same state many times. That is what makes caching worth it. The first is a correctness property, the second is a cost property. You can have the first without the second, and then DP is correct but pointless.
The production decision is rarely "should I use DP". It is "does the state space fit the budget". Take a fuzzy-match endpoint that scores how close two strings are with edit distance. States are (i, j): prefix i of the source against prefix j of the target. Overlap is real: the naive recursion reaches d[i][j] along exponentially many distinct paths, so the table computes each cell once instead of re-deriving it. Optimal substructure holds: d[i][j] is the minimum of three neighbours plus a cost.
Trace it on "cat" vs "cut":
| "" | c | u | t | |
|---|---|---|---|---|
| "" | 0 | 1 | 2 | 3 |
| c | 1 | 0 | 1 | 2 |
| a | 2 | 1 | 1 | 2 |
| t | 3 | 2 | 2 | 1 |
Each cell is min(d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1] + (s[i]==t[j] ? 0 : 1)). The diagonal is free when the characters match, which is why d[1][1] is 0 and d[3][3] is 1: one substitution turns "cat" into "cut".
Now the decision. 200-character strings are 40,000 cells; at 4 bytes each that is 160 KB and a few hundred microseconds of work. 10,000-character strings are 100 million cells: 400 MB per request, and roughly a second of cell updates. That is the moment DP stops being a free win: you either cap the input at, say, 512 characters, or switch to a banded DP that fills only a diagonal strip of width k, or drop to a cheaper heuristic. The two conditions told you the recurrence was right; the arithmetic tells you whether you can afford it.
Two failure modes worth naming. First, no overlap: a tree walk where each node is visited once. The memo table never hits, and you have added a hash lookup per node for nothing. Detect it by instrumenting the cache: hit rate near zero on real traffic. Second, no optimal substructure: longest simple path in a graph with cycles. The recurrence looks fine, the answers are wrong, and it survives testing because small acyclic inputs happen to work. Detect it with a brute-force reference on small inputs, or by checking that your state captures everything the future depends on.
So: state both conditions, then price the state space. If the table fits, DP is usually the simplest correct thing. If it does not, the conditions being satisfied does not help you.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.