Classic DP Problems

Longest increasing subsequence, coin change, LCS, edit distance and bitmask DP — the problems every DP question is built from.

Advanced 2 min readLesson 9 of 18 Interview Q&A

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 + max dp[j] over j < i with a[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). tails stays 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;
}

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];
}

Longest common subsequence (LCS)

dp[i][j] = LCS of the first i chars of A and the first j chars of B.

dp[i][j]={dp[i−1][j−1]+1Ai=Bjmax⁡(dp[i−1][j], dp[i][j−1])otherwisedp[i][j] = \begin{cases} dp[i-1][j-1] + 1 & A_{i} = B_{j} \\ \max(dp[i-1][j],\ dp[i][j-1]) & \text{otherwise} \end{cases}
acbdabcd0000001111011220122201223
LCS of 'abcd' and 'acbd' = 3 ('abd'). Green cells are where characters matched.

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];
}

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;
}
Practice problems
  • 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
Key takeaways
  • 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)).
Interview questions
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.