Overview
Curated: · Written: · Reviewed:
1-D Dynamic Programming
In one line
Dynamic programming answers an optimum or count by defining one state per index, writing a transition over the last decision, and computing each state once. Reach for it when subproblems overlap and their answers combine into the full answer.
Key definitions
- State: the smallest set of parameters that determines the rest of the solution. Write it as an English sentence before any code.
- Transition: the exhaustive, non-overlapping enumeration of the last decision.
- Base case: the value of every state reachable without recursing. Impossible states get a sentinel such as negative infinity, not zero.
- Optimal substructure: the optimum is built from subproblem optima.
- Ending-here versus best-so-far: the value the recurrence extends versus the value the answer reports.
- Pseudo-polynomial: running time polynomial in the numeric value of an input, such as O(nW) for knapsack.
Formulas and complexity
How it works
Worked example: house robber, where no two adjacent houses can both be robbed. The state is dp[i], the best total over the first i houses. Skipping house i-1 inherits dp[i-1]. Robbing it adds a[i-1] to dp[i-2], because house i-2 is then forbidden. Base cases are dp[0] = 0 and dp[1] = a[0].
Trace on a = [2, 7, 9, 3, 1]:
- dp[2] = max(2, 7) = 7
- dp[3] = max(7, dp[1] + 9 = 11) = 11
- dp[4] = max(11, dp[2] + 3 = 10) = 11
- dp[5] = max(11, dp[3] + 1 = 12) = 12
The answer is 12, from robbing houses 0, 2 and 4.
Knapsack has a different take branch. Taking item i-1 adds its value to dp[i-1] at capacity W minus the item's weight, not to dp[i-2]. Do not reuse the house-robber shape for it.
Fill the table in dependency order. Recurrences that look backward fill upward; recurrences that look forward fill downward. Memoisation visits only reachable states but recurses to the depth of the dependency chain.
When to use and when not to
| Situation | Choice | Reason |
|---|---|---|
| Overlapping subproblems and optimal substructure | Dynamic programming | Cache hits and exact answers |
| A provable local rule (exchange argument) | Greedy | Cheaper and correct for that problem only |
| Every configuration must be listed | Backtracking | The answer is the enumeration itself |
| Overlap exists but optimal substructure does not | Neither as stated | Recurrence is wrong, cache only hides it |
| Caller needs the chosen items | Keep a decision per state | A rolled-up row cannot be walked back |
| State product too large for memory | Redesign the state | Compute the size before coding |
Traps interviewers probe
- Zero as the base for an impossible state. Every amount looks reachable. Use a sentinel for unreachable states. For counting, the empty solution is 1, so dp[0] = 1.
- Kadane's initialised at zero. An all-negative array returns 0, but no empty subarray is allowed. Start from a[0] and test an all-negative input.
- Reporting the ending-here value. That is the best subarray ending at the last element. Track best separately and return it.
- Wrong loop nesting. Coins outermost counts combinations. Amounts outermost counts permutations. In 1-D knapsack, iterate capacity downward for 0/1 items and upward for unlimited copies.
- Collapsing the table, then reconstructing. A rolled-up row loses the choices. Keep a predecessor or decision per state. The LIS tails array gives the length only, not a valid subsequence.
Interview tips
Open by stating the state as one sentence, then the transition, then the base cases. Name the complexity as states times transition cost.
Expect these follow-ups: collapse the table to O(1) or O(W) space and say what is lost; reconstruct the chosen items; why greedy fails on coins [1, 3, 4] for 6 (greedy gives 4+1+1, the optimum is 3+3); why the knapsack bound is pseudo-polynomial; when the default recursion limit forces tabulation; and how a modulus must be applied at every step in counting problems.
30-second outline: "The state is the best total over the first i houses. Each house is either skipped, which inherits the previous state, or robbed, which adds to the state two back, because the neighbour is forbidden. Base cases are dp[0] = 0 and dp[1] = a[0]. I fill in increasing index order, so the time is O(n) states times O(1) transition, and the space drops to two variables if I do not need the choices. For 0/1 knapsack the take branch instead reads dp[i-1] at capacity W minus the item's weight."
Feedback on this overview
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.