Overview
Curated: · Written: · Reviewed:
2-D Dynamic Programming
In one line
Use a second index when one index cannot capture what the answer depends on: a prefix of each of two sequences, a remaining budget or capacity, or a range. Reach for it when a one-dimensional state loses information the transition needs.
Key definitions
- State: the subproblem a cell answers, written as one sentence before any code.
- Prefix convention: dp[i][j] covers the first i characters of a and the first j of b, so the table is (m+1) x (n+1) and row 0 and column 0 are base cases.
- Transition: the recurrence that combines predecessor cells. For 0/1 knapsack it is take-or-skip.
- Rolling rows: keeping only the previous row when a row depends only on the one before it.
- Hirschberg: linear-space alignment by divide and conquer over a forward and a backward pass.
- Monotone split: an optimal split point that never moves backwards, which permits a narrowed search.
Formulas and complexity
How it works
- Write the subproblem as a sentence. Its dimensions give the table, and the table gives the memory.
- Fill the base row and column with the operator's base values: prefix lengths for edit distance, 1s for grid counts, infinity for a minimum.
- Each cell combines its predecessors. A match extends the diagonal; otherwise the cell takes the better neighbour.
- Fill in dependency order: row by row for prefixes, by increasing length for ranges. Collapsed 0/1 knapsack iterates capacity downward.
- Read the answer at the cell the sentence names, usually the bottom-right. Reconstruct by walking back from it.
When to use and when not to
| Situation | Use 2-D DP | Prefer instead |
|---|---|---|
| Two sequences, alignment or score | Yes, O(mn) | Nothing cheaper in general |
| Budget with exact weights, small capacity | Yes, index by remaining capacity | Index by value when weights are huge: dp[v] = minimum weight reaching value v |
| Only the longest palindrome | No | Expand around centres: O(n^2) time, O(1) space |
| Few reachable states in a large space | Dict memo | Dense table wastes memory |
| Alignment needed, memory tight | Hirschberg | Full table exceeds the budget |
Traps interviewers probe
- Zero as the base of a minimum. Zero is the identity for addition, so every cell comes out zero. Fix: initialise with infinity and set dp[0][0] to the entry cost.
- Blocked border cells. Skipping only the obstacle leaves later border cells reachable. Fix: break the border loop at the first obstacle.
- Upward capacity loop after collapsing. Items get reused and 4 + 4 = 8 passes for items {4, 6}. Fix: iterate capacity downward for 0/1, or read the previous row in the two-row version.
- Wrong answer cell. Returning dp[m-1][n-1] for LCS('ABC', 'AC') gives 1 instead of 2. Fix: return dp[m][n] under the prefix convention.
- Wrong order for ranges. Iterating by left endpoint reads uncomputed sub-ranges. A palindrome loop that ascends i reads row i+1 before it is filled and reports 8 instead of 9 for 'aabaa'. Fix: loop by length, or descend i.
Interview tips
Open by naming the subproblem: 'dp[i][j] is the best value over the first i of a and the first j of b.' Then state the recurrence, base cases, fill order, answer cell, and complexity.
Follow-ups to expect:
- Can you cut the memory? Rolling rows keep the value but discard the alignment. Hirschberg keeps the alignment in linear space.
- Why is top-down risky here? Depth grows with m + n. CPython's default limit of 1,000 raises RecursionError for 4,000 x 6,000.
- Does weighted edit distance stay symmetric? Not with asymmetric costs, so cache by the ordered pair, not frozenset.
- Can you use the monotone optimisation? Only after verifying the split point is monotone, then testing against the plain DP.
- Are the reconstructed sequences unique? Not under ties. Assert the value and the validity of the output.
30-second outline: 'dp[i][j] is the best result over the first i of a and the first j of b. It takes the diagonal on a match and the better neighbour otherwise. Base cases are the prefix lengths. I fill row by row and read dp[m][n]. Time and space are O(mn). If only the value is needed, two rows bring space to O(n). If the alignment is needed, I keep the table or use Hirschberg.'
Feedback on this overview
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.