- Learn
- Computer Science & IT
- Programming
- Data Structures and Algorithms
- Dynamic Programming in Python
Dynamic Programming in Python: Memoization and Recurrences
IntermediateLesson 10 of 10 in Data Structures and Algorithms Course
What you will learn
- Explain how dynamic programming removes repeated work from recursive solutions, and decide whether a problem has the structure it needs.
- Spot repeated work in a recursive solutionTrace a recursive solution, find subproblems that are solved again and again, and measure how much work storing their answers saves.
- Identify problems that dynamic programming can solveRecognize optimization, counting and decision problems whose answers can be built from smaller subproblems, and explain why some problems lack this structure.
- Spot repeated work in a recursive solution
- Turn a recurrence into working Python code with memoization or with a table, and choose the approach that suits the problem.
- Speed up recursion with memoizationAdd a cache to a recursive function so that each subproblem is computed once, and avoid the bugs that make a cache return wrong answers.
- Fill a table bottom-up with tabulationBuild a dynamic programming table from the base cases upward, in an order where every entry's inputs are already known, and save memory where the recurrence allows.
- Choose between memoization and tabulationCompare the two implementations on ease of writing, subproblems computed, speed, recursion depth and memory, and test either one against brute force.
- Speed up recursion with memoization
- Plan a dynamic programming solution from scratch: choose subproblems, relate them with a recurrence, analyze the cost and recover the optimal solution itself, not only its value.
- Choose subproblems that capture the problemDefine subproblems precisely, using prefixes, suffixes, substrings or a remaining amount, and add a parameter when the recurrence needs more information.
- Write recurrences for optimization and countingBuild a recurrence by trying every option for one decision, combine the options with min, max, sum or or, and set base cases that make the smallest inputs correct.
- Analyze the running time and memory of a DP solutionEstimate time from the number of subproblems and the work in each, estimate memory from the table, and compare the result with brute force.
- Reconstruct an optimal solution from the tableRecover the choices behind an optimal value, either from a stored choice table or by retracing the recurrence, and handle ties between equally good solutions.
- Choose subproblems that capture the problem
- Solve the longest common subsequence problem with a table over pairs of prefixes, and recover one longest subsequence from it.
- Define the LCS problem and its recurrenceDistinguish subsequences from substrings, define the LCS subproblems over pairs of prefixes, and justify each case of the recurrence.
- Fill the LCS table and trace back a subsequenceFill the LCS table in a valid order, read its entries, trace back one longest common subsequence and state the time and memory used.
- Define the LCS problem and its recurrence
- Use tables indexed by items and amounts to decide subset sum and to maximize knapsack value, and explain why their running time depends on the size of the numbers.
- Decide subset sum with a table of true and false valuesDecide whether some numbers add up to a target, recover the numbers that do, and adapt the table to count subsets.
- Maximize value with the 0/1 knapsack tableFill the 0/1 knapsack table, recover the chosen items, and adapt the method to the unbounded and exact-capacity versions.
- Explain why knapsack runs in pseudopolynomial timeMeasure input size in bits, explain why a running time of O(nW) is pseudopolynomial rather than polynomial, and judge when the table method is practical.
- Decide subset sum with a table of true and false values
Dynamic Programming in Python study guide
1When stored answers save work
Recursion can hide a great deal of repeated work behind a short function. You will compare requests with distinct subproblems, then identify the structure that lets stored answers replace repeated calculations. Optimization, counting and decision problems combine their smaller answers in different ways. Tracing a few small cases will show both why sharing answers helps and why some recursive problems gain little from it.
1.1 Repeated calls and reusable answers
A recursive definition can be easy to read and expensive to run. The cost depends on how often it solves the same problem. Dynamic programming stores the answer to each distinct subproblem and reuses it on later requests. Richard Bellman introduced the method in the 1950s; “programming” means planning with a table of results.
Follow the calls
The Fibonacci sequence starts with and . Each later value is the sum of the previous two:
The values through are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 and 55. A direct translation into Python is short:
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
For fib(5), the first split requests fib(4) and fib(3). The fib(4) branch also requests fib(3). Both requests mean exactly the same thing: find the third Fibonacci number. The answer cannot depend on which branch asked for it.
Expand the calls and count identical arguments:
| Argument | 5 | 4 | 3 | 2 | 1 | 0 |
|---|---|---|---|---|---|---|
| Calls | 1 | 1 | 2 | 3 | 5 | 3 |
There are 15 calls but only six distinct subproblems. Nine calls repeat a subproblem requested earlier. This is overlap: different branches need the same answer. A cache lets them share it.
Count work, not just the answer
For the direct function, the total call count is . It grows by a factor approaching when the argument increases by 1. At fib(30), 2,692,537 calls produce 832,040, even though only 31 different arguments occur. The output is one number; the recursion tree measures the work needed to obtain it.
Storing an answer does not prevent all future calls with that argument. It makes those calls cheap: a lookup replaces the expansion of another subtree. Distinguish a request for a value from the first computation of that value. This distinction explains why memoized code can make more calls than it has cache entries and still run in linear time.
Recognize when storage pays off
Draw a small recursion tree and circle repeated argument lists. Each argument list must describe the whole subproblem; two calls with different inputs are not interchangeable just because their answers happen to match. You can also count the possible arguments and compare that count with the size of the call tree.
A factorial function calls only fact(n - 1), then fact(n - 2), and so on. In one evaluation, each size appears once. Saving those answers does not shorten that chain. Merge sort also avoids this kind of repeated work: its recursive branches sort separate halves of the input. Its divide-and-conquer structure alone is no reason to add a cache.
A list or dictionary is the storage mechanism. The defining idea is that repeated requests share one computed result. A large table without reusable subproblems is not evidence of a dynamic programming speedup.
Key Takeaways
- Overlap means separate branches request the same fully specified subproblem.
- A cache replaces repeated computation with a lookup; calls and computed states are different counts.
- Fibonacci has exponentially many direct recursive calls but only linearly many distinct arguments.
- Factorial and merge sort do not gain this overlap-based speedup in a single evaluation.
1.2 Problems built from smaller answers
Dynamic programming can minimize a cost, count possibilities or answer a yes-or-no question. In each case, the smaller answers must contain enough information to combine into a correct answer. Overlap creates the opportunity to save work; a valid way to combine subproblems makes the method correct.
Match the operation to the question
| Problem type | Question | How alternatives combine |
|---|---|---|
| Optimization | What is the fewest number of coins? | Take a minimum |
| Counting | How many routes reach a grid cell? | Add counts of disjoint cases |
| Decision | Can some numbers reach a target? | Use logical or |
An optimization problem has optimal substructure when its optimal solutions are built from optimal subproblem solutions. Suppose a shortest route from A to C passes through B. Its A-to-B part must be shortest too. Replacing a longer A-to-B part with a shorter one would shorten the whole route, contradicting its optimality.
This replacement argument checks more than whether a problem can be split. The replacement must leave a valid whole solution. If the pieces share constraints that the state has forgotten, a locally optimal replacement can break the whole solution.
Notice when pieces interfere
Consider a four-vertex cycle with edges a–b, b–c, c–d and d–a. A simple path cannot repeat a vertex. The longest simple a-to-b path is a–d–c–b, with three edges. Its first a-to-d part has one edge. Yet the longest simple a-to-d path is a–b–c–d, with three edges.
Substituting that longer part into the original route would reuse vertices. An endpoint-only subproblem has forgotten which vertices remain available. The longest simple path therefore lacks the optimal substructure of this endpoint-only design. Naming smaller paths is not enough to make their best answers compatible.
For counting, check a different condition: the cases must cover every object exactly once. A right-and-down route reaches a cell either from above or from the left. Each route has one last move, so those cases are disjoint and exhaustive. Adding their counts counts every route once. An overlapping case split would count some routes twice.
Put dependencies in order
Build a subproblem graph with one vertex per state. Draw an arrow from a state to each later state that uses its answer. For Fibonacci, arrows run from to and where those states exist. A topological order puts each dependency before its users. Base cases come first, and no arrows loop back to form a cycle.
A useful design combines a valid recurrence, repeated states and a number of states small enough to compute and store. A recurrence with exponentially many distinct states can still be too expensive after caching.
Compare all choices
Choosing the largest fitting coin is not a reliable minimum-coin rule. With coin values 1, 3 and 4, it makes 6 as 4 + 1 + 1, using three coins. The split 3 + 3 uses two. Dynamic programming evaluates each possible last coin together with the best answer for the remaining amount. It commits after comparing complete candidate values, including the cost left behind by each choice.
Key Takeaways
- Optimization uses min or max; counting adds disjoint cases; decision uses or.
- Optimal substructure requires replacing a piece with an optimal piece to preserve a valid solution.
- Subproblems must keep the information needed to combine their answers without constraint conflicts.
- With arrows from dependencies to their users, a topological order is a valid computation order.
- Caching helps most when many requests share a manageable set of states.
2Top-down and bottom-up Python
A recurrence can run through recursive calls or through loops over a table. You will implement both approaches in Python, check that their states mean the same thing, and compare their practical costs. Cache keys, base cases and dependency order determine correctness. Reachable states, recursion depth and the values that must remain available determine which implementation fits a particular problem.
2.1 Memoization in Python
Memoization keeps the recursive structure and adds a cache. Each key identifies one subproblem. A call first looks for its key; only a missing answer triggers the recurrence. This top-down approach starts at the requested answer and discovers the states it needs.
Add a cache to Fibonacci
memo = {0: 0, 1: 1}
def fib(n):
if n not in memo:
memo[n] = fib(n - 1) + fib(n - 2)
return memo[n]
The base answers are already stored. For a missing value such as fib(4), the function obtains the two smaller values, adds them and stores the result. A later request for fib(4) returns 3 directly. All recursive calls go through the cached function, so repeated states benefit too.
For an initially base-only cache, fib(30) makes 59 calls: one initial call plus two calls from each newly computed state from 2 through 30. The direct version makes 2,692,537 calls. The cached version computes 29 nonbase answers and retains 31 entries, including the two bases.
Let Python manage the dictionary
Python 3.9 and later provide functools.cache:
from functools import cache
@cache
def fib_cached(n):
if n < 2:
return n
return fib_cached(n - 1) + fib_cached(n - 2)
lru_cache(maxsize=None) provides the same unbounded caching behavior. Arguments must be hashable, meaning they can serve as dictionary keys. An integer index or a tuple works; a mutable list does not. For a fixed input list, a helper can close over the list and accept only indices and amounts.
Make the key describe the whole question
Suppose solve(i, c) finds the best value using the first i items with capacity c. A cache indexed only by i merges different questions. The best answer at capacity 2 can differ from the best answer at capacity 9, even with exactly the same available items. Store both parameters as (i, c).
Data outside the key must remain unchanged. If solve reads a global item list and that list changes, old entries describe the old items. Clear the cache with solve.cache_clear(), create a new cached helper for the new input, or include immutable item data in the key. Cached Fibonacci answers remain valid across different requests because each value depends only on its argument.
Membership matters when using a manual cache. An answer of 0 or False can be correct, so a truth-value test such as if memo.get(key): confuses a stored false-like value with a missing entry. Use if key in memo: to test whether an answer exists.
Account for time and the call stack
Each state pays for its own nonrecursive work once. With average constant-time dictionary access, reached states and at most constant-time choices per state take work. Include the cache and recursion stack in memory usage.
Memoization does not shorten the longest dependency chain. CPython’s default recursion limit is 1,000; sys.getrecursionlimit() reports the current setting. An empty-cache call to fib_cached(5000) exceeds that default limit. A bottom-up implementation avoids recursive frames.
Caching also cannot remove genuinely different states. If a key records every remaining subset of items, the number of keys can be exponential. A correct cache saves repeated work within that state space; it does not make the state space smaller.
Key Takeaways
- Check the cache before expanding a state, and send recursive calls through the cached function.
- A cache key must distinguish every changing input that affects the answer.
- Use hashable keys and clear cached results when unkeyed input data changes.
- Memoization retains both cached answers and a recursion stack.
- Count reached states and work per state; caching cannot remove exponentially many distinct states.
- Cache membership must distinguish a missing entry from a stored 0 or
False.
2.2 Tables filled in dependency order
Tabulation computes subproblems in an explicit order, starting with the base cases. Every entry is ready before another entry reads it. This bottom-up implementation uses loops and avoids the recursive call stack.
Build the Fibonacci table
def fib_table(n):
if n == 0:
return 0
F = [0] * (n + 1)
F[1] = 1
for i in range(2, n + 1):
F[i] = F[i - 1] + F[i - 2]
return F[n]
The list contains positions 0 through n. At iteration i, both positions read by the recurrence have smaller indices and are already correct. The special case for 0 matters: a one-entry list has no position 1. For n = 10, the completed list is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55.
Increasing index is suitable here because dependencies point toward larger indices. Other recurrences can require decreasing indices or increasing interval length. The general rule is a topological order of the subproblem graph, with arrows from dependencies to the states that use them.
Count routes through cells
Take a grid with three rows and four columns of cells. A route starts in the top-left cell and moves only right or down. Let P[r][c] count routes reaching cell (r, c). Every cell in the first row or first column has one route. Other cells add the counts above and to the left.
| Row | Column 0 | Column 1 | Column 2 | Column 3 |
|---|---|---|---|---|
| 0 | 1 | 1 | 1 | 1 |
| 1 | 1 | 2 | 3 | 4 |
| 2 | 1 | 3 | 6 | 10 |
For instance, row 2, column 2 receives 3 routes from above and 3 from the left, giving 6. The final entry is 10. A row-by-row, left-to-right loop makes both inputs ready at every step.
Now block cell (1, 1). Set its entry to 0. The rows become 1 1 1 1, 1 0 1 2 and 1 1 2 4, leaving four routes. The blocked entry contributes nothing to its neighbors. If an obstacle lies on the first row or column, cells beyond it need the recurrence too; do not initialize an entire blocked boundary to ones.
Keep only live values
Fibonacci reads only two older entries. Once an entry can never be read again, it can be discarded:
def fib_small(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
Python evaluates the right side before assigning either variable. After n iterations, a holds the requested value. This uses a constant number of stored values instead of a growing list. Similarly, some two-dimensional recurrences need only a previous row and a current row.
Discarding entries changes what remains available. A final value can survive while the path of choices that produced it is lost. Keep a full table or choice records when you need to recover a solution.
A wrong filling order can fail silently: an uncomputed entry still contains its initial zero, which looks like a valid answer. For each read in the loop, identify the earlier iteration that established its value. Include zero or empty prefixes when sizing the table, so a range from 0 through a limit has one more entry than the limit.
Key Takeaways
- Fill base cases first, then compute each state after all its dependencies.
- A table indexed from 0 through a limit needs limit + 1 entries.
- Blocked grid cells contribute zero routes; boundary obstacles must block routes beyond them.
- Rolling storage retains only values future states still need.
- Discarded values cannot support ordinary traceback.
2.3 Choosing and checking an implementation
Memoization and tabulation evaluate the same recurrence in different ways. They should agree on every input when both implementations are correct. Choose between them by asking which states are reached, how deep the dependencies run, and which results must remain available.
Compare the costs that differ
| Feature | Memoization | Tabulation |
|---|---|---|
| Order | Discovered by recursive calls | Written explicitly in loops |
| States computed | Only those reached by the request | Usually the whole chosen table |
| Call stack | Retained during recursion | No recursive stack |
| Typical overhead | Calls and cache lookups | Indexing and loop operations |
| Storage savings | Avoids unreached states | Can discard old rows or entries |
When both approaches visit the same states and do the same work per state, their asymptotic time usually matches. Function-call overhead changes a constant factor, not a linear bound into a quadratic one. Tabulation often runs faster because it avoids calls and dictionary lookups, but a sparse reachable state space can favor memoization.
For subset sum with numbers 100, 200 and 300 and target 600, a full table contains entries. A memoized search needs at most 14 distinct pairs of item index and remaining target. Subtracting these numbers keeps the remaining target a multiple of 100. Most columns of the full table are irrelevant to this particular query.
Convert without changing the question
A practical route is to define the state and recurrence, implement a memoized version, and then translate it into loops. Preserve the state meaning and base cases. Replace recursive dependency requests with table reads, and choose a loop order that makes those reads valid.
A long dependency chain favors loops even when the number of states is small. Memoized Fibonacci still follows a chain of decreasing arguments. Tabulation removes that recursion-depth risk. When only a value is needed, an explicit filling order may also let old values be discarded.
Memory is not decided by the words “top-down” and “bottom-up.” A dense list can be more compact than a dictionary, and bottom-up code has no recursive frames. A full rectangular table can nevertheless use more memory than a small cache. Compare the actual entries and stack frames retained by each implementation.
Check correctness with small exhaustive cases
For subset sum, enumerate all subsets on small inputs and compare the yes-or-no result with the dynamic program. At ten items there are only subsets. Include an empty list with target 0, an empty list with a positive target, a reachable target, and a target that would require reusing an item.
Check more than whether the two DP versions agree. They may share the same incorrect recurrence. An exhaustive solver follows a separate method and is a stronger reference on small inputs. If a mismatch appears, inspect state meaning, base values and loop boundaries before changing the optimization strategy.
Key Takeaways
- The same recurrence gives the same answers in top-down and bottom-up implementations.
- Memoization can avoid unreachable states; tabulation avoids recursive frames and supports rolling storage.
- Compare actual retained states and stack use to judge memory.
- Use a separate exhaustive solver on small inputs to catch shared recurrence errors.
3Designing a complete DP solution
The hardest step often comes before the code: deciding what each stored answer means. You will build states that remember enough for the next choice, turn those choices into recurrences, and count the work they perform. Rod cutting, coin problems and increasing subsequences show how small changes in the question change the design. Choice records then let you recover an actual solution from an optimal value.
3.1 States that remember enough
A state is a precise description of one subproblem. Its parameters must retain everything needed to make the next choice. Before writing loops, finish the sentence “This entry is…” with a meaning that another programmer could check on a small input.
Use a design checklist
MIT's SRTBOT checklist names six parts of a solution: Subproblems, Relation between them, Topological order, Base cases, Original answer and Time. The recurrence and order depend on what each state means, so define that meaning first.
For example: “K[i][c] is the greatest total value obtainable using the first i items with capacity c, for i from 0 through n and c from 0 through W.” This says which items are available, what the capacity means and what the entry stores. “The best answer so far” says none of these things.
Common state shapes give different numbers of subproblems:
| Shape | Meaning | Number of states |
|---|---|---|
| Prefix | First i elements | n + 1, including empty |
| Suffix | From index i to the end | n + 1, including empty |
| Substring | Contiguous interval from i to j | Quadratic in n |
| Two prefixes | First i and first j elements of two sequences | (m + 1)(n + 1) |
| Items and amount | Available prefix and remaining capacity or target | Product of the two ranges |
A substring state keeps both ends of an interval. A subsequence can skip elements, so it is not a substring state just because it comes from a sequence.
Keep the endpoint when extension needs it
For the longest increasing subsequence, values must rise strictly while retaining their original order. The best length anywhere in a prefix does not tell you whether a new value can extend that subsequence. Its final value matters.
Define as the longest increasing subsequence ending exactly at position . Its endpoint is now known. To extend from an earlier position , require both and :
with if the set is empty. The one counts the element at position itself.
For 3, 1, 4, 1, 5, 9, 2, 6, the state values are 1, 1, 2, 1, 3, 4, 2, 4. At the second 1, no earlier value is smaller, so its entry is 1. At 9, the earlier 5 has entry 3, so extending gives 4. Equal values cannot extend a strictly increasing subsequence.
The original answer is the maximum across all endpoint states: 4, achieved by 1, 4, 5, 9, for example. It is not defined as the last entry; the best subsequence may end earlier. For an empty sequence, return 0 because there are no endpoint states.
Check the dependency graph
Every referenced state must belong to the defined state set. The dependencies must also admit an order without cycles. Smaller indices make the LIS order straightforward. Same-size dependencies can work too: compute B[i] before A[i] if A[i] needs B[i] and B[i] needs only earlier states. A mutual dependency between A[i] and B[i] has no such order. Memoization cannot finish either call before the other returns, and a table would read an unfinished value.
Key Takeaways
- Define every state in words, including its parameters, ranges and stored answer.
- Choose prefixes, suffixes, intervals or numeric limits according to what the next choice needs.
- An LIS endpoint state records the final position, making extension checks possible.
- The answer for endpoint states is the maximum over all endpoints.
- Every dependency must be a defined state and fit an acyclic computation order.
3.2 Choices, recurrences and base cases
A recurrence expresses a state using other states. Choose one decision in a solution, such as its first piece or last coin. List every legal option for that decision. Each option must leave a subproblem with exactly the meaning your state definition gives it.
Maximize rod-cutting revenue
A rod of length meters can be cut into whole-meter pieces. A piece of length has unitless price . Let be the best total price for the rod. If its first piece has length , that piece earns and the remaining rod earns :
The option sells the rod whole. With prices 2, 5, 7, 8 and 10 for lengths 1 through 5 m, the best values for lengths 0 through 5 are 0, 2, 5, 7, 10 and 12. For length 4, compare , , and 8, so the best is 10. For length 5, the candidates are 12, 12, 12, 10 and 10. The maximum 12 beats the whole-rod price 10.
Minimize the number of coins
With unlimited coins of positive values, let be the fewest coins totaling exactly . Try each possible last coin:
If no candidate is reachable, the answer is infinity. With coins 1, 3 and 4, amounts 0 through 6 need 0, 1, 2, 1, 1, 2 and 2 coins. At 6, a last coin of 3 leaves amount 3, giving two coins in total.
Use float('inf') for an impossible minimum, not 0. With coins 3 and 4, amount 2 is impossible. A false zero there would make amount 5 appear possible with one final coin of 3. For maximization with exact constraints, use minus infinity to keep impossible options from winning.
Count combinations or sequences
Counting uses addition, but first decide what counts as a different result. With coins 1, 2 and 5, amount 5 has four unordered combinations: 5, 2 + 2 + 1, 2 + 1 + 1 + 1 and five ones. If order matters, 2 + 2 + 1, 2 + 1 + 2 and 1 + 2 + 2 are distinct. There are nine ordered sequences in total.
These loops count unordered combinations:
ways = [0] * (amount + 1)
ways[0] = 1
for coin in coins:
for a in range(coin, amount + 1):
ways[a] += ways[a - coin]
After each coin pass, only denominations processed so far are allowed. Each combination is built in that fixed denomination order. For ordered sequences, put amounts in the outer loop and sum over possible last coins inside; every sequence has one final coin, so those cases are disjoint.
Let the empty case do its job
There is one way to form amount 0: choose nothing. Thus counting starts from 1, while minimum-coin optimization starts from 0 coins. With a zero counting base, every addition would keep producing zero.
For a decision problem, alternatives combine with or: success in either legal case makes the state true. For optimization, every solution must be represented by at least one candidate. For counting, every result must be represented exactly once. Enumerating the tiny cases by hand checks both the recurrence and its base values.
Key Takeaways
- Choose a first or last decision and include every legal option in the recurrence.
- Combine candidate values with min, max, addition or or, according to the question.
- Use infinity for impossible minima and minus infinity for impossible maxima.
- Counting amount 0 starts at 1 because the empty choice is one result.
- Coin-first loops count combinations; amount-first loops count ordered sequences.
- Counting cases must be both exhaustive and disjoint.
3.3 Time and memory from the state design
The time of a dynamic program is the sum of the work done at all its states. Count distinct states, then count how many options each state examines. A cache or table prevents recomputation, but each first computation still has a cost.
Include every option
| Algorithm | States | Work at a state | Total time |
|---|---|---|---|
| Fibonacci | Linear in n | Constant | |
| Rod cutting | Linear in n | Up to n cuts | |
| Simple LIS DP | One per endpoint | Scan earlier endpoints | |
| LCS | Prefix-pair grid | Constant | |
| 0/1 knapsack | Item-capacity grid | Constant |
For rod cutting at length 5, states 1 through 5 try 1, 2, 3, 4 and 5 first pieces. That is 15 candidate evaluations. In general:
Counting only the five nonempty states would miss most of the work. The same issue occurs in LIS: although there are only endpoint states, each inspects earlier endpoints. The strict-value comparison decides whether each earlier state can contribute; the scan still takes time when that comparison fails.
For memoization, count the states actually reached. Exclude the recursive work from the local cost of a state, since that work is counted at its own states. Add any final computation, such as the scan taking the maximum over LIS endpoints.
Count retained information
A full LCS table has entries. A full knapsack table has entries. Memoized code also retains recursive frames along its deepest active call chain. Memory analysis must include those frames as well as the cache.
If each row depends only on the previous row, a value-only calculation may retain two rows. A one-list update can save more memory when its direction protects the old values. Space savings do not reduce the number of state updates: rolling a knapsack table into one list still performs about updates.
A count of entries is not yet a count of bytes. Python lists hold references, and dictionaries and integer objects have overhead. Use the entry count to compare designs, then measure the implementation if the memory budget is tight.
Compare with exhaustive search
Trying all subsets of 40 items means about subsets. A capacity-indexed table for 40 items and capacity 1,000 contains entries. This is a large reduction in states, provided the table's numeric dimension is moderate.
Counts can also grow large even when there are few states. Grid-route totals grow exponentially with grid size. Python integers grow to keep exact values, while a fixed-size type such as Java's long can overflow. Some counting tasks request a remainder modulo to keep values bounded. State-update bounds such as use constant-time table operations; exact arithmetic on very large counts has an additional cost that grows with their bit length.
Key Takeaways
- Time includes both the number of states and the options processed at each state.
- Rod cutting and the simple LIS recurrence take quadratic time despite having linearly many states.
- Memory includes the table or cache and any recursive call stack.
- Rolling storage reduces retained entries without reducing the number of updates.
- Exact large-integer counting has arithmetic costs beyond a constant-time update model.
3.4 Recovering choices from optimal values
An entry containing an optimal value does not name the choices that produced it. Reconstruction recovers those choices. Start at the original problem, follow an option that achieves its stored optimum, and continue until a base case is reached.
Store the winning decision
For rod cutting, keep cut[length], the first-piece length of one optimal solution. The code can record a choice while computing each value:
def rod_solution(prices, n):
best = [0] + [float('-inf')] * n
cut = [0] * (n + 1)
for length in range(1, n + 1):
for first in range(1, length + 1):
candidate = prices[first - 1] + best[length - first]
if candidate > best[length]:
best[length] = candidate
cut[length] = first
pieces = []
remaining = n
while remaining > 0:
first = cut[remaining]
pieces.append(first)
remaining -= first
return best[n], pieces
The price list supplies every length from 1 through n. The strict comparison keeps the first choice found at a tied maximum. Each recorded first piece is positive, so the remaining length decreases and the reconstruction stops.
With prices 2, 5, 7, 8 and 10, the stored first choices include cut[5] = 1, cut[4] = 2 and cut[2] = 2. Reconstruction takes a 1 m piece, leaving 4 m; a 2 m piece, leaving 2 m; and another 2 m piece, leaving 0. Their values add to .
Retrace the recurrence instead
A separate choice table is optional when the full value table is available. At remaining length 5, find a first length whose price plus the remaining value equals 12. Length 1 works because . Move to length 4 and repeat.
Do not simply choose the largest neighboring table value. A candidate must include its own contribution, such as the first piece's price, and must leave the corresponding legal state. The recurrence tells you which moves are allowed.
Handle ties and verify the result
The same rod also has an optimal split of 2 m and 3 m, with total value . Either split is correct when the task asks for one optimum. Keeping the first maximum gives a reproducible answer, but it does not guarantee the fewest pieces. A task with that extra objective needs a tie rule that evaluates it.
Check reconstructed choices against the original constraints and value: piece lengths sum to 5 m, and piece prices sum to 12. In knapsack, check that no item was reused and total weight fits; in LCS, check both order and length.
Following stored rod choices takes at most one step per meter, or steps. Knapsack traceback takes at most one step per item, and LCS takes moves. Recomputing all candidates at each traceback step can cost more than following stored choices; charge those scans if you use them.
Rolling storage may remove the earlier entries that these moves need. For straightforward reconstruction, retain the full value table or enough choice records for every visited state. A final optimum alone cannot tell you how it was formed.
Key Takeaways
- Store a winning choice during filling, or identify a candidate that equals the stored optimum afterward.
- A traceback move must follow the recurrence and include the choice’s own contribution.
- Ties can produce different valid optimal solutions.
- Check both feasibility and achieved value after reconstruction.
- Stored choices support a short traceback; rescanning alternatives adds work.
- Keep the information needed for reconstruction before discarding old rows.
4Longest common subsequences
Two sequences may share a long ordered selection even when their common elements are separated by gaps. You will use pairs of prefixes to find that selection, translate the recurrence into Python indices, and follow the filled table backward. Matches, mismatches and tied predecessors each have a clear role. The same table shape also provides a useful comparison with the different objective of edit distance.
4.1 Prefixes and the LCS recurrence
A subsequence retains some elements in their original order, with gaps allowed. From “ALGORITHM,” deleting elements can leave “LGTM.” It cannot leave “MAG,” because the needed letters occur in a different order. A substring is stricter: it must be one contiguous block.
Ask for the longest shared order
A common subsequence belongs to both inputs. A longest common subsequence, or LCS, has the maximum possible length. Several different strings can share that length. For “ACTGA” and “CATGTA,” both “ATGA” and “CTGA” are LCSs of length 4.
Their longest common substring has length 2; “TG” is one example. Allowing gaps changes the problem. Resetting a table entry to zero on a mismatch computes a contiguous-match quantity, not the LCS length.
Brute force can choose any subset of positions from an input of length , giving choices of positions to consider. Repeated letters can yield the same text from different choices, but the enumeration still has exponentially many candidates.
Give empty prefixes a place
Let be the LCS length of the first elements of X and first elements of Y. The ranges are and . Row 0 and column 0 represent empty prefixes:
An empty sequence shares no nonempty subsequence with another sequence. The requested full-input answer is . The table contains states, including the empty cases.
Compare the last two elements
If the prefix endpoints match, include that matching pair and solve the shorter prefixes:
Some optimal common subsequence uses that pair at its end. Removing it leaves a common subsequence of the two shorter prefixes. Conversely, appending the matching element to an LCS of the shorter prefixes produces a valid common subsequence one element longer.
If the endpoints differ, they cannot both be the last matched element. Drop the endpoint of X or the endpoint of Y and take the better result:
No element is matched in this step, so do not add 1. For the prefixes “ACT” and “CAT,” the final T matches T. The shorter prefixes “AC” and “CA” have LCS length 1. Therefore , represented by “AT” or “CT.”
Translate positions into Python
The mathematical element is Python's X[i - 1]. The row counts elements in the prefix; the string index starts at zero. Thus row 1 compares X[0], and row m compares X[m - 1]. Using X[i] skips the first character and eventually reads beyond the end.
The same shared-order idea helps compare lines in file versions. Related sequence-alignment methods compare biological sequences. The LCS table records matched order; it does not require the shared elements to remain adjacent.
Key Takeaways
- A subsequence preserves order and allows gaps; a substring must be contiguous.
- An LCS has maximum length, but its text need not be unique.
- Each LCS state compares two prefixes, with an empty row and column of zeros.
- Matching endpoints add 1 to the diagonal; differing endpoints take the maximum above or left.
- Prefix length
icorresponds to Python character indexi - 1.
4.2 Filling and tracing the LCS table
The LCS recurrence reads the entries above, left and diagonally above-left. Fill rows from top to bottom and each row from left to right. Then all required prefix answers are ready when a new cell is computed.
Fill the table in Python
def lcs(X, Y):
m, n = len(X), len(Y)
L = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if X[i - 1] == Y[j - 1]:
L[i][j] = L[i - 1][j - 1] + 1
else:
L[i][j] = max(L[i - 1][j], L[i][j - 1])
i, j = m, n
result = []
while i > 0 and j > 0:
if X[i - 1] == Y[j - 1]:
result.append(X[i - 1])
i -= 1
j -= 1
elif L[i - 1][j] >= L[i][j - 1]:
i -= 1
else:
j -= 1
return L[m][n], ''.join(reversed(result))
The list comprehension creates separate rows. Repeating one inner list with multiplication would make rows share storage, so changing one cell could corrupt several rows.
For X = “ACTGA” and Y = “CATGTA,” the table is:
| X prefix ending | Empty | C | A | T | G | T | A |
|---|---|---|---|---|---|---|---|
| Empty | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| A | 0 | 0 | 1 | 1 | 1 | 1 | 1 |
| C | 0 | 1 | 1 | 1 | 1 | 1 | 1 |
| T | 0 | 1 | 1 | 2 | 2 | 2 | 2 |
| G | 0 | 1 | 1 | 2 | 3 | 3 | 3 |
| A | 0 | 1 | 2 | 2 | 3 | 3 | 4 |
The last entry is 4. An interior entry answers its own prefix question: row 3, column 3 says “ACT” and “CAT” have LCS length 2.
Walk backward through the decisions
Start at (5, 6). A matches A, so record A and move diagonally to (4, 5). G and T differ; the left entry is 3 and the upper entry is 2, so move left without recording anything. At (4, 4), record the matching G. At (3, 3), record T.
At (2, 2), C and A differ and both predecessors have value 1. The code chooses up on this tie. At (1, 2), record A and reach the empty row. The recorded order is A, G, T, A, so reverse it to get “ATGA.” Choosing left on the tie gives “CTGA,” also length 4. Moving up or left skips an element; only a matching diagonal contributes a letter.
Time, space and a related problem
For nonempty inputs, filling takes time and space. Traceback adds at most moves. Two inputs of 1,000 characters need entries. If only the length is needed, two rows suffice. Put the shorter sequence on the columns for extra entries. Those two rows do not retain the earlier values needed by this traceback.
Edit distance uses the same pair-of-prefixes state shape but stores the fewest edits. With unit-cost insertion, deletion and substitution, initialize and . Take the minimum of the upper entry plus 1, the left entry plus 1, and the diagonal plus 0 for a match or 1 for a mismatch. For “kitten” to “sitting,” substitute k with s, substitute e with i, and append g: three edits. Different state meanings require different base cases and recurrences, even when their tables have the same shape.
Key Takeaways
- Row-by-row filling makes all three LCS predecessors available.
- Record a character only on a matching diagonal move.
- At mismatches, follow an optimal upper or left predecessor; ties allow different LCSs.
- Reverse the characters collected by backward traversal.
- Full-table LCS takes quadratic product time and space; two rows suffice for length alone.
- Edit distance uses prefix pairs too, but minimizes edits with different bases and transitions.
5Subset sum, knapsack and numeric limits
Choosing a subset becomes manageable when many choices leave the same item prefix and remaining amount. You will use those states to decide exact sums and maximize packed value, then recover the chosen numbers or items. Single-list updates save space, but their direction changes whether reuse is allowed. Finally, measuring the input in bits explains why a modest-looking numeric limit can dominate the computation.
5.1 Reachable sums and subsets
Subset sum asks whether some input numbers add up to an exact target. Each input position may be used at most once. With positive integers 3, 5, 6 and 8, target 14 is reachable as 6 + 8 or 3 + 5 + 6. Target 12 is not reachable.
Include or skip the current number
Let mean that a subset of the first numbers totals exactly , for and . With no numbers, only zero is reachable: is true and is false for positive .
For number , either skip it and use , or take it and use when it fits. Combine those cases with logical or. Both cases read the previous row, so neither can use the current input twice.
def subset_table(numbers, target):
S = [[False] * (target + 1) for _ in range(len(numbers) + 1)]
S[0][0] = True
for i, a in enumerate(numbers, start=1):
for t in range(target + 1):
S[i][t] = S[i - 1][t]
if a <= t:
S[i][t] = S[i][t] or S[i - 1][t - a]
return S
After processing 3, 5, 6 and 8, the reachable totals are 0, 3, 5, 6, 8, 9, 11, 13, 14, 16, 17, 19 and 22. A table ending at target 14 stores only those totals up to 14; larger totals need no columns for that query because all inputs are positive.
Recover a subset
At a true entry , skip the current number if is true. Otherwise take it and subtract its value from the target. In both cases decrease the item index.
For target 14, the first three numbers already suffice, so skip 8. With the first two numbers, 14 is unreachable, so take 6 and continue at target 8. Take 5, then 3, reaching target 0. The result is a valid subset and its sum checks: . A different tie rule can recover 6 + 8.
Save space without reusing an input
def subset_possible(numbers, target):
can = [False] * (target + 1)
can[0] = True
for a in numbers:
for t in range(target, a - 1, -1):
can[t] = can[t] or can[t - a]
return can[target]
The downward loop reads a smaller target that has not yet been updated for this number. An upward loop would let one update feed another in the same pass. With only the number 5, it would mark 5 true and then incorrectly mark 10 true.
Count subsets instead of deciding
Store counts and add the skip and take counts, using zero when the take case does not fit. Start with and other entries zero. For the example, . Subsets distinguish input positions: two equal numbers in separate positions are separate available choices.
The decision table takes time and space; the single list uses space. Column indices require nonnegative integer amounts. Exact decimal measurements can be scaled to integers, such as multiplying one-decimal-place masses by 10. Scale both the inputs and target; the larger numeric target also increases the table width.
Key Takeaways
- Use a state for an available input prefix and an exact target.
- Both the skip and take cases read the previous row to enforce at-most-once use.
- The empty subset makes target 0 reachable and contributes one subset to a count.
- A downward single-list loop prevents reuse of the current input.
- Traceback follows true predecessors and decreases the item index at every step.
- Replacing or with addition counts subsets of input positions.
- Scaling exact measurements to integer indices changes table cost.
5.2 Packing whole items for maximum value
In 0/1 knapsack, item has positive integer weight and value . Choose whole items at most once, with total weight at most capacity , to maximize value.
Compare taking and leaving
Let be the best value using the first items with capacity . With no items, every capacity has value 0. When the current item fits:
The first candidate skips the item. The second takes it and solves the remaining capacity using earlier items. If it is too heavy, copy .
For capacity 7 kg, take A with weight 1 kg and value 5; B with 4 kg and 16; C with 3 kg and 11; and D with 5 kg and 15.
| Available items | 0 kg | 1 kg | 2 kg | 3 kg | 4 kg | 5 kg | 6 kg | 7 kg |
|---|---|---|---|---|---|---|---|---|
| None | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| A | 0 | 5 | 5 | 5 | 5 | 5 | 5 | 5 |
| A, B | 0 | 5 | 5 | 5 | 16 | 21 | 21 | 21 |
| A, B, C | 0 | 5 | 5 | 11 | 16 | 21 | 21 | 27 |
| A, B, C, D | 0 | 5 | 5 | 11 | 16 | 21 | 21 | 27 |
At , skipping C gives 21. Taking C gives . Ratio order would take A and B first, leaving 2 kg that fits neither C nor D. That yields only 21.
Trace back the selected items
Start at . It equals the entry above, so skip D. At the value exceeds the entry above, so take C and reduce capacity to 4. At take B and reduce capacity to 0. B and C weigh 7 kg and have value 27.
Equality with the previous row means an optimum exists without the current item. Skipping it is safe even if taking it could tie. Move to the previous row after either decision, so no item can be reported twice.
Implement the value-only version
def knapsack(items, capacity):
best = [0] * (capacity + 1)
for w, v in items:
for c in range(capacity, w - 1, -1):
best[c] = max(best[c], v + best[c - w])
return best[capacity]
Descending capacities preserve the previous-row meaning of best[c - w]. The time is and the list uses space. A full table uses space and supports the traceback above.
Change the rules deliberately
| Variant | What changes |
|---|---|
| Unbounded | Repeated copies are allowed; process capacities upward |
| Exact capacity | Only total weight exactly equal to the capacity counts as feasible |
| Fractional | Pieces of items are allowed; it is a different optimization problem |
For unbounded knapsack, . Use ; when no item fits, the value is 0. Smaller capacities are ready in increasing order, and reuse is legal. Seven copies of A give value 35 at 7 kg.
For exact capacity, initialize only and give every positive capacity in the empty row value . The recurrence then preserves impossibility where no exact fill exists. Initializing the whole row to zero would silently permit unused capacity and answer the at-most version. Values may be negative. At a positive exact capacity, the empty selection is infeasible even when all item values are negative. Weights and capacity must be integers for these column indices.
Key Takeaways
- An item is taken whole at most once in 0/1 knapsack.
- The recurrence compares skipping the item with its value plus an earlier-item subproblem.
- Value-per-weight order can miss the optimal whole-item combination.
- Traceback moves up an item row after either taking or skipping.
- Descending single-list updates enforce 0/1 use; ascending updates allow reuse.
- Exact capacity requires minus infinity for impossible positive empty-row states.
- Whole-item, unbounded and fractional rules describe different problems.
5.3 Numeric values and input length
A table can be small in its number of dimensions and still be enormous. Knapsack has an item dimension and a capacity dimension. The capacity is a numeric value encoded in the input, so it can be much larger than the number of bits needed to write it.
Measure the written input
An integer needs binary digits. A list of numbers below needs about bits. Polynomial time means a polynomial bound in this encoded input length.
A capacity of 1,000,000 fits in 20 bits because . Yet a capacity-indexed table needs 1,000,001 columns. With 100 items, it holds about entries. The number of columns is the value plus one, not the bit count plus one.
Knapsack's bound is pseudopolynomial: polynomial in the numeric capacity and number of items, but not polynomial in the general binary input length. If a capacity uses bits, its value can approach . Adding ten bits can multiply the number of columns by about .
Subset sum has the same issue with target in its table. LCS differs: its dimensions count input symbols. The lengths and correspond directly to the amount of sequence data, so is polynomial in input length.
Estimate updates and storage separately
For target 3,000,000 and 20 numbers, about updates are needed. With 10,000 numbers, that grows to about updates. The first is a manageable work count; actual elapsed time depends on the implementation. The second is much more demanding even though the target is unchanged.
A full table retains entries. A single list retains only entries but still performs about updates. A target near makes even the single list infeasible. Space optimization cannot remove the numeric dimension from the time bound.
Table DP also does not beat brute force for every input. At 30 items and capacity , the table requires about entries, compared with subsets. Both are large; the comparison shows why the capacity matters when selecting an exact method.
Track the effect of units
For whole-kilogram weights and capacity 5 kg, columns 0 through 5 give six entries per row. Expressing the same measurements in grams creates columns 0 through 5,000, giving 5,001 entries. The feasible choices are unchanged, but an unreduced table is about 1,000 times wider. Increasing numeric precision has the same practical effect when it increases the integer scale.
Writing a number in unary would give it one input symbol per unit. Under that encoding, is polynomial in the written length. Binary encoding packs that magnitude into far fewer symbols. No exact algorithm is known that solves general subset sum or 0/1 knapsack in time polynomial in the binary input length; the table method is effective when the numeric limits are moderate.
Key Takeaways
- Input length counts encoded bits, while a numeric table dimension counts units of capacity or target.
- Pseudopolynomial bounds can be exponential in the bit length of a numeric limit.
- LCS dimensions count input symbols, so its product-time bound is polynomial.
- Judge practicality from both update count and retained storage.
- Changing measurement scale can widen a table without changing the feasible selections.
Dynamic Programming in Python examples
1Find the work worth sharing
12 steps
- 1IntroductionOne answer, many requests
A short recursive function can ask the same question thousands of times. Those repeated subproblems are what dynamic programming exploits. You will trace a small example, distinguish repeated requests from different states, and see what storing an answer in a cache saves.
Then check the other half of the method: whether smaller answers can be combined correctly, which for optimization is called optimal substructure. Optimization and counting need different arguments for that step.
- 2ExplanationStart with the Fibonacci rule
The first two values are and . For later arguments, use . The values begin 0, 1, 1, 2, 3, 5.
Direct recursion asks for both smaller values each time. To compute
fib(5), it requestsfib(4)andfib(3). Expandingfib(4)requestsfib(3)again. Both requests ask exactly the same question. - 3ExampleCount the repeated questions
In the full evaluation of
fib(5), arguments 5 and 4 appear once each, 3 appears twice, 2 appears three times, 1 appears five times and 0 appears three times.That is 15 calls for only six distinct subproblems. The repeated nodes are not new mathematical questions; they repeat earlier work. At argument 30, the direct function grows to 2,692,537 calls although only 31 states exist.
- 4AnalogyShare the computed result
Think of a cache like a notebook indexed by the question asked. Once the answer for argument 3 is written down, either branch can look it up.
The request still occurs, but its work changes from expanding a subtree to reading one saved value. The notebook must label the whole question: if a state has both an item index and a capacity, recording only the index mixes different problems.
- 5ChallengeWould this chain benefit?
A recursive function computes a product by requesting only the next smaller argument, once per level. Does adding a cache remove repeated work from its first evaluation? Explain the distinction between a call and a repeated subproblem.
---reveal---
No. The chain visits each argument once, so it has calls but no repeated subproblem computations. Cached results may help later separate requests, but there is no overlap within this first chain.
- 6ExplanationCheck optimal pieces
An optimization problem has optimal substructure when its optimal solutions contain compatible optimal solutions to smaller problems.
A shortest route through an intermediate point uses a shortest route to that point. Otherwise a shorter replacement would improve the whole route. The replacement must remain feasible: an endpoint-only longest-simple-path state can fail because its replacement may reuse vertices needed later.
- 7ConnectionCounting needs separate cases
Counting does not choose a maximum or minimum. It adds counts, so each object must belong to exactly one case.
A right-and-down route into a cell has one last move: from above or from the left. These cases cover every route and do not overlap. Grouping routes by every cell they pass through would not work the same way; one route can pass through several named cells and be counted more than once.
- 8ExplanationDraw arrows toward the users
Create one graph vertex for each subproblem. Draw an arrow from a state to a state that uses its answer. For Fibonacci, smaller arguments point toward the larger arguments that read them.
A topological order places each dependency first. It exists when the graph has no directed cycle. This graph explains why either a recursive dependency traversal or an explicit table order can compute the same answers.
- 9ExampleLook past the first coin
With coins 1, 3 and 4, largest-first makes amount 6 as
4 + 1 + 1, using three coins. Starting with 3 leaves amount 3, which needs just one more coin. The total is two.The locally largest coin does not account for the cost of its remainder. Dynamic programming compares every legal last coin together with the best result for the remaining amount, then chooses a minimum.
- 10ChallengeCan these cases be added?
A counter splits grid routes into “uses the top boundary” and “uses the left boundary.” A route may use both. Why is adding those counts unsafe, and what property should a replacement split have?
---reveal---
A route using both boundaries belongs to both cases and is counted twice. A safe split covers every route exactly once. Using the final move, from above or from the left, gives that partition for right-and-down routes.
- 11ChallengeOverlap is only part of the test
A proposed recursive solver repeats states, but its state remembers only path endpoints and forgets which vertices have already been used. What must be checked before a cache can make it a correct longest-simple-path solution?
---reveal---
The state must retain enough information to enforce the no-repeated-vertex constraint when pieces combine. Sharing an incomplete state only reuses an answer to the wrong question. The corrected state space must also be small enough to compute.
- 12RecapA test for a promising design
Check three things: repeated requests, a manageable distinct state set, and a correct way to combine the smaller answers.
For optimization, test whether replacing a piece preserves a feasible optimal solution. For counting, check that cases are disjoint and exhaustive. Then draw dependency arrows from earlier answers to their users and find an order without cycles.
2Turn a recurrence into Python
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTwo ways to schedule the work
- 2ExampleCheck before computing
- 3TipGive the cache a complete key
- 4ChallengeSpot the false cache miss
- 5ExplanationTurn dependencies into loop order
- 6ExampleFill one grid cell at a time
- 7ExampleRemove routes through the obstacle
- 8Key InsightDiscard values after their last use
- 9ChallengeInclude the empty position
- 10ExampleA query may use very little of a table
- 11ConnectionCompare the actual storage
- 12ChallengeChoose for a long dense computation
- 13RecapKeep the recurrence, change the machinery
3Design and recover a complete solution
18 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionBegin with the question each entry answers
- 2ExplanationChoose the shape of the state
- 3ExampleKeep an endpoint for increasing subsequences
- 4ChallengeFind the original answer
- 5ExplanationTry each first rod piece
- 6ExampleCompute the next rod value
- 7TipKeep impossibility out of the minimum
- 8ConnectionDecide whether order distinguishes results
- 9ChallengeChoose the empty count
- 10ExplanationCount candidates across states
- 11ExampleSeparate time from retained space
- 12ChallengeCharge the missing scan
- 13ExplanationSave a decision beside the value
- 14ExampleTake the first recorded cut
- 15ExampleFinish the remaining cuts
- 16Key InsightA tie does not mean an error
- 17ChallengeCan the value alone recover the pieces?
- 18RecapA complete design has six parts
4Recover a longest common subsequence
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionKeep shared order, allow gaps
- 2ExampleGaps are allowed, reordering is not
- 3ExplanationGive each cell a prefix question
- 4ExplanationA matching pair extends the diagonal
- 5ExplanationA mismatch skips an endpoint
- 6ChallengeInterpret a table position
- 7ExampleFill the early rows
- 8ExampleFinish the prefix grid
- 9ExampleStart traceback at the final match
- 10ExampleCollect G and T, then handle a tie
- 11Key InsightPut the matches back in forward order
- 12ChallengeWhat may a mismatch record?
- 13TipChoose storage for the requested output
- 14ConnectionReuse the layout for edit distance
- 15ChallengeDiagnose a contiguous-match rule
- 16RecapFrom prefix lengths to shared text
5Choose subsets and pack whole items
17 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionA shared shape with different questions
- 2ExplanationDefine exact reachability
- 3ExampleBuild the reachable totals
- 4ExampleRecover one subset
- 5Key InsightA downward pass protects old values
- 6ChallengeTest the repeated-input bug
- 7ExplanationReplace reachability with best value
- 8ExampleEvaluate a take-or-skip cell
- 9ExampleFollow the chosen item rows
- 10ConnectionPermit copies only when intended
- 11TipExact filling changes the base
- 12ChallengeSeparate the three variants
- 13ExplanationA short number can make a wide table
- 14ExampleEstimate both updates and storage
- 15ConnectionMeasurement scale changes the index range
- 16ChallengeDoes one list make the time polynomial?
- 17RecapRead the rules before choosing the loops
Dynamic Programming in Python practice questions
Set 1: States, tables and first solutions10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
L[2][2] store?Show answerHide answer
Question 3 of 10
2, 7, 9, 13 may be used once. How many subsets sum to exactly 22?Show answerHide answer
9 + 13 and 2 + 7 + 13, so the count is two. The triple 2 + 7 + 9 totals 18 and does not add another solution. Reordering 9 + 13 as 13 + 9 also adds no subset, because subset sum distinguishes selected inputs, not their written order.Question 4 of 10
solve(4, 7) from two separate branches. What feature makes this a candidate for storing and reusing an answer?Show answerHide answer
Question 5 of 10
Show answerHide answer
2 + 2 + 3 makes 7 as an unordered combination. The 3 can occupy any of three positions, giving three ordered sequences. Counting two combinations usually treats a rearrangement as a new selection, even though the counts of each denomination have not changed.Question 6 of 10
i fixed items with remaining capacity c. What key identifies its subproblem?Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
2, 7, 3, 5, 1, what are the lengths of the longest strictly increasing subsequences ending at each position?Show answerHide answer
2, 3, while the final 1 has no smaller predecessor. Keeping 3 at the final position would record the best length anywhere in the prefix, not a subsequence ending at that position.Question 9 of 10
Show answerHide answer
Question 10 of 10
Show answerHide answer
Set 2: Implementation choices and recovered answers10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
f(k - 1) before returning, until it reaches 0. Within one evaluation of f(12), how many repeated subproblem computations can caching remove?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
solve(i, c) reads a list of items outside its arguments. After solving one input, the program replaces that list and calls the same helper again. What change makes the new result reliable?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
i scans all earlier positions. What are its time and value-table space bounds for n inputs?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
(i, j) for 1 ≤ j ≤ i ≤ n. Computing each state scans j candidates. What is the total time growth, and how much space stores one value for every state?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
can[0] = True. It processes input numbers 4 and 7, updating targets upward. What answer does it report for target 12, and what is the correct answer?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 3: Reasoning about states and variants10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
D[i] reads only D[i + 1] and D[i + 2] when those indices exist. The needed end bases are ready. In what index order should the remaining entries be filled?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
cut[6] = 2, cut[4] = 1 and cut[3] = 3. What pieces does the reconstruction return?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 4: Debugging recurrences and traceback10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
False. How should the function check whether a key already has a stored answer?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
(0, 0), move only right or down, and block cell (1, 0). How many routes reach (3, 2)?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
1, 9 and 1, 2 both have length 2, and the next value is 3. What information is missing, and what state fixes the problem?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
4, 6, 2, 3, 5, 1, what is the LIS length, and why is the final endpoint state insufficient to report it?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 5: Transfer to unfamiliar constraints10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
(0, 0) to (2, 2). It adds the number of routes starting right to the number ending down and gets 6, matching the true total. Is that case split valid, and why?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
B[i] reads A[i - 1], and A[i] reads B[i]. Values at index 0 are ready. What computation order works for positive indices?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
ways[0] = 1, then loops over amounts outside and possible last sizes inside. What does it return for amount 9, and what does that count mean?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
L[i - 1][j - 1]. What result does this give for “AB” and “ACB”, compared with the correct LCS length?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
2, 3, 5, 7 seconds. Each task is distinct and available once. What count and update rule fit a single-list DP?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
B
Base case
Bit length
C
Cache
Cache key
Call overhead
Capacity
Choice table
Common subsequence
Counting problem
D
Decision problem
Distinct subproblem
Dynamic programming
E
Edit distance
Empty subset
Encoded input size
Endpoint state
Exact-fill knapsack
Exhaustive search
F
Filling order
Fractional knapsack
H
Hashable argument
I
Infeasible state
Integer overflow
Interval state
L
Longest common subsequence
Longest increasing subsequence
4, 1, 3, 6, the subsequence 1, 3, 6 has length 3; equal values would not extend it.M
Memoization
O
Optimal substructure
Optimization problem
Ordered sequence
2, 3 and 3, 2 count separately when order matters, even though both total 5.Overlapping subproblems
fib(4) overlap even if those calls occur at different depths in the tree.P
Polynomial time
Prefix
Prefix-pair table
Pseudopolynomial time
R
Reachability table
Reachable state
Reconstruction
Recurrence
Recursion depth
Recursion tree
Rod cutting
Rolling storage
S
Space complexity
State
K[i][c] records a value for a particular available-item prefix and a particular capacity.Subproblem graph
Subsequence
Subset count
Subset sum
4, 6, 9, target 10 is reachable with 4 and 6, but the same 4 cannot be used twice.Substitution
Substring
Suffix
T
Tabulation
Tie-breaking rule
Time complexity
Topological order
Traceback
Transition
U
Unary encoding
Unbounded knapsack
Unordered combination
1 + 4 once, without adding another combination for 4 + 1.W
Work per state
#
0/1 knapsack
- 1Big-O Notation
- 2Recursion
- 3Linear Data Structures
- 4Sorting and Searching
- 5Hash Tables
- 6Binary Search Trees
- 7Heaps and Priority Queues
- 8Graph Traversal
- 9Shortest Path Algorithms
- 10Dynamic Programming in Python
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.