Classic DP Problems
Longest increasing subsequence, coin change, LCS, edit distance and bitmask DP — the problems every DP question is built from.
These problems recur constantly — in interviews, in real systems (diff tools, spell checkers, bioinformatics), and as building blocks for harder DP. Learn the state for each; the code follows.
Longest increasing subsequence (LIS)
Length of the longest strictly increasing subsequence (not necessarily contiguous).
- O(n²) DP:
dp[i]= LIS length ending at i = 1 + maxdp[j]over j < i witha[j] < a[i]. - O(n log n): keep
tails[k]= smallest possible tail of an increasing subsequence of length k+1. For each x, binary-search the first tail ≥ x and replace it (or append).tailsstays sorted.
int lengthOfLIS(int[] a) {
int[] tails = new int[a.length];
int size = 0;
for (int x : a) {
int lo = 0, hi = size;
while (lo < hi) { // lower bound of x in tails
int m = (lo + hi) >>> 1;
if (tails[m] < x) lo = m + 1; else hi = m;
}
tails[lo] = x;
if (lo == size) size++;
}
return size;
}from bisect import bisect_left
def length_of_lis(a):
tails = []
for x in a:
i = bisect_left(tails, x)
if i == len(tails):
tails.append(x)
else:
tails[i] = x
return len(tails)function lengthOfLIS(a: number[]): number {
const tails: number[] = [];
for (const x of a) {
let lo = 0, hi = tails.length;
while (lo < hi) {
const m = (lo + hi) >> 1;
if (tails[m] < x) lo = m + 1; else hi = m;
}
tails[lo] = x;
}
return tails.length;
}Coin change (minimum coins)
dp[v] = fewest coins summing to v. dp[v] = 1 + min(dp[v − c]) over coins c ≤ v; dp[0] = 0. O(V · coins). (Counting the number of ways instead: loop coins in the outer loop so each combination is counted once.)
int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
Arrays.fill(dp, amount + 1); // "infinity"
dp[0] = 0;
for (int v = 1; v <= amount; v++)
for (int c : coins)
if (c <= v) dp[v] = Math.min(dp[v], dp[v - c] + 1);
return dp[amount] > amount ? -1 : dp[amount];
}def coin_change(coins, amount):
INF = amount + 1
dp = [0] + [INF] * amount
for v in range(1, amount + 1):
for c in coins:
if c <= v:
dp[v] = min(dp[v], dp[v - c] + 1)
return -1 if dp[amount] == INF else dp[amount]function coinChange(coins: number[], amount: number): number {
const dp = new Array(amount + 1).fill(Infinity);
dp[0] = 0;
for (let v = 1; v <= amount; v++)
for (const c of coins) if (c <= v) dp[v] = Math.min(dp[v], dp[v - c] + 1);
return dp[amount] === Infinity ? -1 : dp[amount];
}Longest common subsequence (LCS)
dp[i][j] = LCS of the first i chars of A and the first j chars of B.
LCS powers diff, git merge, and DNA alignment.
Edit distance (Levenshtein)
Minimum insertions, deletions and substitutions to turn A into B. dp[i][j]:
- If
A[i−1] == B[j−1]:dp[i−1][j−1](free). - Else
1 + min(dp[i−1][j]delete,dp[i][j−1]insert,dp[i−1][j−1]replace). - Base:
dp[i][0] = i,dp[0][j] = j.
int minDistance(String a, String b) {
int m = a.length(), n = b.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 0; i <= m; i++) dp[i][0] = i;
for (int j = 0; j <= n; j++) dp[0][j] = j;
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
dp[i][j] = a.charAt(i - 1) == b.charAt(j - 1)
? dp[i - 1][j - 1]
: 1 + Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1]));
return dp[m][n];
}def min_distance(a: str, b: str) -> int:
m, n = len(a), len(b)
prev = list(range(n + 1)) # rolling 1D array: O(n) space
for i in range(1, m + 1):
cur = [i] + [0] * n
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]:
cur[j] = prev[j - 1]
else:
cur[j] = 1 + min(prev[j - 1], prev[j], cur[j - 1])
prev = cur
return prev[n]function minDistance(a: string, b: string): number {
const m = a.length, n = b.length;
let prev = Array.from({ length: n + 1 }, (_, j) => j);
for (let i = 1; i <= m; i++) {
const cur = [i, ...new Array(n).fill(0)];
for (let j = 1; j <= n; j++)
cur[j] = a[i - 1] === b[j - 1] ? prev[j - 1] : 1 + Math.min(prev[j - 1], prev[j], cur[j - 1]);
prev = cur;
}
return prev[n];
}Bitmask DP
When n ≤ ~20, a subset can be a bitmask. Travelling salesman: dp[mask][v] = cheapest path that visits exactly the cities in mask and ends at v. Transition: extend to an unvisited city u. O(2ⁿ · n²) — versus O(n!) brute force (20! ≈ 2.4 × 10¹⁸ vs 2²⁰·400 ≈ 4 × 10⁸).
int tsp(int[][] d) {
int n = d.length, FULL = (1 << n) - 1, INF = Integer.MAX_VALUE / 2;
int[][] dp = new int[1 << n][n];
for (int[] row : dp) Arrays.fill(row, INF);
dp[1][0] = 0; // start at city 0
for (int mask = 1; mask <= FULL; mask++)
for (int v = 0; v < n; v++) {
if (dp[mask][v] == INF) continue;
for (int u = 0; u < n; u++)
if ((mask & (1 << u)) == 0)
dp[mask | 1 << u][u] = Math.min(dp[mask | 1 << u][u], dp[mask][v] + d[v][u]);
}
int best = INF;
for (int v = 0; v < n; v++) best = Math.min(best, dp[FULL][v] + d[v][0]);
return best;
}from functools import cache
def tsp(d):
n = len(d)
@cache
def go(mask, v): # cities in mask visited, currently at v
if mask == (1 << n) - 1:
return d[v][0]
return min(d[v][u] + go(mask | 1 << u, u)
for u in range(n) if not mask & (1 << u))
return go(1, 0)function tsp(d: number[][]): number {
const n = d.length, FULL = (1 << n) - 1;
const dp = Array.from({ length: 1 << n }, () => new Array(n).fill(Infinity));
dp[1][0] = 0;
for (let mask = 1; mask <= FULL; mask++)
for (let v = 0; v < n; v++) {
if (dp[mask][v] === Infinity) continue;
for (let u = 0; u < n; u++)
if (!(mask & (1 << u)))
dp[mask | (1 << u)][u] = Math.min(dp[mask | (1 << u)][u], dp[mask][v] + d[v][u]);
}
return Math.min(...dp[FULL].map((c, v) => c + d[v][0]));
}- Longest Increasing Subsequencetails + binary searchmedium
- Coin Change / Coin Change IImin coins / count waysmedium
- Longest Common Subsequence2D prefix DPmedium
- Edit Distanceinsert / delete / replacemedium
- Word Breakdp[i] = any dp[j] && word(j..i)medium
- Partition Equal Subset Sumsubset-sum knapsackmedium
- Burst Balloonsinterval DP: last balloon bursthard
- Shortest Path Visiting All NodesBFS over (node, mask)hard
- LIS: O(n²) DP or O(n log n) with tails + binary search.
- Coin change: unbounded knapsack over amounts.
- LCS and edit distance: 2D DP over prefixes of two strings; roll to O(n) space.
- Bitmask DP handles subsets of up to ~20 items in O(2ⁿ · poly(n)).
QWhy do loop orders matter in 'coin change II' (number of combinations)?medium
With coins in the outer loop and amounts inside, each combination is built in a fixed coin order, so 2 and 1 count once. Swapping the loops counts ordered sequences (permutations) instead.
QReconstruct the LIS itself, not just its length.hard
Alongside tails, store the array index of each tail and a parent[i] pointing to the index of the previous element in the subsequence ending at i. Walk parents back from the last tail.