Dynamic Programming

Solve each overlapping subproblem once. A step-by-step framework — state, transition, base case, order — with memoization and tabulation.

Intermediate 4 min readLesson 8 of 18 Interview Q&A

Dynamic programming (DP) solves problems by breaking them into overlapping subproblems, solving each once, and storing the answers. It turns exponential brute force into polynomial time.

A problem is a DP candidate when it has:

  1. Optimal substructure — the optimal answer is built from optimal answers to subproblems.
  2. Overlapping subproblems — the same subproblems are needed again and again.

The framework

  1. Define the state. What does dp[i] (or dp[i][j]) mean, in words? This is the hardest and most important step.
  2. Write the transition. How is dp[i] computed from smaller states?
  3. Set base cases. The smallest states you know directly.
  4. Choose an order. Compute states so dependencies are ready (or recurse with memoization).
  5. Locate the answer (dp[n], max(dp), …) and optimise space if only recent rows are needed.

Worked example: climbing stairs

You can climb 1 or 2 steps at a time. How many distinct ways to reach step n?

  • State: ways(i) = number of ways to reach step i.
  • Transition: the last move was a 1-step from i−1 or a 2-step from i−2, so ways(i) = ways(i−1) + ways(i−2).
  • Base: ways(0) = 1, ways(1) = 1.

Top-down: memoization

Write the natural recursion, then cache results.

Bottom-up: tabulation

Fill a table from the base cases upward — no recursion, and you can often keep only the last few values.

// Top-down (memoized recursion)
int ways(int i, int[] memo) {
    if (i <= 1) return 1;
    if (memo[i] != 0) return memo[i];
    return memo[i] = ways(i - 1, memo) + ways(i - 2, memo);
}

// Bottom-up (tabulation)
int climbStairs(int n) {
    int[] dp = new int[n + 1];
    dp[0] = dp[1] = 1;
    for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2];
    return dp[n];
}

// Bottom-up with O(1) space
int climbStairsO1(int n) {
    int prev = 1, cur = 1;
    for (int i = 2; i <= n; i++) { int next = prev + cur; prev = cur; cur = next; }
    return cur;
}
Top-down (memoization)
  • Natural: write the recursion, add a cache
  • Only computes states actually needed
  • Recursion overhead; stack depth limits
  • Easier to derive first
Bottom-up (tabulation)
  • Iterative loops in dependency order
  • Computes every state
  • No recursion; usually faster
  • Enables rolling-array space optimisation

Worked example: house robber

Houses in a row hold a[i] money; you can't rob two adjacent houses. Maximise loot.

  • State: dp[i] = best loot from the first i houses.
  • Transition: skip house i−1 → dp[i−1]; or rob it → dp[i−2] + a[i−1]. Take the max.
dp0dp1dp2dp3dp4dp5027111112
Houses [2, 7, 9, 3, 1]: dp[3] = max(dp[2], dp[1] + 9) = max(7, 11) = 11. Answer: 12.
int rob(int[] a) {
    int prev2 = 0, prev1 = 0;            // dp[i-2], dp[i-1]
    for (int x : a) {
        int cur = Math.max(prev1, prev2 + x);
        prev2 = prev1;
        prev1 = cur;
    }
    return prev1;
}

Worked example: unique paths in a grid (2D DP)

A robot moves only right or down in an m × n grid. dp[r][c] = dp[r−1][c] + dp[r][c−1], with the first row and column all 1.

1111123413610
3 × 4 grid: 10 unique paths. Each cell = cell above + cell to the left.

Recognising DP problems

Strong signals in the problem statement:

  • "Count the number of ways to …"
  • "Minimum / maximum cost, profit, length …"
  • "Is it possible to reach / partition / form …"
  • Choices at each step, where a greedy choice can go wrong.
  • Constraints like n ≤ 1000 or n ≤ 5000 (O(n²) DP) or a small "capacity" dimension.

Common DP families

FamilyStateExamplesLesson
1D lineardp[i]stairs, house robber, decode ways, LISDP classics
Two sequencesdp[i][j] over prefixesLCS, edit distanceDP on sequences
Knapsackdp[i][capacity]0/1 knapsack, subset sum, coin changeKnapsack DP
Griddp[r][c]unique paths, min path sumDP on grids & intervals
Intervaldp[l][r]matrix chain, burst balloons, palindromesDP on grids & intervals
Bitmaskdp[mask]TSP on ≤ 20 cities, assignmentsDP classics
Treedp[node][state]house robber III, max independent setTree DFS
Key takeaways
  • DP = recursion + caching for overlapping subproblems with optimal substructure.
  • Always define the state in words first; then transition, base cases, order, answer.
  • Top-down memoization is easiest to derive; bottom-up tabulation is faster and space-optimisable.
  • Complexity = (number of states) × (work per transition).
Interview questions
QHow do you derive the time complexity of a DP solution?easy

Multiply the number of distinct states by the work to compute each one. Edit distance has (m+1)(n+1) states with O(1) transitions → O(mn). LIS with dp[i] = max over j < i has n states with O(n) transitions → O(n²).

QDecode ways: how many ways can a digit string be decoded with A=1 … Z=26?medium

dp[i] = ways to decode the first i characters. Add dp[i−1] if s[i−1] is not '0'; add dp[i−2] if the two-digit number s[i−2..i−1] is between 10 and 26. Base dp[0] = 1. O(n) time, O(1) space with two variables.

QHow do you reconstruct the actual solution, not just its value?medium

Either store the choice made at each state (a "parent" table) or, after filling the table, walk backwards from the answer state, at each step checking which transition produced its value.