Skip to content
TOPIC · 14 PROBLEMS · 5 PATTERNS

Dynamic programming

Big answers built from small ones. If the same smaller question keeps coming up, answer it once, write it down, and look it up next time.

How to spot a dynamic programming problem

“how many ways”Counting routes, splits or arrangements without listing them. Each count is a sum of counts for smaller inputs.
“minimum / maximum”The cheapest, longest or best total, where one choice now changes what is left. Try each choice and keep the best.
“is it possible”Can you reach the target, split the string, fill the bag. A yes for a big input rests on a yes for a smaller one.
“two strings”Compare, align or transform one sequence into another. That is a table with one string down the side and one along the top.

Five patterns cover almost everything

1D DP

O(n)

One number per position. Each entry comes from the few entries just before it.

Reach for it when the input is a line, such as steps, houses or characters, and the answer at i depends only on earlier positions.Go deeper: From memoised recursion to dynamic programming

2D grid DP

O(m · n)

Fill a grid row by row. Each cell comes from its neighbours above and to the left.

Reach for it when you move through a grid only right or down, and want a count or a cheapest path.

Two strings

O(m · n)

dp[i][j] answers the question for the first i characters of one and the first j of the other. Match the last characters, or drop one.

Reach for it when two sequences must be compared, aligned or edited into each other.

Knapsack

O(n · target)

Index the table by what is left to fill. For each item, take it or leave it, and keep the better result.

Reach for it when you pick items to hit a sum or capacity exactly, with or without reuse.

Interval DP

O(n²) to O(n³)

Solve every short range first, then longer ones built from them, splitting each range at every point.

Reach for it when the answer for a stretch i..j depends on smaller stretches inside it, such as palindromes or what to pop last.

The one template to memorise

Not every table looks like this one, but most are filled the same way. Coin change shows the whole shape: a base case, a loop over sizes, and one line that picks the best smaller answer.

solution.py
def coin_change(coins, amount):
best = [0] + [amount + 1] * amount # amount + 1 means "can't make it"
for total in range(1, amount + 1):
for coin in coins:
if coin <= total:
best[total] = min(best[total], best[total - coin] + 1)
return best[amount] if best[amount] <= amount else -1

Problems, easy to hard

Do them in order the first time
Next upBacktracking