CodingPatterns9 min read

Dynamic Programming: From Recursion to a Table

This lesson is for candidates in software and data coding rounds who can follow a dynamic programming solution after the fact but cannot produce one under pressure. The fix is not memorizing problems. It is a five-step recipe that turns a recursive idea into a table, plus a way of explaining it that lets the interviewer follow every step. Two worked examples, one 1D and one 2D, show the recipe end to end.

How to recognize a DP problem

Dynamic programming fits when two things are true:

  • Optimal substructure. The best answer for the whole problem is built from best answers to smaller versions of it. The fewest coins for 6 is one coin plus the fewest coins for whatever is left.

  • Overlapping subproblems. A plain recursive solution asks the same smaller question many times. Caching each answer once removes the repeats.

The wording usually gives it away:

  • "Minimum", "maximum", "longest", "fewest" over a sequence of choices.

  • "How many ways" to reach something.

  • "Is it possible" to reach a target, where each step has several options.

A second clue is that a greedy rule almost works but you can find a counterexample. When the locally best choice can be wrong, you need to compare all the choices, and DP is how you do that without exponential cost.

How DP problems are judged

The SmartIntervu coding report scores problem solving, correctness, code quality, testing and edge cases, and communication. DP is mostly decided in problem solving and communication: the interviewer wants to hear why greedy or plain recursion is not enough, and an exact definition of the state, before any code. Correctness is lost on base cases, evaluation order and the impossible case. For testing, trace the smallest inputs (amount 0, an empty string) and one input with no answer.

Interviewers probe DP in a predictable order. After a recursive idea they ask "what is repeated here?", which is your cue to add the memo. After the memo they ask "can you do it without recursion?" and then "can you use less space?". If you are stuck on the recurrence, the hint is usually "what was the last choice?", as in the last coin used or the last characters compared. The memo, the table and the two-row version below answer them in that order.

The five-step recipe

Say each step out loud before writing code. Most DP bugs are a fuzzy state definition, and saying it forces you to make it exact.

  1. Define the state in words. "dp[a] is the fewest coins that sum to exactly a." If you cannot say it in one sentence, the state is wrong.

  2. Write the recurrence. How a state is built from smaller states: "dp[a] is 1 plus the minimum of dp[a - c] over every coin c no larger than a."

  3. Set the base cases. The smallest states you know directly: "dp[0] is 0."

  4. Choose the evaluation order. Every state must be computed after the states it depends on. For dp[a] that means increasing a.

  5. Locate the answer. Usually the last cell, sometimes the best over a row.

Complexity follows directly: the number of states times the work per state.

Worked example in 1D: fewest coins

Problem: given coin values and an amount, return the fewest coins that sum to the amount, or -1 if it is impossible. Any coin can be used any number of times.

Start by testing greedy, since it is the obvious idea. With coins 1, 3 and 4 and amount 6, greedy takes the largest coin first: 4, then 1, then 1, for three coins. But 3 plus 3 is two coins. Greedy fails, so we need to compare choices. That is the moment to say "this looks like dynamic programming."

Top down: recursion plus a memo

Write the recurrence as a recursive function first. It is the most direct translation of step 2.

function minCoins(coins: number[], amount: number): number {
  const memo = new Map<number, number>();

  function best(remaining: number): number {
    if (remaining === 0) return 0;
    if (remaining < 0) return Infinity; // overshot: not a valid path
    const cached = memo.get(remaining);
    if (cached !== undefined) return cached;

    let result = Infinity;
    for (const coin of coins) {
      result = Math.min(result, best(remaining - coin) + 1);
    }
    memo.set(remaining, result);
    return result;
  }

  const answer = best(amount);
  return answer === Infinity ? -1 : answer;
}

Without the memo, best(6) calls best(5), best(3) and best(2), and best(5) calls best(2) again, and so on: the same values are recomputed many times and the call tree grows exponentially. With the memo each amount from 0 to 6 is computed once.

Bottom up: the same recurrence as a table

Tabulation fills the states in the order from step 4, with no recursion.

function minCoinsTable(coins: number[], amount: number): number {
  const dp: number[] = new Array(amount + 1).fill(Infinity);
  dp[0] = 0;
  for (let a = 1; a <= amount; a++) {
    for (const coin of coins) {
      if (coin <= a) dp[a] = Math.min(dp[a], dp[a - coin] + 1);
    }
  }
  return dp[amount] === Infinity ? -1 : dp[amount];
}

Trace it for coins 1, 3 and 4 and amount 6. dp[0] is 0, dp[1] is 1, dp[2] is 2. dp[3] is 1, from dp[0] plus a 3. dp[4] is 1, from dp[0] plus a 4. dp[5] is 2, from dp[4] or dp[1] plus a coin. dp[6] is 2, from dp[3] plus a 3. The answer is 2, matching 3 plus 3.

There are amount + 1 states and each tries every coin, so the time is O(amount * number of coins) and the space is O(amount).

Memoization or tabulation?

Both have the same complexity. Pick by what you can explain fastest:

  • Memoization follows the recurrence word for word, computes only the states actually reached, and is easy to write first. Its cost is recursion depth, which can overflow the stack on large inputs.

  • Tabulation has no recursion and makes the evaluation order explicit, which is what enables space optimization.

A strong move in an interview is to write the memoized version, then say: "I can turn this into a bottom-up table, which also lets me cut the space." Then do it if time allows.

Worked example in 2D: longest common subsequence

Problem: given two strings, return the length of their longest common subsequence: the longest sequence of characters that appears in both in the same order, not necessarily next to each other. For "abcde" and "ace" the answer is 3 ("ace").

Run the recipe:

  1. State: dp[i][j] is the length of the longest common subsequence of the first i characters of a and the first j characters of b.

  2. Recurrence: if a[i - 1] equals b[j - 1], that character extends the best answer without it: dp[i - 1][j - 1] + 1. Otherwise one of the two last characters is not in the answer, so take the better of dropping either: max(dp[i - 1][j], dp[i][j - 1]).

  3. Base cases: dp[0][j] and dp[i][0] are 0, since an empty string shares nothing.

  4. Order: rows top to bottom, each row left to right, so the cells above, to the left and diagonally up-left are ready.

  5. Answer: dp[a.length][b.length].

function lcsLength(a: string, b: string): number {
  const dp: number[][] = Array.from({ length: a.length + 1 }, () =>
    new Array(b.length + 1).fill(0)
  );
  for (let i = 1; i <= a.length; i++) {
    for (let j = 1; j <= b.length; j++) {
      dp[i][j] =
        a[i - 1] === b[j - 1]
          ? dp[i - 1][j - 1] + 1
          : Math.max(dp[i - 1][j], dp[i][j - 1]);
    }
  }
  return dp[a.length][b.length];
}

The time and space are both O(m * n) for strings of length m and n.

Space optimization

Each row reads only the row above it, so two rows are enough:

function lcsLengthTwoRows(a: string, b: string): number {
  let prev: number[] = new Array(b.length + 1).fill(0);
  for (let i = 1; i <= a.length; i++) {
    const curr: number[] = new Array(b.length + 1).fill(0);
    for (let j = 1; j <= b.length; j++) {
      curr[j] =
        a[i - 1] === b[j - 1]
          ? prev[j - 1] + 1
          : Math.max(prev[j], curr[j - 1]);
    }
    prev = curr;
  }
  return prev[b.length];
}

Space drops to O(n), and to O(min(m, n)) if you pass the shorter string as b. Mention the trade-off: with only two rows you can no longer walk back through the table to rebuild the subsequence itself, just its length.

How to explain a DP solution out loud

Interviewers score the reasoning as much as the code. A clear explanation sounds like this:

"Greedy fails on 1, 3, 4 with amount 6, so I need to compare choices. Let dp[a] be the fewest coins summing to a. The last coin is some c, so dp[a] is 1 plus the minimum of dp[a minus c]. Base case dp[0] is 0. I fill a from 1 up, and the answer is dp[amount]. That's O(amount times coins) time and O(amount) space."

Six sentences: why DP, the state, the recurrence, the base case, the order and answer, the complexity. Then code. If you get stuck partway, going back to the state sentence usually shows where the gap is.

Follow-ups to expect

  • "Can you return the coins themselves, not just the count?" Store which choice produced each state, then walk back from the answer.

  • "Can you reduce the space?" Check which earlier states each cell reads. If it only needs the previous row or the last few values, keep only those.

  • "What if the amount is huge but there are few coins?" The table becomes too big. Say so, and discuss whether the constraints allow it.

  • "Why not greedy?" Give the counterexample. Having one ready is strong evidence you understand the problem.

What changes with seniority

A junior candidate should reach a correct memoized solution with some help on the state. A mid-level candidate defines the state unprompted, converts to a table, and states time and space. A senior candidate also explains why greedy fails with a counterexample, reduces the space, reconstructs the actual answer (the coins, the subsequence) when asked, and says when the table is too large for the input limits.

Mistakes that cost points

  • A vague state. "dp[i] is the answer up to i" is not a definition. Say exactly what quantity the cell holds.

  • Wrong evaluation order. Reading a cell before it is filled gives silent wrong answers. Name the order before coding.

  • Off-by-one in 2D tables. Using i as a string index and a table index at once. The common fix is a table one larger in each dimension, with row 0 and column 0 as the empty prefix.

  • Forgetting the impossible case. Initialize to infinity (or a sentinel) and convert it at the end, as with the -1 above.

  • Jumping to the optimized version. Get a correct memoized solution first. An optimized wrong answer scores worse than a slower right one.

Practice it

Take 15 minutes with this drill: count the number of distinct ways to climb a staircase of n steps taking 1 or 2 steps at a time. Write the five recipe sentences first, then the memoized version, then the table, then the two-variable version. Check that n = 5 gives 8.

Then start a coding interview such as Design an LRU Cache and practice the same habit there: state your data structures and what each one holds before you write a line. The coding quick start covers the full method, and backtracking covers the search problems that DP sometimes replaces.

Practise this in a mock interview

Try what this lesson covers out loud: the AI interviewer asks one of these questions, follows up, and scores your answer.

Read next

  • Intervals and Greedy: Sort First, Then Decide Once

    Merge, insert and count overlapping intervals with a sort-then-sweep template, justify a greedy rule with the exchange argument, and recognize when greedy fails and dynamic programming is needed.

    9 min read

  • Two Pointers

    Recognize when sorted input, in-place edits or a linked list call for two pointers, then apply the opposite-ends, reader-writer and fast-slow shapes and say why each pointer move is safe.

    8 min read

  • Sliding Window

    Spot contiguous-range problems, run fixed and variable windows from one template, decide where to record the answer, and explain why the window breaks once values can be negative.

    8 min read

  • Binary Search

    Write one boundary-search template without off-by-one bugs, derive exact, first, last and count searches from it, and binary search on the answer and on rotated arrays.

    9 min read