Classic dynamic programming problems are Fibonacci, climbing stairs, house robber, coin change, 0/1 knapsack, longest common subsequence, edit distance and longest increasing subsequence. Each has a state, a recurrence that builds it from smaller states, and a cached or tabulated solution that cuts exponential work to polynomial time. Runnable Python for all eight is below.
On this page
The eight problems in one tableExamples 1 to 3: Fibonacci, climbing stairs, house robberExamples 4 and 5: coin change and 0/1 knapsackExamples 6 to 8: LCS, edit distance and longest increasing subsequenceHow to practise these so they stickFrequently asked questionsThis page is a worked problem set, not a definition. If you still need the idea itself, read what dynamic programming is first; it already walks through Fibonacci, stairs, coin change, knapsack and LCS in detail. Here every problem gets the same treatment so you can compare them: the state, the recurrence, a top-down version, a bottom-up version, and the output of code that was run.
All code below was executed with Python 3.9. Top-down means recursion plus a cache (functools.lru_cache). Bottom-up means filling a table or a few variables in order. The two always agree in these examples, and each block prints both answers so you can see that. Recursion basics are in what is recursion; the cost words are explained in time complexity and Big O.
The eight problems in one table
Dynamic programming (DP) applies when a problem breaks into overlapping smaller problems and the best answer to the whole is built from best answers to the parts. To solve any of the eight problems below, write down the state (what the sub-problem is), the transition (how a state is computed from smaller ones) and the base case. This table is the cheat sheet; the sections after it show the code.
| Problem | State | Transition | Time | Space (bottom-up) |
|---|---|---|---|---|
| Fibonacci | fib(n) | fib(n-1) + fib(n-2) | O(n) | O(1) |
| Climbing stairs | ways(n) | ways(n-1) + ways(n-2) | O(n) | O(1) |
| House robber | best(i), best from house i onwards | max(h[i] + best(i+2), best(i+1)) | O(n) | O(1) |
| Coin change (fewest coins) | f(a), fewest coins for amount a | 1 + min(f(a - c)) over coins c | O(amount x coins) | O(amount) |
| 0/1 knapsack | f(i, c), items i onwards, capacity c | max(skip item, value + take item) | O(items x capacity) | O(capacity) |
| Longest common subsequence | f(i, j), suffixes a[i:] and b[j:] | match: 1 + f(i+1, j+1); else max of two skips | O(m x n) | O(m x n) |
| Edit distance | f(i, j), suffixes a[i:] and b[j:] | match: f(i+1, j+1); else 1 + min(delete, insert, replace) | O(m x n) | O(n) with two rows |
| Longest increasing subsequence | f(i), best run ending at i | 1 + max(f(j)) for j < i with a[j] < a[i] | O(n^2), or O(n log n) with binary search | O(n) |
Knapsack time is called pseudo-polynomial: it grows with the capacity number, not with how many digits that number has. Mention it in interviews; it is a common follow-up.
Examples 1 to 3: Fibonacci, climbing stairs, house robber
These three have a one-dimensional state, so the table is a single row or just two variables. They are the right place to learn the pattern.
Fibonacci and climbing stairs
Fibonacci is fib(n) = fib(n-1) + fib(n-2) with fib(0)=0, fib(1)=1. Climbing stairs asks how many ways there are to climb n steps taking 1 or 2 at a time. The last move was either a 1-step from n-1 or a 2-step from n-2, so ways(n) = ways(n-1) + ways(n-2) with ways(0)=ways(1)=1. Same recurrence, different base cases. The bottom-up versions keep only the last two values, so space drops from O(n) to O(1).
from functools import lru_cache
@lru_cache(maxsize=None)
def fib_td(n): # top-down: recursion plus a cache
return n if n < 2 else fib_td(n - 1) + fib_td(n - 2)
def fib_bu(n): # bottom-up: keep only the last two values
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
def stairs_bu(n): # ways(n) = ways(n-1) + ways(n-2)
one, two = 1, 1 # ways(0), ways(1)
for _ in range(2, n + 1):
one, two = one + two, one
return one
print(fib_td(40), fib_bu(40))
print([stairs_bu(n) for n in range(1, 9)])Output: 102334155 102334155 for fib(40), then [1, 2, 3, 5, 8, 13, 21, 34] for stairs of 1 to 8 steps. Without the cache, fib(40) makes over 300 million calls; with it, 41 distinct calls. Types of dynamic programming measures that gap.
House robber
You cannot rob two adjacent houses. For house i you either take it and jump to i+2, or skip it and go to i+1: best(i) = max(h[i] + best(i+2), best(i+1)). For [2, 7, 9, 3, 1] the answer is 12 (houses with 2, 9 and 1). The bottom-up version keeps two numbers, the best total if the previous house was robbed and if it was skipped.
from functools import lru_cache
houses = [2, 7, 9, 3, 1]
def rob_td(h):
@lru_cache(maxsize=None)
def best(i): # best loot from houses i, i+1, ...
if i >= len(h):
return 0
return max(h[i] + best(i + 2), best(i + 1))
return best(0)
def rob_bu(h):
take, skip = 0, 0 # best loot if we do / do not rob the previous house
for x in h:
take, skip = skip + x, max(take, skip)
return max(take, skip)
print(rob_td(houses), rob_bu(houses))Output: 12 12. This take-or-skip choice is the seed of the knapsack pattern below.
Examples 4 and 5: coin change and 0/1 knapsack
Coin change: fewest coins
Given coin values and an amount, find the fewest coins that sum to it. f(a) = 1 + min(f(a - c)) over every coin c that fits, with f(0) = 0. For coins 1, 5, 6, 9 and amount 11, the answer is 2 (5 + 6). A greedy habit of taking the biggest coin first gives 9 + 1 + 1 = 3 coins, which is why this needs DP; greedy algorithms explained shows exactly when greedy is safe. If no combination works, such as amount 3 with coins 5 and 7, the code returns -1.
from functools import lru_cache
def coin_td(coins, amount):
@lru_cache(maxsize=None)
def f(a): # fewest coins to make a
if a == 0:
return 0
options = [f(a - c) for c in coins if c <= a]
return min(options, default=float("inf")) + 1
r = f(amount)
return -1 if r == float("inf") else r
def coin_bu(coins, amount):
INF = float("inf")
dp = [0] + [INF] * amount
for a in range(1, amount + 1):
for c in coins:
if c <= a and dp[a - c] + 1 < dp[a]:
dp[a] = dp[a - c] + 1
return -1 if dp[amount] == INF else dp[amount]
print(coin_td((1, 5, 6, 9), 11), coin_bu([1, 5, 6, 9], 11)) # greedy would pick 9+1+1 = 3 coins
print(coin_bu([5, 7], 3))Output: 2 2, then -1.
0/1 knapsack
Each item has a weight and a value and can be taken once. For each item you skip it or take it if it fits: f(i, c) = max(f(i+1, c), v[i] + f(i+1, c - w[i])). With weights [1, 3, 4, 5], values [1, 4, 5, 7] and capacity 7, the best is the items of weight 3 and 4 for a value of 9. The bottom-up loop runs the capacity backwards so each item is counted at most once; run it forwards and you have solved the unbounded version by accident, a very common bug.
from functools import lru_cache
weights, values, cap = [1, 3, 4, 5], [1, 4, 5, 7], 7
def knap_td(w, v, cap):
@lru_cache(maxsize=None)
def f(i, c): # best value using items i.. with capacity c
if i == len(w):
return 0
best = f(i + 1, c) # skip item i
if w[i] <= c:
best = max(best, v[i] + f(i + 1, c - w[i]))
return best
return f(0, cap)
def knap_bu(w, v, cap):
dp = [0] * (cap + 1)
for wi, vi in zip(w, v):
for c in range(cap, wi - 1, -1): # backwards so each item is used once
dp[c] = max(dp[c], dp[c - wi] + vi)
return dp[cap]
print(knap_td(weights, values, cap), knap_bu(weights, values, cap))Output: 9 9.
Examples 6 to 8: LCS, edit distance and longest increasing subsequence
These have two indices (or one index with a scan over earlier ones), so the state is a grid. Draw the grid on paper once and every one of them becomes easy to reason about.
Longest common subsequence
A subsequence keeps order but may skip characters. For ABCBDAB and BDCABA the longest common one has length 4 (for example BCBA). If the first characters match, take them and move both pointers; otherwise try dropping one character from either side and keep the better result.
from functools import lru_cache
def lcs_td(a, b):
@lru_cache(maxsize=None)
def f(i, j): # LCS length of a[i:] and b[j:]
if i == len(a) or j == len(b):
return 0
if a[i] == b[j]:
return 1 + f(i + 1, j + 1)
return max(f(i + 1, j), f(i, j + 1))
return f(0, 0)
def lcs_bu(a, b):
dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 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[-1][-1]
print(lcs_td("ABCBDAB", "BDCABA"), lcs_bu("ABCBDAB", "BDCABA"))Output: 4 4.
Edit distance
The minimum number of single-character insertions, deletions and replacements to turn one word into another. It is LCS with three choices on a mismatch. kitten to sitting takes 3 edits (two replacements and one insertion); sunday to saturday also takes 3. Spell checkers and fuzzy search use this idea. The bottom-up code keeps only two rows, so memory is O(n) rather than O(m x n).
from functools import lru_cache
def edit_td(a, b):
@lru_cache(maxsize=None)
def f(i, j): # edits to turn a[i:] into b[j:]
if i == len(a):
return len(b) - j
if j == len(b):
return len(a) - i
if a[i] == b[j]:
return f(i + 1, j + 1)
return 1 + min(f(i + 1, j), # delete from a
f(i, j + 1), # insert into a
f(i + 1, j + 1)) # replace
return f(0, 0)
def edit_bu(a, b):
prev = list(range(len(b) + 1))
for i in range(1, len(a) + 1):
cur = [i] + [0] * len(b)
for j in range(1, len(b) + 1):
if a[i - 1] == b[j - 1]:
cur[j] = prev[j - 1]
else:
cur[j] = 1 + min(prev[j], cur[j - 1], prev[j - 1])
prev = cur
return prev[-1]
print(edit_td("kitten", "sitting"), edit_bu("kitten", "sitting"))
print(edit_bu("sunday", "saturday"))Output: 3 3, then 3.
Longest increasing subsequence
For [10, 9, 2, 5, 3, 7, 101, 18] the answer is 4 (for example 2, 3, 7, 18). The DP table version is O(n^2). The third function keeps the smallest possible tail for each length and uses binary search, which gets O(n log n); it is not a table fill, but interviewers often ask for it as the follow-up.
from bisect import bisect_left
from functools import lru_cache
nums = [10, 9, 2, 5, 3, 7, 101, 18]
def lis_td(a):
@lru_cache(maxsize=None)
def f(i): # longest increasing subsequence ending at i
return 1 + max((f(j) for j in range(i) if a[j] < a[i]), default=0)
return max(f(i) for i in range(len(a)))
def lis_bu(a): # O(n^2) table
dp = [1] * len(a)
for i in range(len(a)):
for j in range(i):
if a[j] < a[i]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
def lis_fast(a): # O(n log n): not DP table, but same answer
tails = []
for x in a:
k = bisect_left(tails, x)
if k == len(tails):
tails.append(x)
else:
tails[k] = x
return len(tails)
print(lis_td(nums), lis_bu(nums), lis_fast(nums))Output: 4 4 4.
How to practise these so they stick
- Read the problem and write the state in one sentence before touching code: "f(i, j) is the answer for the suffixes starting at i and j".
- Write the recurrence and base cases on paper. Test them by hand on a tiny input.
- Code the top-down version first. It is the recurrence plus a cache, so it is hard to get wrong.
- Convert to bottom-up by finding the order in which states depend on each other, then shrink the table if only the previous row is needed.
- Run both and assert that they return the same answer on random small inputs.
- Change one rule (allow reuse of items, forbid adjacent picks, add a third operation) and redo the recurrence.
Follow this order on a practice site from coding practice websites, and see where DP sits among the other patterns in DSA interview questions. The wider path is on the data structures and algorithms learning path.
Mistakes that show up again and again: a table indexed off by one (decide whether index i means "first i items" or "item i" and stay with it), forgetting the base case for an empty input, mutating a list argument inside a cached function (the cache key must be hashable), and filling the knapsack loop in the wrong direction.
Frequently asked questions
What are the most common dynamic programming problems in interviews?
Fibonacci and climbing stairs for warm-up, then house robber, coin change, 0/1 knapsack, longest common subsequence, edit distance and longest increasing subsequence. Grid path counting and partition problems such as subset sum are close behind. If you can state the state and recurrence for these eight without looking, you can handle most first-round DP questions.
Which dynamic programming problem should a beginner start with?
Climbing stairs. It has one index, a recurrence you can derive by asking what the last move was, and base cases that are easy to check by hand. Move to house robber next because it introduces the take-or-skip choice, then coin change, and only after that the two-index problems such as LCS.
What is the difference between top-down and bottom-up DP?
Top-down is the natural recursion with a cache so each state is computed once. Bottom-up fills a table from the smallest states upward with loops. Both give the same answer and the same time complexity. Bottom-up avoids recursion limits and can save memory by keeping only the rows still needed.
Is coin change a greedy or a DP problem?
It depends on the coin set. For standard Indian coins and notes, picking the largest first gives the fewest coins. For a set such as 1, 5, 6, 9 and amount 11, greedy gives three coins while the best is two (5 + 6). Because greedy is unreliable in general, the safe solution is DP.
How do I know the state for a DP problem?
Ask what the smallest amount of information is that lets you answer the question for the rest of the input. For sequences it is usually an index, or a pair of indices for two sequences. For knapsack-type problems it is the index plus the remaining capacity or amount. If two different paths reach the same state, DP applies.
Why does my DP answer work on small inputs but time out?
Usually the cache is missing or keyed wrongly, so the recursion is still exponential. Check that each state is computed once by counting calls on a small input. Another cause is an O(n^2) table where n is large; look for a rolling array or a binary-search trick such as the one for increasing subsequences.
Learn this with mentors
Programmes for builders and engineers with admissions open: live classes, mentors and project work.


