Skip to contentKEEP THE CRAFTTHE SANCTUARY

Dynamic Programming

Define a sufficient subproblem state, enumerate its complete choices and reuse solved dependencies. Choose memoization or tabulation from the dependency graph, and derive cost from reached states and transitions.

3 practice exercises24 interview problems

Recognize it when Different decisions reach the same remaining subproblem.

Checking your account…

Dynamic Programming Code Labs

Name the Repeated State

Dynamic programming begins when different decision paths reach the same subproblem. Define the smallest state whose value fully answers the remaining question; extra history prevents reuse.

Write the Recurrence Before the Table

Express the answer for one state using already-defined smaller states. State what each option means—take, skip, extend, split—and why those options are exhaustive and non-overlapping where required.

Trace Take-or-Skip States

Reference
def rob_state_trace(values):
    skip=take=0; trace=[]
    for value in values:
        skip,take=max(skip,take),skip+value
        trace.append([skip,take])
    return trace
Practice

Implement rob_state_trace(values). Return [skip,take] after each house for the non-adjacent maximum-sum recurrence.

Public tests

  • Advance from prior states only

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Take-or-Skip States

def rob_state_trace(values):
    skip=take=0; trace=[]
    for value in values:
        skip,take=max(skip,take),skip+value
        trace.append([skip,take])
    return trace

Keep Old Take and Skip Separate

Predict the state pairs of the existing Lab. Take means the newest house was selected; skip means it was not. They have different allowed predecessors even when one value is currently larger.

Step Executed statement State Why
First house skip,take=max(skip,take),skip+value;trace.append([skip,take]) value=5: skip=0, take=5 Taking the first house adds its value to the empty previous-skip state.
Adjacent house skip,take=max(skip,take),skip+value;trace.append([skip,take]) value=4: skip=5, take=4 Taking 4 may not use previous take=5; adjacent houses cannot both contribute.
Third house skip,take=max(skip,take),skip+value;trace.append([skip,take]) value=6: skip=5, take=11 Old skip=5 represents skipping the middle house, so it can combine with 6.
Extract answer return trace [[0,5],[5,4],[5,11]]; empty call [] The trace exposes two constrained states; the final optimum is max of the final pair, not always take.
Print Output
print(rob_state_trace([5,4,6])) [[0, 5], [5, 4], [5, 11]]
print(rob_state_trace([])) []

This drill has a tiny rolling state. Other DPs need prefixes, capacities, masks or intervals. Their dimensions and transitions determine complexity; O(n) is not a universal DP bound.

Choose Evaluation Order and Base Cases

Base cases are valid states, not initialization tricks. Tabulation must visit dependencies before consumers; memoized recursion must decrease toward a base case. Use a sentinel that cannot be confused with a valid value.

Compute Minimum Coin Count

Reference
def min_coin_count(coins,amount):
    dp=[amount+1]*(amount+1); dp[0]=0
    for total in range(1,amount+1):
        for coin in coins:
            if coin<=total: dp[total]=min(dp[total],dp[total-coin]+1)
    return -1 if dp[amount]>amount else dp[amount]
Practice

Implement min_coin_count(coins,amount). Return the minimum number of reusable coins totaling amount, or -1. Coin denominations are positive integers, and amount is a nonnegative integer.

Public tests

  • Use solved smaller amounts

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Compute Minimum Coin Count

def min_coin_count(coins,amount):
    dp=[amount+1]*(amount+1); dp[0]=0
    for total in range(1,amount+1):
        for coin in coins:
            if coin<=total: dp[total]=min(dp[total],dp[total-coin]+1)
    return -1 if dp[amount]>amount else dp[amount]

Choose Memoization or Tabulation

Memoization computes only reached states and mirrors the recurrence, but uses recursion and cache overhead. Tabulation exposes order, avoids stack depth, and often permits rolling-state compression. Both are O(number of states × transitions per state).

Explain It in an Interview

Say: “State means this. The recurrence considers these complete choices, and these base cases anchor it. I evaluate in this dependency order.” Then derive time from states times transitions and space from the table plus call stack. House Robber(opens in a new tab) is the canonical take-or-skip transfer.

Template To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

2D dynamic programming

Add an empty row and column; each cell looks up, left, or diagonally.

The state depends on two indices: positions in two strings, or a row and column in a grid.

Trigger words

  • two strings
  • common subsequence
  • edit distance
  • unique paths
  • interleaving
  • regex with * and .
def longest_common_subsequence(a, b):
    rows, cols = len(a), len(b)
    # dp[i][j] = answer for the first i letters of a and the first j letters of b
    dp = [[0] * (cols + 1) for _ in range(rows + 1)]
    for i in range(1, rows + 1):
        for j in range(1, cols + 1):
            if a[i - 1] == b[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
    return dp[rows][cols]

Spot it when

  • 'Longest common subsequence', 'edit distance'.
  • 'Unique paths' in a grid.

Remember

  • The extra row and column stand for the empty prefix, so there are no special cases at the edges.
  • Fill the table in an order where the cells you read are already done.

How problems bend it

  • Edit distance: Row 0 and column 0 start at 0..n; a mismatch costs 1 + min(insert, delete, replace).
  • Unique paths: dp[r][c] = dp[r - 1][c] + dp[r][c - 1] with the first row and column set to 1.

Python Version Note

Python 3.11+

The code uses standard Python syntax and containers supported by the browser Judge. The Dynamic Programming proof does not depend on a minor Python release.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Take/skip state traceO(n)O(n)Two constant-cost states per item; trace stores each pair.
Reusable minimum coin countO(A * c + A)O(A * c + A)A is amount and c coin count; this is pseudo-polynomial in numeric amount, not input bit length.

Space

O(n) returned take/skip trace; coin table O(A); a non-tracing take/skip computation needs O(1) state.

Assumptions

  • Coin denominations must be positive integers and amount nonnegative so transitions use smaller valid amounts.
  • Memoization also stores cache entries and call frames; tuple/string keys may add hashing costs.

Invariants Worth Saying Aloud

  1. Each stored value answers its stated subproblem, not the whole original question.
  2. Transitions read correct dependency values from the intended earlier stage.
  3. Every legal final choice is included and invalid choices are excluded.

When To Use Or Avoid Dynamic Programming

Use It When

  • Use DP when the state includes every history detail needed for future choices.
  • Choose an acyclic evaluation order or decreasing memoized recursion before implementing transitions.

Choose Another Tool When

  • Enumeration may still require outputting exponentially many distinct paths even when a count has a compact DP.
  • A large state space or unnecessary dimensions can make DP less practical than a proven greedy choice.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Reading an already overwritten predecessor

Sequentially updating skip then take allows the current item to reuse its own updated skip. Old skip=0, take=5 and value=4 would produce illegal take=9.

Prevent it: Compute both new states from the old pair.

Avoid

skip=max(skip,take)
take=skip+value

Use instead

skip,take=max(skip,take),skip+value

Using zero for an impossible positive amount

An unfilled amount is not achievable with zero coins. Adding one to that fake predecessor invents a valid solution.

Prevent it: Use an unreachable sentinel larger than any feasible count.

Avoid

previous=0
candidate=previous+1

Use instead

previous=amount+1
candidate=previous+1

Choosing the largest coin without a proof

For amount 6 and coins 1,3,4, choosing 4 first needs two more ones; two threes use fewer coins.

Prevent it: Compare all legal predecessor amounts rather than transferring an unsupported greedy rule.

Avoid

count=1+(amount-4)

Use instead

count=1+best_for_three

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.