Skip to content

Dynamic Programming

Reach for it when the problem says

  • Count the ways
  • min/max cost
  • "can you reach…"
  • overlapping choices
Solved
0/36Solved
Problems
36Problems
Variants
6Variants

Problems

6 variants

Linear 1D

0 of 9 solved

State machine

0 of 5 solved

Knapsack

0 of 7 solved

Grid paths

0 of 6 solved

Two strings

0 of 5 solved

Interval DP

0 of 4 solved

Pattern guide

Dynamic programming (DP) is the pattern interviewers use to separate people who memorised answers from people who can build one. Every DP problem asks the same two questions: what is the state, and how does one state follow from smaller ones? Answer those out loud and the code is usually ten lines.

What it is

A problem is a DP problem when two things are true. First, the answer can be built from answers to smaller versions of the same problem (this is called optimal substructure). Second, a plain recursive solution would solve the same smaller problems many times (overlapping subproblems). DP solves each smaller problem once, stores the result in a table, and reads it back.

Take House Robber: houses hold coins, and you cannot rob two neighbours. Brute force tries every allowed subset, which is O(2ⁿ). But the best haul from the first i houses only depends on two smaller answers: the best from the first i - 1 houses (skip house i) and the best from the first i - 2 houses plus house i (rob it). Watch the table fill.

House Robber: best[i] = max(best[i - 1], best[i - 2] + nums[i])
2
0
7
1
9
2
3
3
1
4
best = [ ]

Houses hold [2, 7, 9, 3, 1]. best[i] will be the most coins from houses 0..i.

1/6

Every DP solution you write has the same four parts:

  1. State: what one cell of the table means, in one sentence ("best[i] is the most coins from houses 0..i").
  2. Recurrence: how a cell is computed from smaller cells.
  3. Base cases: the cells you know without computing.
  4. Order: fill cells so every cell's inputs are ready before you need them, then read off the answer.

You can implement it top-down (recursion plus a memo, a cache keyed by the arguments) or bottom-up (loops filling a table). They do the same work. Bottom-up avoids recursion depth limits and makes space savings obvious; top-down is easier when the fill order is awkward.

Quick check
Which property makes memoisation pay off?
Need a nudge? A hint rules out a wrong answer.

How to recognise it

Wording clues

Phrase in the promptWhat it suggests
"how many ways", "number of distinct"Counting DP: add the counts of smaller states
"minimum cost", "fewest", "maximum profit"Optimisation DP: min or max over choices
"can you reach", "is it possible to split"Boolean DP: OR over choices
"subsequence" (not substring)Characters can be skipped: a prefix or interval table
"two strings", "transform a into b"2D table over (prefix of a, prefix of b)
"you cannot pick two adjacent", "cooldown"Take-or-skip, or a small state machine per index
"unlimited supply", "use each at most once"Knapsack: sweep upward vs downward

Constraint clues

ConstraintWhat it suggests
n <= 202ⁿ may pass; bitmask DP or backtracking
n <= 500 to n <= 1000 with two stringsO(n · m) table, about 10^6 cells
n <= 300 with rangesO(n³) interval DP is the intended budget
n <= 10^5O(n) or O(n log n): a 1D DP with O(1) work per cell
amount <= 10^4, sum <= 1000A table indexed by value is cheap
"return the answer modulo 10^9 + 7"Counting with huge results: almost always DP

Input and output shape clues

  • One array, answer is one number (best sum, count of ways): Linear 1D.
  • Rules that depend on what you did yesterday (holding a stock, cooldown): State machine.
  • A target total and a list of item values: Knapsack.
  • A grid with right and down moves: Grid paths.
  • Two strings: Two strings.
  • One string or array where the answer for a range uses smaller ranges inside it (palindromes, bursting): Interval DP.

Looks like it but isn't

It smells like DP, but...Use instead
"Return all combinations / permutations"Backtracking. You must list them, and caching a count does not help.
A local choice is provably safe (Jump Game, interval scheduling)Greedy. DP works but is slower than it needs to be.
Shortest path with arbitrary moves or weights in a gridBFS or Dijkstra. DP needs an order with no cycles.
Contiguous subarray with a monotonic rule (sum at most k, all positives)Sliding window.
Quick check
Which of these is NOT a good fit for DP?
Need a nudge? A hint rules out a wrong answer.

The sub-patterns

Linear 1D

When it applies: one sequence, and the answer at position i depends on a fixed number of earlier positions (i - 1, i - 2, sometimes every j < i). The state is "the answer for the prefix ending at i". When each cell looks back a constant number of places, roll a few variables instead of storing the table.

Climbing Stairs: ways[i] = ways[i - 1] + ways[i - 2]
1
0
1
1
2
3
4
5

Base cases: one way to stand on step 0 and one way to reach step 1.

1/4
Python
def rob(nums: list[int]) -> int: prev, curr = 0, 0 # best for i - 2 and i - 1 for coins in nums: prev, curr = curr, max(curr, prev + coins) return curr print(rob([2, 7, 9, 3, 1])) # 12
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(n) time, O(1) space with rolling variables. When each cell scans all earlier cells (Longest Increasing Subsequence), it is O(n²).

Best-known problems: Climbing Stairs, House Robber, Decode Ways, Longest Increasing Subsequence.

Predict the outputPython

What does this print?

prev, curr = 0, 0
for coins in [2, 1, 1, 2]:
  prev, curr = curr, max(curr, prev + coins)
print(curr)
Need a nudge? Hints walk you through it.

State machine

When it applies: at each index you can be in one of a few modes (holding a stock or not, just sold, cooling down), and the rules say which mode can follow which. The state is (index, mode). Draw the modes as boxes with arrows; each arrow is one term in a recurrence. Maximum Product Subarray fits too: the two modes are "largest product ending here" and "smallest product ending here".

Stock with cooldown: three modes per day
1
0
2
1
3
2
0
3
2
4
hold = -∞sold = 0rest = 0

Before day 0 you cannot hold anything, so hold = -∞.

1/5
Python
def max_profit_cooldown(prices: list[int]) -> int: hold, sold, rest = float("-inf"), 0, 0 for p in prices: # all three update from yesterday's values at once hold, sold, rest = max(hold, rest - p), hold + p, max(rest, sold) return int(max(sold, rest)) print(max_profit_cooldown([1, 2, 3, 0, 2])) # 3
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(n · k) for k modes, which is O(n) for the usual two or three. Space is O(k).

Best-known problems: Best Time to Buy and Sell Stock with Cooldown, Best Time to Buy and Sell Stock with Transaction Fee, Maximum Product Subarray.

Knapsack

When it applies: you have items (coins, numbers, words, squares) and a target total, and you pick items to hit it: fewest items, number of ways, or whether it is possible. The state is indexed by the total, not by position. Two flavours:

  • Unbounded (each item reusable): sweep totals upward, so a total can build on a smaller total that already used the same item.
  • 0/1 (each item once): for each item, sweep totals downward, so table[t - item] still describes the world before this item.

When counting, loop order also decides what you count: items outside counts combinations; totals outside counts ordered sequences.

Coin Change, coins [1, 3, 4], amount 6
0
0
1
2
3
4
5
6

fewest[0] = 0: zero coins make zero. Everything else starts as impossible.

1/5
Python
def coin_change(coins: list[int], amount: int) -> int: # unbounded, minimum fewest = [0] + [amount + 1] * amount for t in range(1, amount + 1): for c in coins: if c <= t: fewest[t] = min(fewest[t], fewest[t - c] + 1) return fewest[amount] if fewest[amount] <= amount else -1 def can_reach(nums: list[int], goal: int) -> bool: # 0/1, boolean ok = [True] + [False] * goal for x in nums: for s in range(goal, x - 1, -1): # downward! ok[s] = ok[s] or ok[s - x] return ok[goal] print(coin_change([1, 3, 4], 6), can_reach([1, 5, 11, 5], 11)) # 2 True
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(n · T) time for n items and target T, O(T) space.

Best-known problems: Coin Change, Coin Change II, Partition Equal Subset Sum, Target Sum, Word Break.

Predict the outputPython

Same table, two loop orders. What does this print?

coins, amount = [1, 2, 5], 5
a = [1] + [0] * amount
for c in coins:
  for t in range(c, amount + 1):
      a[t] += a[t - c]
b = [1] + [0] * amount
for t in range(1, amount + 1):
  for c in coins:
      if c <= t:
          b[t] += b[t - c]
print(a[amount], b[amount])
Need a nudge? Hints walk you through it.

Grid paths

When it applies: a grid where you move only right and down (or down a triangle), and you want the number of paths, the cheapest path, or the largest shape ending at each cell. Every cell's predecessors are above and to the left, so filling row by row always has the inputs ready. The state is dp[r][c]; usually one rolling row is enough.

Minimum Path Sum: best[r][c] = grid[r][c] + min(above, left)
1

Grid [[1,3,1],[1,5,1],[4,2,1]]. The start costs 1.

1/5
Python
def min_path_sum(grid: list[list[int]]) -> int: best = [float("inf")] * len(grid[0]) best[0] = 0 for row in grid: best[0] += row[0] for c in range(1, len(row)): best[c] = min(best[c], best[c - 1]) + row[c] # above, left return int(best[-1]) print(min_path_sum([[1, 3, 1], [1, 5, 1], [4, 2, 1]])) # 7
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(m · n) time, O(n) space with a rolling row.

Best-known problems: Unique Paths, Minimum Path Sum, Maximal Square, Longest Increasing Path in a Matrix (moves go in all four directions there, so use memoised DFS instead of a row-by-row fill).

Two strings

When it applies: two strings (or arrays) and a question about matching them: common subsequence, edit distance, interleaving, counting embeddings, pattern matching. The state is dp[i][j] for the prefixes a[:i] and b[:j] (or suffixes). The recurrence always asks: do the last characters match? Add an extra row and column for the empty prefix; that is where the base cases live.

LCS of abc (rows) and ac (columns)
∅ac
∅000
a0
b0
c0

Row 0 and column 0 are the empty prefix: LCS 0.

1/4
Python
def lcs(a: str, b: str) -> int: prev = [0] * (len(b) + 1) for ch in a: curr = [0] * (len(b) + 1) for j in range(1, len(b) + 1): if ch == b[j - 1]: curr[j] = prev[j - 1] + 1 # diagonal + 1 else: curr[j] = max(prev[j], curr[j - 1]) # drop one character prev = curr return prev[-1] print(lcs("abcde", "ace")) # 3
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(m · n) time, O(n) space with two rows.

Best-known problems: Longest Common Subsequence, Edit Distance, Distinct Subsequences, Regular Expression Matching.

Interval DP

When it applies: one sequence, and the answer for a range [i, j] is built from smaller ranges inside it: trim the ends (palindromes) or split at some k (Burst Balloons, matrix chain). The state is dp[i][j]. Fill by increasing length, or loop i downward and j upward, so inner ranges are ready first.

Longest palindromic subsequence of cbbd: lps[i][j]
cbbd
c1
b1
b1
d1

Length-1 ranges: every single character is a palindrome of length 1.

1/4
Python
def longest_palindrome_subseq(s: str) -> int: n = len(s) dp = [[0] * n for _ in range(n)] for i in range(n - 1, -1, -1): # i goes down dp[i][i] = 1 for j in range(i + 1, n): # j goes up if s[i] == s[j]: dp[i][j] = dp[i + 1][j - 1] + 2 else: dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]) return dp[0][n - 1] print(longest_palindrome_subseq("bbbab")) # 4
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(n²) when each range trims its ends, O(n³) when each range tries every split point k.

Best-known problems: Longest Palindromic Substring, Palindromic Substrings, Longest Palindromic Subsequence, Burst Balloons.

Quick check
In Burst Balloons, why do we choose the last balloon to burst in a range instead of the first?
Need a nudge? A hint rules out a wrong answer.

A decision checklist

Match the pairs0/6 matched

Match each problem shape to its sub-pattern.

Choose an item, then its match on the other side.
Put it in order5 steps

Put the steps for building a DP solution in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Traps

  • Off-by-one in the table size. Prefix tables are length n + 1 because the empty prefix is a real state. ways[0] = 1 (one way to make nothing) is the most common base case that people get wrong.
  • Wrong sweep direction in knapsack. Upward means reusable items; downward means each item once. Mixing them up silently gives the wrong answer on inputs like [2, 6] for partition.
  • Wrong loop order when counting. Items outside counts combinations; totals outside counts orderings.
  • Overwriting a value you still need. In a rolling row, save the old dp[c] before overwriting if the next cell needs it as its diagonal (Maximal Square, Edit Distance). In a state machine, update all modes at once from yesterday's values.
  • Starting a max at 0 when answers can be negative (Maximum Product Subarray, Triangle). Start from the first element or negative infinity.
  • Recursion depth. Top-down memoisation on a 10^4-long input can hit Python's default limit of 1000 frames. Bottom-up avoids it.
  • Forgetting the modulo on counting problems, or applying it only at the end after the numbers overflowed (in languages with fixed-width integers).

Always test: the empty input (or length 1), all-equal values, an input where greedy fails, and the largest size from the constraints.

Quick check
In 0/1 knapsack with a 1D table, why do you loop the total s from high to low for each item?
Need a nudge? A hint rules out a wrong answer.

How to talk it through

If you get stuck, say the brute-force recursion out loud. The arguments of that recursion are your state, and adding a memo turns it into DP. From there, converting to a bottom-up loop is mechanical.

Key terms
Overlapping subproblems
A plain recursion would solve the same smaller problem many times. Caching each answer once is what makes DP fast.
Optimal substructure
The best answer to a problem is built from best answers to smaller versions of it.
State
What one cell of the DP table means, stated in one sentence, for example best[i] is the most coins from houses 0..i.
Recurrence
The formula that computes a state from smaller states, such as ways[i] = ways[i - 1] + ways[i - 2].
Memoisation
Top-down DP: recursion plus a cache keyed by the arguments.
0/1 vs unbounded knapsack
Each item used at most once (sweep totals downward) versus any number of times (sweep upward).