π§© Dynamic Programming
in Python
Learn dynamic programming in Python: overlapping subproblems, functools.cache memoisation, tabulation, knapsack, LCS, coin change and edit distance with printed tables.
What this lesson is about
Dynamic programming, usually shortened to DP, is a way of solving a big problem by solving smaller versions of it once and reusing the answers. It has an intimidating reputation, but the core idea is small: if a plain recursive solution keeps recomputing the same sub-answers, store them. Shortest paths in maps, spell checkers, diff tools, text alignment in bioinformatics, resource budgeting and many scheduling problems are all solved this way.
DP shows up in two places in a programmer's life. In real software it lies behind tools such as diff, fuzzy search and sequence alignment. In interviews and competitive programming it is the topic that separates people who memorised a few solutions from people who understand how to design them. In both cases the skill is the same: describe a problem as a state, write the transition from smaller states to larger ones, and decide the order in which to fill them in.
I have built this page around small examples whose tables you can actually see. We start with the pain that DP removes (a recursive Fibonacci that makes tens of thousands of calls), then fix it with functools.cache, then rebuild it bottom-up with a table. After that we solve the classics: coin change, 0/1 knapsack, longest common subsequence and edit distance, printing the 1D or 2D table each time. The last section teaches you how to recognise a DP problem and a repeatable recipe for attacking one. If recursion still feels shaky, read recursion first, and keep Big-O nearby for the complexity talk.
What you will learn
- βSpot overlapping subproblems and explain why plain recursion wastes work
- βMemoise a recursive function with
functools.cache - βConvert a recursive solution into a bottom-up table (tabulation)
- βPrint and read 1D and 2D DP tables to debug your transitions
- βSolve coin change, 0/1 knapsack, longest common subsequence and edit distance
- βReconstruct the actual answer (not just its size) by walking the table backwards
- βReduce memory by keeping only the rows or cells you still need
- βRecognise when a problem is DP and when greedy or brute force is enough
Why programmers should learn this
- β Many problems have an obvious brute-force solution that takes exponential time; DP often turns that into polynomial time, which is the difference between finishing and never finishing.
- β Everyday tools rely on it: file comparison, fuzzy matching and autocorrect all use edit-distance style tables, so understanding the idea helps you understand the tools.
- β DP interview questions are common because they test whether you can define a state clearly and reason about correctness, skills that also help in ordinary design work.
- β
Learning memoisation gives you a practical Python tool (
functools.cache) that speeds up many recursive functions with one line. - β Once you can build the table by hand, harder topics such as shortest paths in trees and graphs or optimisation problems become easier to read.
Overlapping subproblems: the problem DP solves
Take the Fibonacci numbers, where each value is the sum of the two before it. The recursive definition is a perfect translation of the maths, so it is the first thing most people write. The trouble is how many calls it makes. To compute fib(5) the function calls fib(4) and fib(3); but fib(4) also calls fib(3), so the same work is done twice, and the repetition compounds at every level.
That repetition has a name: overlapping subproblems. A problem has overlapping subproblems when the recursion keeps asking the same question with the same arguments. Divide-and-conquer algorithms such as merge sort do not have this property, because each sub-call gets its own separate slice of the data. DP is only worth reaching for when the sub-calls do overlap.
The second property you need is optimal substructure: the best answer to the big problem can be assembled from best answers to smaller ones. For Fibonacci there is nothing to optimise, but for coin change or knapsack it is exactly this property that lets us trust a table of smaller answers. Run the example below and look at how fast the call counter grows. The number of calls grows roughly by a factor of 1.6 every time n goes up by one, which is exponential growth.
calls = 0
def fib(n):
global calls
calls += 1
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
for n in (5, 10, 15, 20, 25):
calls = 0
value = fib(n)
print(f"fib({n}) = {value}, calls made = {calls}")fib(5) = 5, calls made = 15 fib(10) = 55, calls made = 177 fib(15) = 610, calls made = 1973 fib(20) = 6765, calls made = 21891 fib(25) = 75025, calls made = 242785
Line by line
- 1A counter so we can measure how much work the function does.
- 3-8The textbook recursive Fibonacci.
global callslets the function update the counter; the base case returnsnfor 0 and 1. - 10-13For several values of
n, reset the counter, compute the answer and print both the answer and the number of calls.
The answer grows slowly but the work explodes: fib(25) needs a quarter of a million calls to produce a number that has only five digits. At n = 50 the same code would take hours. The fix is not a faster computer; it is to stop repeating work.
A quick test for overlap: draw the recursion tree for a small input. If the same node (same function, same arguments) appears more than once, memoisation or tabulation will help.
Top-down memoisation with functools.cache
Memoisation means remembering the result of a call so that the next call with the same arguments returns instantly. It is called top-down because you keep the natural recursive shape and start from the full problem. Python makes this nearly free: put @cache from functools above the function and it keeps a dictionary from arguments to results for you.
After the change the call tree collapses. Each distinct value of n is computed exactly once, so fib(50) needs about 50 real computations instead of billions. The function cache_info() reports hits and misses, which is a nice way to prove the saving to yourself. A miss is a real computation, a hit is a reused answer.
The arguments must be hashable, because they become dictionary keys. Integers, strings and tuples are fine; lists and dictionaries are not, so convert them to tuples (or pass indexes instead of slices) when you design the state. It is also worth knowing the manual version, a dictionary you pass around or keep in a closure, because it works in any language and lets you control exactly what is stored. For ideas on closures see recursion and the lessons on decorators.
from functools import cache
@cache
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(50))
print(fib.cache_info())
fib.cache_clear()
print(fib.cache_info())12586269025 CacheInfo(hits=48, misses=51, maxsize=None, currsize=51) CacheInfo(hits=0, misses=0, maxsize=None, currsize=0)
Line by line
- 1Import the
cachedecorator, which stores every result forever. - 3-4The decorator wraps the function; the body below is unchanged from the plain recursive version.
- 5-7Same base case and same recurrence as before.
- 9Compute
fib(50); this finishes instantly now. - 10
cache_info()shows hits, misses and the number of stored entries. 51 misses means 51 real computations (n from 0 to 50). - 11-12
cache_clear()empties the cache, which is useful in tests.
from functools import cache
@cache
def paths(row, col):
"""Ways to walk from the top-left to (row, col), moving only right or down."""
if row == 0 or col == 0:
return 1
return paths(row - 1, col) + paths(row, col - 1)
print(paths(2, 2))
print(paths(5, 5))
print(paths(16, 16))
# the same thing with a hand-made dictionary
def paths_manual(row, col, memo=None):
if memo is None:
memo = {}
if (row, col) in memo:
return memo[(row, col)]
if row == 0 or col == 0:
result = 1
else:
result = paths_manual(row - 1, col, memo) + paths_manual(row, col - 1, memo)
memo[(row, col)] = result
return result
print(paths_manual(16, 16))6 252 601080390 601080390
Line by line
- 3-8A state with two numbers. On the first row or column there is only one route; elsewhere you arrive from above or from the left.
- 10-12Small and larger grids all answer immediately;
paths(16, 16)is 601080390. - 15-25The same function with an explicit dictionary. The key is the tuple
(row, col); we check the memo first, compute only on a miss and store before returning. - 27Both versions agree.
@cache never forgets, so memory grows with the number of distinct arguments. For long-running programs use @lru_cache(maxsize=1000) to keep only recent results. Also remember that deep recursion can hit Python's recursion limit, which is one reason to learn tabulation next.
Bottom-up tabulation: filling a table
Tabulation solves the same problem from the other end. Instead of asking for the big answer and recursing down, you decide an order in which smaller answers can be computed, then fill an array (the table) from the base cases upward. There is no recursion, so there is no call-stack limit, and the loop is often a little faster because it avoids function-call overhead.
Designing a table needs four decisions. What does one cell mean (the state)? What are the first cells, whose values you know without computing (the base cases)? How is a cell computed from earlier cells (the transition)? And in what order do you fill them so that every cell you need already exists? Write the meaning of a cell as a sentence in a comment; most DP bugs are a cell whose meaning drifted halfway through the code.
Climbing stairs is a friendly first example: you can climb one or two steps at a time, and the question is how many different ways reach step n. The ways to reach step i equal the ways to reach i - 1 plus the ways to reach i - 2, which is Fibonacci again, but now you can see the table. The second block shows a common optimisation: the transition looks back only two cells, so two variables are enough and the memory drops from O(n) to O(1).
def climb_table(n):
# ways[i] = number of ways to reach step i
ways = [0] * (n + 1)
ways[0] = 1 # one way to stand at the start: do nothing
if n >= 1:
ways[1] = 1
for i in range(2, n + 1):
ways[i] = ways[i - 1] + ways[i - 2]
return ways
table = climb_table(10)
print("step :", list(range(len(table))))
print("ways :", table)step : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ways : [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Line by line
- 1-3Allocate the table. The comment says exactly what a cell means.
- 4-6Base cases: one way to be at step 0, one way to reach step 1.
- 7-8Fill from left to right; each cell uses the two cells just before it.
- 9Return the entire table so we can print it.
- 11-13Print the step numbers and the ways side by side.
def climb_small(n):
prev, cur = 1, 1 # ways to reach step 0 and step 1
for _ in range(2, n + 1):
prev, cur = cur, prev + cur
return cur
for n in (1, 2, 5, 10, 30):
print(n, climb_small(n))1 1 2 2 5 8 10 89 30 1346269
Line by line
- 2Two variables replace the whole table:
previs step i-2 andcuris step i-1. - 3-4Slide the window one step forward; the tuple assignment evaluates the right side first.
- 5After the loop
curholds the answer for step n. - 7-8Check a few values against the table printed earlier.
Write the table version first so you can print it and check it by hand. Optimise the memory only after it is correct.
Coin change: a 1D table
Coin change asks: given coin values and a target amount, what is the fewest coins that add up exactly to it? A greedy approach (always take the biggest coin that fits) works for everyday currencies but fails for others. With coins 1, 3 and 4 and a target of 6, greedy takes 4 + 1 + 1 (three coins) while the optimum is 3 + 3 (two coins). Because of that, we need DP.
Define best[a] as the fewest coins needed to make amount a. The base case is best[0] = 0. For any amount a, try every coin c that is not larger than a: if we use that coin, we need best[a - c] + 1 coins in total. Take the minimum over all coins. Amounts that cannot be made stay at infinity, so the answer is -1 when best[target] is still infinite.
The table has amount + 1 cells and each cell tries len(coins) options, so the time is O(amount x coins) and the memory is O(amount). A closely related question is how many *ways* there are to make the amount; the second block answers it by looping over coins on the outside so that each combination is counted once rather than once per ordering. That loop order matters: swap the loops and you count sequences instead of combinations.
def min_coins(coins, amount):
INF = float("inf")
best = [0] + [INF] * amount
for a in range(1, amount + 1):
for c in coins:
if c <= a and best[a - c] + 1 < best[a]:
best[a] = best[a - c] + 1
return best
coins = [1, 3, 4]
best = min_coins(coins, 10)
print("amount:", list(range(11)))
print("coins :", best)
print("answer for 6:", best[6])
print("impossible:", min_coins([5, 7], 3)[3])amount: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] coins : [0, 1, 2, 1, 1, 2, 2, 2, 2, 3, 3] answer for 6: 2 impossible: inf
Line by line
- 2-3
best[a]starts at infinity (not yet reachable), exceptbest[0] = 0because zero coins make zero. - 4-7For each amount try each coin that fits; keep the smaller of the current best and 'one coin plus the best for the remainder'.
- 8Return the whole table so we can look at it.
- 10-14Print every amount next to its fewest-coin count. For 6 the answer is 2 (3 + 3), which greedy would miss.
- 15With coins 5 and 7 you cannot make 3, so the cell remains infinity.
def count_ways(coins, amount):
ways = [1] + [0] * amount # one way to make 0: use no coins
for c in coins: # coins outside: each combination counted once
for a in range(c, amount + 1):
ways[a] += ways[a - c]
return ways
print(count_ways([1, 2, 5], 11))
print(count_ways([2], 3))[1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 10, 11] [1, 0, 1, 0]
Line by line
- 2
ways[a]is the number of combinations that makea. Zero can be made one way: the empty combination. - 3-5Process one coin at a time and let it be used any number of times. Adding
ways[a - c]extends every combination of the smaller amount with this coin. - 6Return the table.
- 8-9Combinations of 1, 2 and 5 for each amount up to 11; amount 3 can never be made from only 2s, so it prints 0.
If a problem gives you a finite supply of each item, the inner loop must change; that variant is the knapsack in the next section.
0/1 Knapsack: a 2D table
You have a bag that can carry a fixed weight and a set of items, each with a weight and a value. You may take each item at most once (hence 0/1). Which items give the largest total value without going over the limit? Trying every subset is 2 to the power of n; DP does it in O(n x capacity).
The state has two parts, so the table has two dimensions. Let dp[i][w] be the best value using only the first i items with a weight limit of w. For item i there are two choices. Skip it, and the value is dp[i-1][w]. Take it (only if its weight fits), and the value is dp[i-1][w - weight] + value. The cell keeps the larger of the two. Row 0 and column 0 are all zero because no items or no room means no value.
Printing the table makes this very concrete: you can read across a row to see how adding one more item changes the best value for each capacity. To find *which* items were chosen, walk backwards from the bottom-right cell. If dp[i][w] differs from dp[i-1][w], then item i was taken, so subtract its weight and move up; otherwise just move up. That reconstruction step is a general DP trick that you will reuse for LCS and edit distance.
items = [("map", 2, 3), ("tent", 3, 4), ("stove", 4, 5), ("lamp", 5, 6)] # name, weight, value
capacity = 5
n = len(items)
dp = [[0] * (capacity + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
name, weight, value = items[i - 1]
for w in range(capacity + 1):
dp[i][w] = dp[i - 1][w] # skip the item
if weight <= w: # or take it, if it fits
dp[i][w] = max(dp[i][w], dp[i - 1][w - weight] + value)
print("capacity:", *range(capacity + 1))
for i, row in enumerate(dp):
label = "start" if i == 0 else items[i - 1][0]
print(f"{label:>6} :", *row)
# walk backwards to find the chosen items
chosen = []
w = capacity
for i in range(n, 0, -1):
if dp[i][w] != dp[i - 1][w]:
name, weight, value = items[i - 1]
chosen.append(name)
w -= weight
print("best value:", dp[n][capacity])
print("take:", sorted(chosen))capacity: 0 1 2 3 4 5 start : 0 0 0 0 0 0 map : 0 0 3 3 3 3 tent : 0 0 3 4 4 7 stove : 0 0 3 4 5 7 lamp : 0 0 3 4 5 7 best value: 7 take: ['map', 'tent']
Line by line
- 1-2Four items as
(name, weight, value)tuples and a bag that carries weight 5. - 4-5Build
(n + 1)rows by(capacity + 1)columns of zeros. A list comprehension is needed so that each row is a separate list. - 7-12For each item and each capacity: first copy the value from the row above (skip the item), then, if the item fits, compare with taking it.
- 14-17Print the table with a label for each row so you can see how every new item changes the best value.
- 19-26Walk up from the bottom-right corner. If the value changed compared with the row above, the item was taken; reduce the remaining capacity by its weight.
- 27-28The best value is 7, from the map (2, value 3) and the tent (3, value 4).
Notice the lamp alone has value 6, which is less than map plus tent. The table finds this combination without ever enumerating subsets. Each row depends only on the previous row, so you can store a single 1D array and loop the capacity downwards to avoid using an item twice, reducing memory to O(capacity).
When compressing the knapsack to 1D, iterate the capacity from high to low. Going upward would let an item be reused within the same pass and quietly turn 0/1 knapsack into the unbounded version.
Longest common subsequence
A subsequence keeps characters in order but may skip some, so ACE is a subsequence of ABCDE. The longest common subsequence (LCS) of two strings is the longest sequence that is a subsequence of both. It is the idea behind file comparison: lines in the LCS are unchanged, everything else is an addition or a deletion.
Let dp[i][j] be the LCS length of the first i characters of a and the first j characters of b. If the two last characters match, they extend the best answer for both shorter prefixes: dp[i-1][j-1] + 1. If they differ, one of them cannot be in the answer, so we take the better of dropping the last character of a or of b: max(dp[i-1][j], dp[i][j-1]). The first row and column are 0, since an empty string shares nothing.
The table is (len(a)+1) x (len(b)+1), so the time and memory are O(len(a) x len(b)). To recover an actual subsequence, start in the bottom-right corner: when the characters match, record one and move diagonally; otherwise move toward the neighbour with the larger value. The characters come out reversed, so reverse them at the end. A given pair of strings can have several equally long answers, and the tie-breaking rule decides which one you get.
def lcs(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 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])
# rebuild one longest subsequence
out = []
i, j = m, n
while i > 0 and j > 0:
if a[i - 1] == b[j - 1]:
out.append(a[i - 1])
i -= 1
j -= 1
elif dp[i - 1][j] >= dp[i][j - 1]:
i -= 1
else:
j -= 1
return dp, "".join(reversed(out))
a, b = "ABCBDAB", "BDCABA"
dp, seq = lcs(a, b)
print(" ", " ".join(" " + b))
for i, row in enumerate(dp):
head = " " if i == 0 else a[i - 1]
print(head, " ", " ".join(str(x) for x in row))
print("length:", dp[-1][-1])
print("one LCS:", seq) B D C A B A
0 0 0 0 0 0 0
A 0 0 0 0 1 1 1
B 0 1 1 1 1 2 2
C 0 1 1 2 2 2 2
B 0 1 1 2 2 3 3
D 0 1 2 2 2 3 3
A 0 1 2 2 3 3 4
B 0 1 2 2 3 4 4
length: 4
one LCS: BCBALine by line
- 1-3Create the table of zeros; row 0 and column 0 stay zero for the empty prefix.
- 4-9Fill each cell: matching characters extend the diagonal value by one, otherwise take the better of the cell above and the cell to the left.
- 11-22Walk back from the corner. A match is part of the answer (move diagonally); otherwise follow the larger neighbour.
- 23Return both the table and the reconstructed string (reversed into the correct order).
- 25-26A classic textbook pair of strings; the LCS length is 4.
- 28-31Print the table with the characters of
bacross the top and the characters ofadown the side. - 32-33Show the length and one sequence that achieves it.
Different tie-breaking rules yield different but equally long answers (BCBA and BDAB are both valid here). If a problem asks only for the length, you do not need the reconstruction code at all.
Edit distance (Levenshtein)
Edit distance counts the minimum number of single-character insertions, deletions and substitutions needed to turn one string into another. Spell checkers use it to rank suggestions, and search tools use it for fuzzy matching: kitten to sitting takes three edits (substitute k with s, substitute e with i, insert g).
Let dp[i][j] be the edit distance between the first i characters of a and the first j characters of b. The base cases are clear: turning i characters into nothing takes i deletions, and building j characters from nothing takes j insertions, so the first column is 0..m and the first row is 0..n. For other cells, if the last characters are equal no edit is needed and the cell copies the diagonal. If they differ, we pick the cheapest of three moves, each costing one: delete (dp[i-1][j]), insert (dp[i][j-1]) or substitute (dp[i-1][j-1]).
Compare this with LCS: the table shape and fill order are identical, only the base cases and the transition change. That is the real lesson of this section. Once you can describe a state over prefixes of two sequences, a whole family of problems (longest common substring, shortest common supersequence, sequence alignment) becomes a variation of one template. Use sorting and searching ideas when you need to rank fuzzy-match candidates by their distance.
def edit_distance(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i # delete i characters
for j in range(n + 1):
dp[0][j] = j # insert j characters
for i in range(1, m + 1):
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
else:
dp[i][j] = 1 + min(dp[i - 1][j], # delete
dp[i][j - 1], # insert
dp[i - 1][j - 1]) # substitute
return dp
a, b = "kitten", "sitting"
dp = edit_distance(a, b)
print(" ", " ".join(" " + b))
for i, row in enumerate(dp):
head = " " if i == 0 else a[i - 1]
print(head, " ", " ".join(str(x) for x in row))
print(f"distance({a!r}, {b!r}) = {dp[-1][-1]}")
pairs = [("flaw", "lawn"), ("sunday", "saturday"), ("abc", "abc")]
for x, y in pairs:
print(x, y, edit_distance(x, y)[-1][-1]) s i t t i n g
0 1 2 3 4 5 6 7
k 1 1 2 3 4 5 6 7
i 2 2 1 2 3 4 5 6
t 3 3 2 1 2 3 4 5
t 4 4 3 2 1 2 3 4
e 5 5 4 3 2 2 3 4
n 6 6 5 4 3 3 2 3
distance('kitten', 'sitting') = 3
flaw lawn 2
sunday saturday 3
abc abc 0Line by line
- 1-3Allocate the table for prefixes of both strings.
- 4-7Base cases: the first column is 0, 1, 2, ... (all deletions) and the first row is 0, 1, 2, ... (all insertions).
- 8-16Fill the rest. Equal characters cost nothing and copy the diagonal; otherwise add one to the cheapest of delete, insert or substitute.
- 17Return the whole table.
- 19-24Print the table for
kittenandsitting; the bottom-right cell is 3. - 26-28A few more pairs:
flawtolawnis 2,sundaytosaturdayis 3, and identical strings are 0.
Because each row only needs the row above, edit distance can run in O(min(m, n)) memory when you need the number but not the edit script.
How to recognise a DP problem, and a recipe
Look for these signals. The question asks for a count, a minimum, a maximum or a yes/no ('is it possible?') over many choices. The choices are sequential, such as take or skip, or the next move on a grid. The naive recursive solution would branch repeatedly and revisit the same sub-situations. And the input sizes are modest (hundreds or thousands), which fits a polynomial table. Words like 'longest', 'fewest', 'number of ways' and 'can you reach' are strong hints.
When I attack one I follow the same five steps. First, write a brute-force recursive function and check it on tiny inputs. Second, identify the state: the minimum set of parameters that fully describes a sub-situation, such as (i, w) for knapsack. Third, write the transition as a formula and the base cases. Fourth, add @cache and see whether it becomes fast enough; if the recursion is too deep, convert to a table. Fifth, if memory matters, notice which earlier rows the transition really uses and keep only those.
Equally important is knowing when *not* to use DP. If a greedy choice is provably safe, as in picking the earliest finishing meeting for interval scheduling, greedy is simpler and faster. If the input is huge and the state space is huge too, you may need a different approach altogether. For problems on graphs, such as shortest paths, the table idea reappears in algorithms like Bellman-Ford and Floyd-Warshall, which you can explore in trees and graphs. The final demo below shows the recipe at work and proves why greedy cannot be trusted for coin change.
from functools import cache
coins = (1, 3, 4)
def greedy(amount):
count = 0
for c in sorted(coins, reverse=True):
count += amount // c
amount %= c
return count
@cache
def optimal(amount):
if amount == 0:
return 0
options = [optimal(amount - c) + 1 for c in coins if c <= amount]
return min(options)
print("amount greedy optimal")
for amount in range(1, 11):
g, o = greedy(amount), optimal(amount)
flag = " <- greedy is wrong" if g != o else ""
print(f"{amount:>6} {g:>6} {o:>7}{flag}")amount greedy optimal
1 1 1
2 2 2
3 1 1
4 1 1
5 2 2
6 3 2 <- greedy is wrong
7 2 2
8 2 2
9 3 3
10 4 3 <- greedy is wrongLine by line
- 3The coin set that breaks greedy thinking.
- 5-10Greedy: take as many of the biggest coin as possible, then the next biggest, and so on.
- 12-17The DP version as memoised recursion. State: remaining amount. Transition: try each coin that fits. Base case: amount 0 needs 0 coins.
- 19-23Compare both for amounts 1 to 10 and flag the disagreements. Greedy is wrong at 6 and 10, where it needs one coin more than the optimum.
When you are unsure whether greedy works, brute-force or DP a few hundred small random cases and compare the two answers. A single counterexample settles the question.
Common mistakes
β Memoising when there is no overlap
If every sub-call has different arguments (as in merge sort), a cache only costs memory. Draw the recursion tree and check that states repeat before adding memoisation.
β Unclear state definition
If you cannot say in one sentence what dp[i][j] means, the transition will be wrong. Write the meaning as a comment above the table and keep to it.
β Sharing rows with [[0] * n] * m
[[0] * n] * m makes m references to the same row, so writing one cell changes every row. Use [[0] * n for _ in range(m)] to create independent rows.
β Off-by-one between prefix length and index
Tables indexed by prefix length have size len + 1, and the character for row i is a[i - 1]. Mixing the two conventions is the most common source of wrong answers in LCS and edit distance.
β Forgetting hashability and recursion depth
@cache needs hashable arguments, so pass tuples or indexes instead of lists. Very deep recursion can hit Python's recursion limit, in which case switch to a bottom-up loop.
Quick quiz
Tap an answer. I explain every one, right or wrong.
Q1. What makes a problem a good candidate for dynamic programming?
Q2. What does @cache from functools do to a recursive function?
Q3. In tabulation, what must be true about the order in which you fill the table?
Q4. For coins [1, 3, 4] and amount 6, what is the minimum number of coins?
Q5. In the LCS table, what happens when a[i-1] != b[j-1]?
Q6. What is the time complexity of edit distance between strings of lengths m and n using a table?
Frequently asked questions
Should I use memoisation or tabulation?
+Start with whichever is easier to write correctly. Memoisation follows the recursive thinking naturally and only computes states that are needed; tabulation avoids recursion limits and is often a little faster. Both have the same big-O time for most problems.
Is dynamic programming the same as recursion?
+No. Recursion is a technique for defining a function in terms of itself. DP combines recursion (or loops) with stored results so that overlapping subproblems are solved once. See recursion for the base technique.
Why is it called dynamic programming?
+It is a historical name from operations research, where 'programming' meant planning, not writing code. It does not mean the program changes while it runs.
How do I get better at spotting the state?
+Ask what information you would need to know to continue solving from the middle of the problem. Those pieces of information are your state. Practise on the classics in this lesson, then vary them.
Is functools.cache safe for any function?
+Only for pure functions: the same arguments must always give the same result, and the arguments must be hashable. Functions that read files, the clock or random numbers should not be cached blindly.
Key takeaways
- βDP applies when subproblems overlap and the best answer can be built from best sub-answers.
- βTop-down memoisation keeps the recursive shape and adds a cache; in Python
@cachedoes this in one line. - βBottom-up tabulation fills a table in an order that respects dependencies; it avoids recursion limits and invites memory optimisation.
- βDefine the state in words, write base cases and the transition, and print the table to debug it.
- βCoin change, knapsack, LCS and edit distance share one template: a table over prefixes or amounts with a small number of choices per cell.
- βGreedy is simpler when it is provably correct; test it against DP on small inputs before trusting it.