Dynamic Programming in Python: Memoization and Recurrences

Learn to solve optimization and counting problems with dynamic programming. Find the repeated work hidden in recursive solutions, define subproblems, write recurrences and implement them with memoization or a bottom-up table in Python. Then apply the method to longest common subsequence, subset sum and knapsack, recover the optimal solution from the table, and explain why knapsack's running time depends on the size of its numbers.

IntermediateLesson 10 of 10 in Data Structures and Algorithms Course

What you will learn

  1. 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 solution
      Trace 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 solve
      Recognize optimization, counting and decision problems whose answers can be built from smaller subproblems, and explain why some problems lack this structure.
  2. 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 memoization
      Add 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 tabulation
      Build 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 tabulation
      Compare the two implementations on ease of writing, subproblems computed, speed, recursion depth and memory, and test either one against brute force.
  3. 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 problem
      Define 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 counting
      Build 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 solution
      Estimate 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 table
      Recover the choices behind an optimal value, either from a stored choice table or by retracing the recurrence, and handle ties between equally good solutions.
  4. 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 recurrence
      Distinguish 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 subsequence
      Fill the LCS table in a valid order, read its entries, trace back one longest common subsequence and state the time and memory used.
  5. 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 values
      Decide 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 table
      Fill 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 time
      Measure 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.

Dynamic Programming in Python study guide

5 chapters

1

When 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 F(0)=0 and F(1)=1. Each later value is the sum of the previous two:

F(n)=F(n−1)+F(n−2).

The values through F(10) 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:

Argument543210
Calls112353

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 2F(n+1)−1. It grows by a factor approaching φ≈1.618 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 typeQuestionHow alternatives combine
OptimizationWhat is the fewest number of coins?Take a minimum
CountingHow many routes reach a grid cell?Add counts of disjoint cases
DecisionCan 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 F(k) to F(k+1) and F(k+2) 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.
2

Top-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, s reached states and at most k constant-time choices per state take O(sk) 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.

RowColumn 0Column 1Column 2Column 3
01111
11234
213610

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
FeatureMemoizationTabulation
OrderDiscovered by recursive callsWritten explicitly in loops
States computedOnly those reached by the requestUsually the whole chosen table
Call stackRetained during recursionNo recursive stack
Typical overheadCalls and cache lookupsIndexing and loop operations
Storage savingsAvoids unreached statesCan 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 4×601=2404 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 210=1024 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.
3

Designing 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:

ShapeMeaningNumber of states
PrefixFirst i elementsn + 1, including empty
SuffixFrom index i to the endn + 1, including empty
SubstringContiguous interval from i to jQuadratic in n
Two prefixesFirst i and first j elements of two sequences(m + 1)(n + 1)
Items and amountAvailable prefix and remaining capacity or targetProduct 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 L(i) as the longest increasing subsequence ending exactly at position i. Its endpoint is now known. To extend from an earlier position j, require both j<i and aj<ai:

L(i)=1+max⁡{L(j):j<i and aj<ai},

with L(i)=1 if the set is empty. The one counts the element at position i 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 n meters can be cut into whole-meter pieces. A piece of length i has unitless price pi. Let r(n) be the best total price for the rod. If its first piece has length i, that piece earns pi and the remaining rod earns r(n−i):

r(0)=0,r(n)=max⁡1≤i≤n(pi+r(n−i)).

The option i=n 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 2+7=9, 5+5=10, 7+2=9 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 M(a) be the fewest coins totaling exactly a. Try each possible last coin:

M(0)=0,M(a)=1+min⁡{M(a−c):c≤a}.

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
AlgorithmStatesWork at a stateTotal time
FibonacciLinear in nConstantΘ(n)
Rod cuttingLinear in nUp to n cutsΘ(n2)
Simple LIS DPOne per endpointScan earlier endpointsΘ(n2)
LCSPrefix-pair gridConstantΘ(mn)
0/1 knapsackItem-capacity gridConstantΘ(nW)

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:

1+2+⋯+n=n(n+1)2.

Counting only the five nonempty states would miss most of the work. The same issue occurs in LIS: although there are only n 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 (m+1)(n+1) entries. A full knapsack table has (n+1)(W+1) 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 nW 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 1.1×1012 subsets. A capacity-indexed table for 40 items and capacity 1,000 contains 41×1001=41041 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 109+7 to keep values bounded. State-update bounds such as O(nT) 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 2+5+5=12.

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 2+r(4)=2+10=12. 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 5+7=12. 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 O(n) steps. Knapsack traceback takes at most one step per item, and LCS takes O(m+n) 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.
4

Longest 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 m, giving 2m 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 L[i][j] be the LCS length of the first i elements of X and first j elements of Y. The ranges are 0≤i≤m and 0≤j≤n. Row 0 and column 0 represent empty prefixes:

L[i][0]=L[0][j]=0.

An empty sequence shares no nonempty subsequence with another sequence. The requested full-input answer is L[m][n]. The table contains (m+1)(n+1) states, including the empty cases.

Compare the last two elements

If the prefix endpoints match, include that matching pair and solve the shorter prefixes:

L[i][j]=L[i−1][j−1]+1when xi=yj.

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:

L[i][j]=max⁡(L[i−1][j],L[i][j−1])when xi≠yj.

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 L[3][3]=1+1=2, represented by “AT” or “CT.”

Translate positions into Python

The mathematical element xi 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 i corresponds to Python character index i - 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 endingEmptyCATGTA
Empty0000000
A0011111
C0111111
T0112222
G0112333
A0122334

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 Θ(mn) time and space. Traceback adds at most m+n moves. Two inputs of 1,000 characters need 1001×1001=1002001 entries. If only the length is needed, two rows suffice. Put the shorter sequence on the columns for O(min⁡(m,n)) 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 E[i][0]=i and E[0][j]=j. 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.
5

Subset 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 S[i][t] mean that a subset of the first i numbers totals exactly t, for 0≤i≤n and 0≤t≤T. With no numbers, only zero is reachable: S[0][0] is true and S[0][t] is false for positive t.

For number ai, either skip it and use S[i−1][t], or take it and use S[i−1][t−ai] 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 S[i][t], skip the current number if S[i−1][t] 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: 3+5+6=14. 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 N[i][t] and add the skip and take counts, using zero when the take case does not fit. Start with N[0][0]=1 and other entries zero. For the example, N[4][14]=2. Subsets distinguish input positions: two equal numbers in separate positions are separate available choices.

The decision table takes O(nT) time and space; the single list uses O(T) 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 i has positive integer weight wi and value vi. Choose whole items at most once, with total weight at most capacity W, to maximize value.

Compare taking and leaving

Let K[i][c] be the best value using the first i items with capacity c. With no items, every capacity has value 0. When the current item fits:

K[i][c]=max⁡(K[i−1][c],vi+K[i−1][c−wi]).

The first candidate skips the item. The second takes it and solves the remaining capacity using earlier items. If it is too heavy, copy K[i−1][c].

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 items0 kg1 kg2 kg3 kg4 kg5 kg6 kg7 kg
None00000000
A05555555
A, B055516212121
A, B, C0551116212127
A, B, C, D0551116212127

At K[3][7], skipping C gives 21. Taking C gives 11+K[2][4]=11+16=27. 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 K[4][7]. It equals the entry above, so skip D. At K[3][7] the value exceeds the entry above, so take C and reduce capacity to 4. At K[2][4] 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 O(nW) and the list uses O(W) space. A full table uses O(nW) space and supports the traceback above.

Change the rules deliberately
VariantWhat changes
UnboundedRepeated copies are allowed; process capacities upward
Exact capacityOnly total weight exactly equal to the capacity counts as feasible
FractionalPieces of items are allowed; it is a different optimization problem

For unbounded knapsack, U(c)=max⁡(0,max⁡{vi+U(c−wi):wi≤c}). Use U(0)=0; 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 K[0][0]=0 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 W>0 needs ⌊log⁡2W⌋+1 binary digits. A list of n numbers below 2b needs about nb bits. Polynomial time means a polynomial bound in this encoded input length.

A capacity of 1,000,000 fits in 20 bits because 220=1048576. Yet a capacity-indexed table needs 1,000,001 columns. With 100 items, it holds about 108 entries. The number of columns is the value plus one, not the bit count plus one.

Knapsack's O(nW) 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 b bits, its value can approach 2b. Adding ten bits can multiply the number of columns by about 210=1024.

Subset sum has the same issue with target T in its O(nT) table. LCS differs: its dimensions count input symbols. The lengths m and n correspond directly to the amount of sequence data, so O(mn) is polynomial in input length.

Estimate updates and storage separately

For target 3,000,000 and 20 numbers, about 6×107 updates are needed. With 10,000 numbers, that grows to about 3×1010 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 (n+1)(T+1) entries. A single list retains only T+1 entries but still performs about nT updates. A target near 260≈1.15×1018 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 109, the table requires about 3×1010 entries, compared with 230≈1.07×109 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, O(nW) 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

5 Walkthroughs

1

Find the work worth sharing

12 steps
Trace repeated recursive requests and check whether smaller answers combine into a correct solution.
  1. 1
    IntroductionOne 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.

  2. 2
    ExplanationStart with the Fibonacci rule

    The first two values are F(0)=0 and F(1)=1. For later arguments, use F(n)=F(n−1)+F(n−2). The values begin 0, 1, 1, 2, 3, 5.

    Direct recursion asks for both smaller values each time. To compute fib(5), it requests fib(4) and fib(3). Expanding fib(4) requests fib(3) again. Both requests ask exactly the same question.

  3. 3
    ExampleCount 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.

  4. 4
    AnalogyShare 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.

  5. 5
    ChallengeWould 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.

  6. 6
    ExplanationCheck 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.

  7. 7
    ConnectionCounting 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.

  8. 8
    ExplanationDraw 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.

  9. 9
    ExampleLook 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.

  10. 10
    ChallengeCan 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.

  11. 11
    ChallengeOverlap 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.

  12. 12
    RecapA 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.

2

Turn a recurrence into Python

13 steps
Compare cached recursion with table filling, then decide which implementation fits the state space and required output.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionTwo ways to schedule the work
  2. 2
    ExampleCheck before computing
  3. 3
    TipGive the cache a complete key
  4. 4
    ChallengeSpot the false cache miss
  5. 5
    ExplanationTurn dependencies into loop order
  6. 6
    ExampleFill one grid cell at a time
  7. 7
    ExampleRemove routes through the obstacle
  8. 8
    Key InsightDiscard values after their last use
  9. 9
    ChallengeInclude the empty position
  10. 10
    ExampleA query may use very little of a table
  11. 11
    ConnectionCompare the actual storage
  12. 12
    ChallengeChoose for a long dense computation
  13. 13
    RecapKeep the recurrence, change the machinery
3

Design and recover a complete solution

18 steps
Build endpoint and amount states, derive choice recurrences, estimate their cost and recover the decisions behind the optimum.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionBegin with the question each entry answers
  2. 2
    ExplanationChoose the shape of the state
  3. 3
    ExampleKeep an endpoint for increasing subsequences
  4. 4
    ChallengeFind the original answer
  5. 5
    ExplanationTry each first rod piece
  6. 6
    ExampleCompute the next rod value
  7. 7
    TipKeep impossibility out of the minimum
  8. 8
    ConnectionDecide whether order distinguishes results
  9. 9
    ChallengeChoose the empty count
  10. 10
    ExplanationCount candidates across states
  11. 11
    ExampleSeparate time from retained space
  12. 12
    ChallengeCharge the missing scan
  13. 13
    ExplanationSave a decision beside the value
  14. 14
    ExampleTake the first recorded cut
  15. 15
    ExampleFinish the remaining cuts
  16. 16
    Key InsightA tie does not mean an error
  17. 17
    ChallengeCan the value alone recover the pieces?
  18. 18
    RecapA complete design has six parts
4

Recover a longest common subsequence

16 steps
Use prefix states to fill an LCS table and follow its matching decisions backward.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionKeep shared order, allow gaps
  2. 2
    ExampleGaps are allowed, reordering is not
  3. 3
    ExplanationGive each cell a prefix question
  4. 4
    ExplanationA matching pair extends the diagonal
  5. 5
    ExplanationA mismatch skips an endpoint
  6. 6
    ChallengeInterpret a table position
  7. 7
    ExampleFill the early rows
  8. 8
    ExampleFinish the prefix grid
  9. 9
    ExampleStart traceback at the final match
  10. 10
    ExampleCollect G and T, then handle a tie
  11. 11
    Key InsightPut the matches back in forward order
  12. 12
    ChallengeWhat may a mismatch record?
  13. 13
    TipChoose storage for the requested output
  14. 14
    ConnectionReuse the layout for edit distance
  15. 15
    ChallengeDiagnose a contiguous-match rule
  16. 16
    RecapFrom prefix lengths to shared text
5

Choose subsets and pack whole items

17 steps
Build item-and-amount states, distinguish reuse and exact-fill rules, and estimate the numeric cost of the table.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionA shared shape with different questions
  2. 2
    ExplanationDefine exact reachability
  3. 3
    ExampleBuild the reachable totals
  4. 4
    ExampleRecover one subset
  5. 5
    Key InsightA downward pass protects old values
  6. 6
    ChallengeTest the repeated-input bug
  7. 7
    ExplanationReplace reachability with best value
  8. 8
    ExampleEvaluate a take-or-skip cell
  9. 9
    ExampleFollow the chosen item rows
  10. 10
    ConnectionPermit copies only when intended
  11. 11
    TipExact filling changes the base
  12. 12
    ChallengeSeparate the three variants
  13. 13
    ExplanationA short number can make a wide table
  14. 14
    ExampleEstimate both updates and storage
  15. 15
    ConnectionMeasurement scale changes the index range
  16. 16
    ChallengeDoes one list make the time polynomial?
  17. 17
    RecapRead the rules before choosing the loops

Dynamic Programming in Python practice questions

50 Practice Questions in 5 sets

Set 1: States, tables and first solutions10 Practice Questions

Question 1 of 10

What is a subsequence of the string “BREAD” that is not a contiguous substring?
  1. “BAD”
  2. “REA”
  3. “BAR”
  4. “DAE”
Show answerHide answer
Answer: A
“BAD” keeps B, A and D in their original order while skipping R and E, so it is a subsequence with gaps. “REA” is contiguous and therefore also a substring. “BAR” changes the order of A and R, so the presence of all three letters in the input is not enough to make it a subsequence.

Question 2 of 10

An LCS table uses X = “CAB” and Y = “ACB”. What does its entry L[2][2] store?
  1. Length 2 for the full strings.
  2. Length 2 for “CA” and “AC”.
  3. Length 1 for “CA” and “AC”.
  4. Length 1 for “AB” and “CB”.
Show answerHide answer
Answer: C
Row 2 and column 2 represent the prefixes “CA” and “AC”. They share either A or C, but cannot share both in the same order, so their LCS length is 1. The full strings have length-2 common subsequences, but that result belongs to a later cell with both full prefix lengths.

Question 3 of 10

Each number in 2, 7, 9, 13 may be used once. How many subsets sum to exactly 22?
  1. 2 subsets.
  2. 1 subset.
  3. 3 subsets.
  4. 4 subsets.
Show answerHide answer
Answer: A
The subsets are 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

An uncached evaluation requests solve(4, 7) from two separate branches. What feature makes this a candidate for storing and reusing an answer?
  1. The two branches have the same depth in the call tree.
  2. The two branches return answers of the same data type.
  3. The two calls request the same fully specified subproblem.
  4. The two calls each create more than one recursive branch.
Show answerHide answer
Answer: C
Both calls ask the same question, so one computed result can serve both requests. Equal depth alone does not establish overlap: two calls at the same depth can have different arguments and need different answers. The cache must identify the whole subproblem, here the pair of arguments.

Question 5 of 10

With unlimited coin values 2 and 3, how many unordered combinations and ordered sequences total 7?
  1. 1 combination and 3 sequences.
  2. 2 combinations and 3 sequences.
  3. 1 combination and 2 sequences.
  4. 2 combinations and 4 sequences.
Show answerHide answer
Answer: A
Only 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

A cached function finds the best value using the first i fixed items with remaining capacity c. What key identifies its subproblem?
  1. The item index i alone.
  2. The remaining capacity c alone.
  3. The recursion depth alone.
  4. The ordered pair (i, c).
Show answerHide answer
Answer: D
The answer depends on both which items remain available and how much capacity remains. Keying only by the index mixes capacities that can admit different selections. The fixed item data may stay outside the key while it remains unchanged, but both changing state parameters must be included.

Question 7 of 10

A table stores answers for every prefix of a nine-element sequence, including the empty prefix. How many entries does it need?
  1. 8 entries.
  2. 10 entries.
  3. 9 entries.
  4. 11 entries.
Show answerHide answer
Answer: B
Prefix lengths run from 0 through 9, giving ten entries. Nine entries would represent the nine nonempty lengths but leave no separate position for the empty prefix. That base state often supplies the predecessor used when computing the first nonempty state.

Question 8 of 10

For the list 2, 7, 3, 5, 1, what are the lengths of the longest strictly increasing subsequences ending at each position?
  1. 1, 2, 2, 3, 3
  2. 1, 2, 2, 3, 1
  3. 1, 2, 3, 4, 1
  4. 1, 2, 1, 2, 1
Show answerHide answer
Answer: B
The endpoints 2, 7, 3, 5 and 1 have lengths 1, 2, 2, 3 and 1. The value 5 extends 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

Unlimited coins have values 2, 5 and 7. What is the fewest number of coins making exactly 11?
  1. 2 coins.
  2. 5 coins.
  3. 4 coins.
  4. 3 coins.
Show answerHide answer
Answer: D
The coins 7, 2 and 2 make 11 with three coins. No one coin or pair from these denominations totals 11, so fewer cannot work. Treating 7 plus an impossible remainder as a two-coin solution would confuse a missing coin of value 4 with a reachable amount made from two 2s.

Question 10 of 10

Whole items P, Q and R have (weight in kg, value) pairs (2, 7), (5, 16) and (4, 13). Each is available once and capacity is 9 kg. What selection maximizes value?
  1. P and Q, for value 23.
  2. P and R, for value 20.
  3. P, Q and R, for value 36.
  4. Q and R, for value 29.
Show answerHide answer
Answer: D
Q and R fit exactly at 9 kg and give value 29. P has the highest value per kilogram, but taking it first leaves room for only one other item and reaches at most 23. All three would give 36 but weigh 11 kg, so that attractive total violates the capacity constraint.
Set 2: Implementation choices and recovered answers10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A recursive function calls only f(k - 1) before returning, until it reaches 0. Within one evaluation of f(12), how many repeated subproblem computations can caching remove?
  1. One computation.
  2. No computations.
  3. Twelve computations.
  4. Thirteen computations.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A cached helper 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?
  1. Keep the cache and reverse the new item list.
  2. Keep the cache and increase the initial capacity.
  3. Keep the cache and convert only c to a tuple.
  4. Clear the cache before solving the changed input.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A recurrence has a huge rectangular state range but a query reaches only a few states and has shallow dependency chains. Which implementation feature most favors memoization?
  1. It computes only states reached by that query.
  2. It guarantees constant extra memory for the query.
  3. It eliminates the need to define all base cases.
  4. It makes each recursive operation faster than a loop.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Coins have values 1, 4 and 6, with unlimited copies. For amount 8, how do largest-first selection and the true minimum compare?
  1. Largest-first uses 3 coins; the minimum is 3.
  2. Largest-first uses 2 coins; the minimum is 2.
  3. Largest-first uses 3 coins; the minimum is 2.
  4. Largest-first uses 4 coins; the minimum is 2.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

An endpoint DP has one state per input position. State i scans all earlier positions. What are its time and value-table space bounds for n inputs?
  1. Linear time and linear space.
  2. Quadratic time and quadratic space.
  3. Linear time and quadratic space.
  4. Quadratic time and linear space.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A DP has states (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?
  1. Quadratic time and linear space.
  2. Cubic time and quadratic space.
  3. Cubic time and cubic space.
  4. Quadratic time and quadratic space.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Two nonempty prefixes end in different characters. What does the LCS recurrence do at their cell?
  1. Add 1 to the diagonal entry.
  2. Reset the current entry to 0.
  3. Take the maximum above or left.
  4. Take the sum of above and left.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

LCS traceback for X = “DOG” and Y = “DIG” has just recorded G. At prefixes “DO” and “DI”, the upper and left entries tie at 1. What may it do next?
  1. Move up or left without recording a character.
  2. Move diagonally and record O from the first input.
  3. Move diagonally and record I from the second input.
  4. Move up or left and record both differing characters.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A one-list subset-sum program starts with only 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?
  1. It reports false; false is correct.
  2. It reports true; false is correct.
  3. It reports true; true is correct.
  4. It reports false; true is correct.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A capacity changes from 255 to 511 while the item count stays fixed. Approximately how do the capacity’s binary length and the table’s column count change?
  1. Both become about twice as large.
  2. Both increase by exactly one.
  3. The length grows by one bit; columns double.
  4. The length doubles; columns grow by one.
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

A grid-route counter splits routes into “passes through cell A” and “passes through cell B.” Some routes pass through both. What is wrong with simply adding the two counts?
  1. It forgets that each route must have equal length.
  2. It counts routes through both cells too few times.
  3. It changes a counting problem into optimization.
  4. It counts routes through both cells more than once.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A suffix state 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?
  1. Increasing order, starting with index 0.
  2. Decreasing order, starting near the end.
  3. Even indices first, then odd indices.
  4. Any order, since the bases are ready.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A memoized recurrence visits nearly every state in a dense table and can follow 50,000 dependencies in one chain. Only the final value is required, and each row reads the previous row. What implementation change best addresses both stack depth and storage?
  1. Use a larger cache while keeping the recursive chain.
  2. Keep recursion but key only by the row index.
  3. Use bottom-up loops with previous and current rows.
  4. Keep a full bottom-up table and a recursive traceback.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A choice table for a 6 m rod gives first pieces cut[6] = 2, cut[4] = 1 and cut[3] = 3. What pieces does the reconstruction return?
  1. 2 m, 1 m and 3 m.
  2. 2 m and 4 m.
  3. 2 m, 4 m and 3 m.
  4. 2 m, 1 m and 1 m.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A full LCS table compares sequences of lengths 6 and 8, including empty prefixes. How many entries does it contain?
  1. 48 entries.
  2. 54 entries.
  3. 63 entries.
  4. 56 entries.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A task asks for one optimal solution and has no secondary objective. At a traceback state, two legal choices both achieve the stored optimal value. How should a deterministic implementation handle the tie?
  1. Prefer the choice with the largest remaining value.
  2. Reject the state because the optimum is ambiguous.
  3. Combine both choices into one reported solution.
  4. Follow either choice using a consistent tie rule.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What is the LCS length of “AXBYC” and “ABC”, and their longest common substring length?
  1. LCS 2; substring 2.
  2. LCS 3; substring 1.
  3. LCS 3; substring 3.
  4. LCS 2; substring 1.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Inputs are two distinct entries of value 3 and one entry of value 6. Each entry can be used once. For target 6, what should a subset-counting DP return, and how should its one-list targets run?
  1. 2 subsets; targets downward.
  2. 3 subsets; targets downward.
  3. 2 subsets; targets upward.
  4. 3 subsets; targets upward.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Items have (weight in kg, value) pairs (3, 8) and (5, 11). Capacity is 6 kg. What values do the at-most-capacity 0/1 and unbounded versions return?
  1. 0/1: 16; unbounded: 16.
  2. 0/1: 8; unbounded: 11.
  3. 0/1: 11; unbounded: 11.
  4. 0/1: 11; unbounded: 16.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Why is a length-indexed LCS table polynomial-time while a binary-capacity-indexed knapsack table is pseudopolynomial?
  1. LCS dimensions count input symbols; capacity is a numeric magnitude.
  2. LCS uses a maximum; knapsack compares two different arithmetic sums.
  3. LCS has two dimensions; knapsack has one dimension after compression.
  4. LCS has constant-size cells; every knapsack cell requires a full subset.
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

An uncached run makes 80 recursive calls using 12 distinct keys. A memoized version makes 25 calls and computes each key’s answer once. How many memoized calls return already-stored answers?
  1. 13 calls.
  2. 12 calls.
  3. 55 calls.
  4. 68 calls.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

In an undirected five-vertex cycle p–q–r–s–t–p, a program finds a longest simple p-to-r path, then replaces its p-to-s segment by a longest simple p-to-s path. Why can that replacement fail?
  1. The replacement must have fewer edges than the segment.
  2. The replacement cannot have the same endpoint as the segment.
  3. The replacement can reuse vertices needed by the remaining path.
  4. The replacement must turn an undirected edge into a directed one.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A manual decision-result cache can store False. How should the function check whether a key already has a stored answer?
  1. if memo.get(key):
  2. if key in memo:
  3. if memo[key] == True:
  4. if key == False:
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A grid has four rows and three columns of cells. Start at (0, 0), move only right or down, and block cell (1, 0). How many routes reach (3, 2)?
  1. 10 routes.
  2. 8 routes.
  3. 3 routes.
  4. 4 routes.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A programmer stores only the best increasing-subsequence length in each prefix. Prefixes 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?
  1. The last selected value; store a best length for each exact endpoint.
  2. The prefix length; store a single best length for the entire input.
  3. The number of prefixes; store how often each length has occurred.
  4. The largest input value; store a single best length for each full prefix.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

For unlimited coins 4 and 6, a minimum-coin table incorrectly initializes every amount to 0, then takes the minimum of its current entry and each candidate. What happens at amount 8, and what initialization fixes the issue?
  1. It returns 1; initialize every amount to infinity.
  2. It returns 0; initialize only amount 0 to 0 and the rest to infinity.
  3. It returns 2; initialize only amount 0 to 1 and the rest to 0.
  4. It returns infinity; initialize all even amounts to 0 before updates.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

For 4, 6, 2, 3, 5, 1, what is the LIS length, and why is the final endpoint state insufficient to report it?
  1. The length is 4; the final endpoint has length 1.
  2. The length is 2; the final endpoint has length 1.
  3. The length is 3; the final endpoint has length 3.
  4. The length is 3; the final endpoint has length 1.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

An LCS implementation correctly fills its table for “ABCD” and “ACBD”. During traceback it records a character on every diagonal move, including mismatches. Why can a result of length 4 be invalid even though its characters come from the inputs?
  1. Every LCS must contain all characters shared by the two strings.
  2. Traceback must always choose left on tied predecessor values.
  3. The recorded characters may fail to form a subsequence of both inputs.
  4. The table length increases whenever either input contains a new letter.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Whole items have (weight in kg, value) pairs (2, 5), (3, 8) and (6, 14), each once. What are the optimal values at capacity 7 kg for the at-most and exact-fill versions?
  1. At most: 13; exact fill: 13.
  2. At most: 14; exact fill: 14.
  3. At most: 14; exact fill: impossible.
  4. At most: 13; exact fill: impossible.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A value-only knapsack program changes from a full item-capacity table to one list, preserving its correct updates. How do its time and space bounds change?
  1. Time becomes O(W); space remains O(nW).
  2. Time remains O(nW); space becomes O(W).
  3. Time becomes O(n + W); space becomes O(n).
  4. Time remains O(nW); space becomes O(n).
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

A route counter for a three-row, three-column grid of cells allows only right and down moves from (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?
  1. Yes: both cases have three routes, so their counts may be added.
  2. No: some routes are counted twice while others are omitted.
  3. No: each case has two routes, so the combined count should be four.
  4. Yes: a route has a first and last move, so it belongs to exactly one case.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Two DP implementations agree on many inputs but were translated from the same recurrence. What extra check best tests whether their common recurrence is wrong?
  1. Compare with exhaustive search on many small inputs.
  2. Compare their running times on one large random input.
  3. Compare the names used for their table indices.
  4. Compare the number of entries in their final caches.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Two state families use these dependencies: 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?
  1. All A states in increasing order, then all B states.
  2. At each increasing index, compute A[i] then B[i].
  3. No order works because same-index dependencies form a cycle.
  4. At each increasing index, compute B[i] then A[i].
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A counter totals unlimited selections of sizes 2 and 5 using 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?
  1. 1, counting unordered selections.
  2. 2, counting unordered selections.
  3. 3, counting ordered sequences.
  4. 4, counting ordered sequences.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A rod has prices 3, 4, 8 and 9 for whole lengths 1–4 m. A choice table keeps the first maximizing first-piece length, tested in increasing order. What pieces does traceback return for 4 m?
  1. One 4 m piece.
  2. A 1 m and a 3 m piece.
  3. Two 2 m pieces.
  4. Four 1 m pieces.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A knapsack task asks for both the best value and the chosen items. What information does ordinary table traceback require after filling?
  1. Only the final scalar optimal value.
  2. Only the items sorted by value per kilogram.
  3. The full value table or adequate choice records.
  4. Only the final row with all earlier rows discarded.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A programmer replaces the LCS mismatch recurrence with L[i - 1][j - 1]. What result does this give for “AB” and “ACB”, compared with the correct LCS length?
  1. It gives 1; the correct length is 2.
  2. It gives 0; the correct length is 2.
  3. It gives 2; the correct length is 2.
  4. It gives 1; the correct length is 1.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

The LCS table for “BA” and “AB” has value 1 at the full-input cell, where the endpoints differ and the upper and left predecessors tie. What results follow from choosing up versus left, using ordinary matching traceback afterward?
  1. Up gives “A”; left gives “B”.
  2. Up gives “B”; left gives “A”.
  3. Up gives “A”; left gives “A”.
  4. Up gives “B”; left gives “B”.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A project selector must count subsets of tasks whose execution times total exactly 10 seconds, with execution times 2, 3, 5, 7 seconds. Each task is distinct and available once. What count and update rule fit a single-list DP?
  1. 2; use logical or with downward targets.
  2. 3; use addition with upward targets.
  3. 1; use addition with downward targets.
  4. 2; use addition with downward targets.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An exact-fill 0/1 knapsack has capacity 5 kg and items (2 kg, value −3), (3 kg, value 7) and (5 kg, value 2). What is the optimum, and how should positive capacities in the empty row be initialized?
  1. Value 4; initialize them to minus infinity.
  2. Value 7; initialize them to zero.
  3. Value 2; initialize them to minus infinity.
  4. Value 4; initialize them to zero.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

63 Key Terms, each with its definition

B

Base case
A base case gives a directly known answer at a state that can be solved without expanding the recurrence into more subproblems.
Coin counting starts with one way to make amount 0, while minimum-coin change starts with zero coins.
Bit length
The bit length of a positive integer is the number of binary digits needed to write it, equal to its base-2 logarithm rounded down plus one.
The integer 511 uses nine bits, although a table indexed from 0 through 511 contains 512 columns.

C

Cache
A cache is storage that retains previously computed results so an implementation can retrieve them without repeating the computation.
The Fibonacci cache can start with the known values for arguments 0 and 1 before recursion begins.
Cache key
A cache key is the identifier used to retrieve a stored answer and must distinguish every changing input that affects that answer.
Using only the item index as a knapsack cache key merges states with different remaining capacities.
Call overhead
Call overhead is the work needed to enter, manage and return from a function call, separate from the mathematical work inside that call.
Bottom-up loops can run faster than dense memoized recursion while retaining the same asymptotic bound.
Capacity
A capacity is the maximum total weight allowed in an at-most knapsack state, or the required weight in an exact-fill state.
After taking a 3 kg item from capacity 8 kg, the remaining subproblem has capacity 5 kg.
Choice table
A choice table records one winning decision for each computed state, allowing a solution to be recovered by following those decisions.
A rod-cutting choice table can store the first-piece length for each remaining rod length.
Common subsequence
A common subsequence is a sequence that can be obtained from each of two inputs by deleting elements without rearranging what remains.
“AC” is common to “ABC” and “ADC” because A precedes C in both strings despite different gaps.
Counting problem
A counting problem asks how many valid results exist, requiring a clear rule for when two constructions count as the same result.
Coin counting must specify whether rearrangements of the same coins count as different results.

D

Decision problem
A decision problem asks whether a condition can be met, so its answer is true or false instead of a count or an optimal value.
Subset sum decides whether selected input numbers can reach the target without reusing an input.
Distinct subproblem
A distinct subproblem is one unique question identified by all the parameters and fixed input data that determine its answer.
Calls with the same item index but different capacities represent distinct knapsack subproblems.
Dynamic programming
Dynamic programming solves reusable subproblems once and stores their answers so later requests can reuse the results.
The Fibonacci DP keeps earlier values so repeated branches do not expand the same calculations.

E

Edit distance
Edit distance is the minimum number of allowed insertions, deletions and substitutions needed to transform one sequence into another.
With each edit costing one, “kitten” becomes “sitting” with two substitutions and one insertion.
Empty subset
The empty subset selects no input positions and has total sum 0, giving both a reachable base state and one valid subset for counting.
A subset counter begins with one empty subset at target 0, even when the input list itself is empty.
Encoded input size
The encoded input size is the number of bits needed to represent the supplied data, not the sum of the numeric magnitudes it contains.
A large capacity can occupy a short binary field while creating millions of indexed table columns.
Endpoint state
An endpoint state restricts a subsequence to end at one specified position, making its last value available for extension checks.
The best length ending at a small final input can be shorter than the best length anywhere earlier.
Exact-fill knapsack
Exact-fill knapsack requires selected weights to equal the target capacity, so leaving spare capacity is not a feasible completed solution.
A 4 kg item alone cannot fill an exact 5 kg capacity, even if it gives the greatest individual value.
Exhaustive search
An exhaustive search checks every candidate solution, providing an independent correctness reference when small inputs make enumeration practical.
Enumerating all subsets of a short list can reveal a DP bug that incorrectly reuses the current number.

F

Filling order
A filling order is the sequence in which table entries are computed, chosen so that every value read has already been established.
A suffix recurrence that reads larger indices needs a decreasing-index filling order after its end bases.
Fractional knapsack
Fractional knapsack permits taking part of an item, changing the feasible choices from the whole-item selections used by 0/1 knapsack.
Taking half of a divisible load is allowed in fractional knapsack but not for an indivisible project.

H

Hashable argument
A hashable argument can be used in a dictionary key, with a hash value and equality behavior stable for its lifetime.
Python's cache decorator can accept integer indices or suitable tuples, but cannot accept a mutable list.

I

Infeasible state
An infeasible state has no valid solution under its constraints and needs a representation that cannot be mistaken for an achievable value.
Positive infinity prevents an impossible amount from becoming a cheap candidate in minimum-coin change.
Integer overflow
Integer overflow occurs when a result falls outside the range of a fixed-size integer representation, so it cannot be stored exactly in that type.
A large route count can overflow Java's long type, while Python integers grow to retain the exact count.
Interval state
An interval state describes a contiguous part of one sequence using both endpoints, giving quadratically many possible nonempty intervals.
An input of length n has n(n + 1)/2 nonempty intervals, more than its n nonempty prefixes.

L

Longest common subsequence
A longest common subsequence has the greatest possible length among sequences that are subsequences of both inputs, allowing several tied answers.
“AB” and “BA” have LCS length 1, with either “A” or “B” providing an optimal common subsequence.
Longest increasing subsequence
A longest increasing subsequence is a maximum-length selection of elements that preserves input order and increases strictly in value.
In 4, 1, 3, 6, the subsequence 1, 3, 6 has length 3; equal values would not extend it.

M

Memoization
Memoization stores the results of recursive subproblems in a cache and returns the saved answer when a state is requested again.
A cached Fibonacci function expands each missing argument once and answers later requests by lookup.

O

Optimal substructure
Optimal substructure means that an optimal solution contains optimal solutions to its subproblems that remain compatible when combined.
Replacing part of a shortest route by a shorter compatible route would improve the whole route.
Optimization problem
An optimization problem asks for a feasible solution with the smallest or largest value of a specified measure, such as cost or revenue.
Minimum-coin change optimizes the number of coins while requiring their values to reach an exact amount.
Ordered sequence
An ordered sequence distinguishes arrangements by position, so swapping different elements can create a different counted result.
The coin sequences 2, 3 and 3, 2 count separately when order matters, even though both total 5.
Overlapping subproblems
Overlapping subproblems occur when separate branches of a solution request answers to the same fully specified smaller problem.
Two branches requesting fib(4) overlap even if those calls occur at different depths in the tree.

P

Polynomial time
Polynomial time bounds an algorithm's running time by a polynomial in the length of the encoded input, under the chosen computational model.
LCS is polynomial-time because its dimensions count symbols actually supplied in the two sequences.
Prefix
A prefix is the initial part of a sequence, identified by its length, with length 0 representing the empty initial part.
For “TABLE,” the length-3 prefix is “TAB”; LCS pairs such lengths from two different inputs.
Prefix-pair table
A prefix-pair table assigns one entry to each pair of prefix lengths from two inputs, including the empty prefix of each input.
LCS and edit distance use the same prefix-pair layout but store different quantities and use different bases.
Pseudopolynomial time
Pseudopolynomial time is polynomial in numeric input magnitudes and input length, but can be exponential in the binary length of those magnitudes.
Knapsack's capacity-indexed time O(nW) grows with W itself, not just the bits used to encode W.

R

Reachability table
A reachability table stores true-or-false answers indicating which states can be achieved under the choices and constraints of a problem.
A subset-sum row marks reachable totals using only the input positions processed up to that row.
Reachable state
A reachable state is a subproblem encountered by following recurrence dependencies from the original query, rather than any possible index pair.
Large numeric gaps can leave most subset-sum table columns unvisited by a memoized query.
Reconstruction
Reconstruction recovers an actual sequence of decisions or selected objects from an optimal value and enough information about its predecessors.
A knapsack result needs reconstruction to report the chosen items as well as their total value.
Recurrence
A recurrence expresses one subproblem's answer in terms of other subproblem answers, combining alternatives according to the problem's objective.
A rod-cutting recurrence tries each first piece and adds its price to the best remaining-rod value.
Recursion depth
Recursion depth is the number of nested active calls along a call chain, which consumes stack space even when results are memoized.
A cached Fibonacci request can exceed the recursion limit before its long chain starts returning answers.
Recursion tree
A recursion tree shows a function call as a node and its recursive requests as children, including repeated occurrences of the same state.
A Fibonacci recursion tree has many nodes labeled with the same argument, revealing repeated work.
Rod cutting
Rod cutting asks how to divide a rod into allowed piece lengths to maximize the sum of their listed prices, including the option of no cut.
A high price for a short piece can make repeated short pieces more valuable than selling the rod whole.
Rolling storage
Rolling storage retains only the rows or values still needed by future updates, overwriting entries whose computational role has ended.
Keeping two LCS rows saves space for the length calculation but loses earlier rows used by traceback.

S

Space complexity
Space complexity describes the storage an algorithm requires, including tables, caches, active stack frames and other working information.
One-list knapsack reduces retained values to a capacity-sized list while keeping all item passes.
State
A state is a precisely defined subproblem, including the meaning of its parameters and the answer stored for those parameter values.
The state K[i][c] records a value for a particular available-item prefix and a particular capacity.
Subproblem graph
A subproblem graph represents states as vertices, with an arrow from each state to every state that uses its computed answer.
Fibonacci arrows run from smaller arguments toward the larger arguments that read their values.
Subsequence
A subsequence is formed by deleting zero or more elements while keeping the original order of the retained elements; gaps are allowed.
“BD” is a subsequence of “BREAD,” even though its selected letters are not adjacent in the input.
Subset count
A subset count records how many selections of input positions reach a target, treating different positions as distinct even if values repeat.
Two separate inputs of value 5 give two single-position subsets for target 5, not one shared position.
Subset sum
Subset sum asks whether a subset of given numbers, each input position used at most once, adds up to an exact target amount.
For inputs 4, 6, 9, target 10 is reachable with 4 and 6, but the same 4 cannot be used twice.
Substitution
A substitution replaces one existing sequence element with another, contributing one edit in the unit-cost edit-distance model.
Changing the initial k of “kitten” to s is a substitution; adding a final g is an insertion.
Substring
A substring is a contiguous block of a sequence, so every retained position follows immediately after the previous retained position.
“REA” is a substring of “BREAD”; “BAD” skips letters and is only a subsequence of that string.
Suffix
A suffix is the final part of a sequence, identified by a starting position, including the empty part beyond the last element.
A suffix DP may move backward through indices so that answers nearer the end are computed first.

T

Tabulation
Tabulation is a bottom-up implementation that fills base entries first, then computes each table entry after its dependencies are ready.
A Fibonacci table fills increasing indices because each new value reads the previous two entries.
Tie-breaking rule
A tie-breaking rule chooses consistently between equally good legal alternatives without changing the optimal primary value.
In rod cutting, keeping the first maximum found makes output reproducible but does not necessarily minimize the number of pieces.
Time complexity
Time complexity describes how an algorithm's total operation count grows with its input parameters, including every state update and final step.
Rod cutting has linearly many lengths but quadratically many first-piece comparisons across them.
Topological order
A topological order places every vertex of an acyclic directed graph before its outgoing neighbors, respecting all directed dependencies.
With arrows from dependencies to their users, a topological order gives a valid table-filling order.
Traceback
A traceback follows recurrence-consistent predecessors from the original state to a base case to recover one solution that attains its value.
An LCS traceback records matching characters while skipping unmatched endpoints on up or left moves.
Transition
A transition is one legal way for a recurrence to connect a state to a dependency, including any value contributed by that choice.
Taking a coin of value 4 moves from amount 9 to amount 5 and contributes one coin to the candidate.

U

Unary encoding
A unary encoding writes a positive integer with one repeated symbol per unit, making the representation's length proportional to the value.
Capacity 8 takes eight tally marks in unary, so its magnitude is no longer compressed into a few bits.
Unbounded knapsack
Unbounded knapsack allows any nonnegative number of copies of each item type while maximizing value within the weight constraint.
An upward capacity update can reuse a newly improved smaller capacity because repeated copies are legal.
Unordered combination
An unordered combination counts the selected amounts of each kind without treating different written orders as new selections.
Coin-first counting includes 1 + 4 once, without adding another combination for 4 + 1.

W

Work per state
The work per state is the cost of combining that state's alternatives, excluding recursive work already charged to the dependency states.
An LIS endpoint scans earlier positions, so one computed state can require a linear number of checks.

#

0/1 knapsack
0/1 knapsack maximizes the total value of whole items with total weight at most a capacity, using each available item zero or one time.
A whole box can be selected or left out; taking a fraction of it is not a legal 0/1 choice.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started