Dynamic programming patterns for coding interviews

Dynamic programming solves a problem by answering smaller versions of it once, storing those answers, and building the full answer from them. Use it when a question asks for a count, a minimum or a maximum, and a brute-force recursion would solve the same sub-question many times. Most interview problems fall into a handful of families, and recognizing the family tells you what the state should be.

By Published 8 min read

When a problem needs dynamic programming

Two properties together point to DP. First, the answer is built from answers to smaller versions of the same question: the cheapest way to reach step 10 depends on the cheapest ways to reach steps 8 and 9. Second, a plain recursion would ask the same smaller question over and over, which is what makes it exponential. If the question asks you to list every arrangement, use backtracking instead, since DP gives counts and best values, not the arrangements themselves (though you can usually reconstruct one best arrangement). If a simple local rule always works, a greedy algorithm may be enough, but be ready to show a case where greedy fails.

A five-step recipe

  1. State, in one sentence"best[i] is the largest total I can collect from the first i items." If you cannot say what a cell means, you cannot write the transition.
  2. TransitionHow one state follows from smaller ones. Usually a choice: take this item or skip it, come from above or from the left, match these two characters or not.
  3. Base casesThe smallest states whose answers you know without thinking: zero items, an empty string, the first row.
  4. OrderFill states so that everything a cell depends on is already computed. Top-down memoization handles order for you.
  5. Answer and spaceWhich cell holds the answer, and whether you only need the last row or last two values, which cuts memory.

Family 1: linear sequences

Each position depends on a few positions just before it. Counting the ways to climb stairs taking one or two steps at a time is the starter version. A more useful one: from a row of values, pick any items as long as no two picked items are neighbors, and maximize the total. For [4, 1, 2, 9, 3], the best is 4 + 9 = 13. Track two numbers: the best total if the previous item was taken, and the best if it was not.

def best_non_adjacent(values):
    take, skip = 0, 0   # best total with / without the previous item
    for v in values:
        take, skip = skip + v, max(take, skip)
    return max(take, skip)
Best total with no two neighbors picked: O(n) time, O(1) space.

Family 2: grids

Moving right or down across a grid, the number of ways to reach a cell is the ways to reach the cell above plus the ways to reach the cell to its left, and blocked cells contribute zero. Because each row only needs the row above, one array of width c is enough: before the update, ways[c] still holds the value from above.

def grid_paths(blocked):
    rows, cols = len(blocked), len(blocked[0])
    ways = [0] * cols
    ways[0] = 1
    for r in range(rows):
        for c in range(cols):
            if blocked[r][c]:
                ways[c] = 0
            elif c > 0:
                ways[c] += ways[c - 1]   # above (old value) + left
    return ways[-1]
Count right/down paths around blocked cells, O(rows × cols) time, O(cols) space.

Family 3: each item used at most once (0/1 choice)

Knapsack-style problems: for each item, take it or leave it, under a capacity or target. The simplest is "can some subset of these numbers add up to exactly T?" Keep a list ok[t] for every total up to T. Loop the totals downward for each item so the item is not counted twice in the same round.

def can_reach(values, target):
    ok = [True] + [False] * target
    for v in values:
        for t in range(target, v - 1, -1):   # backwards: each item once
            ok[t] = ok[t] or ok[t - v]
    return ok[target]
Subset reaching a target: O(n × T) time, O(T) space.

Family 4: items usable any number of times

When items can repeat, loop totals upward instead, or compute each amount from every item directly. Fewest coins to make an amount is the classic. It is also the cleanest example of greedy failing: with coins [1, 4, 6] and amount 8, taking the biggest coin first gives 6 + 1 + 1, three coins, while 4 + 4 uses two.

def fewest_coins(coins, amount):
    INF = float("inf")
    best = [0] + [INF] * amount
    for a in range(1, amount + 1):
        for c in coins:
            if c <= a and best[a - c] + 1 < best[a]:
                best[a] = best[a - c] + 1
    return best[amount] if best[amount] != INF else -1
Python: fewest coins, -1 if impossible. O(amount × coins) time.
function fewestCoins(coins, amount) {
  const best = new Array(amount + 1).fill(Infinity);
  best[0] = 0;
  for (let a = 1; a <= amount; a++) {
    for (const c of coins) {
      if (c <= a && best[a - c] + 1 < best[a]) best[a] = best[a - c] + 1;
    }
  }
  return best[amount] === Infinity ? -1 : best[amount];
}
JavaScript version.

Family 5: two sequences

Comparing two strings or lists uses a table where dp[i][j] describes the first i items of one and the first j of the other. The longest common subsequence (characters in order, not necessarily adjacent) is the template: if the last characters match, extend the diagonal; otherwise take the better of dropping one character from either side. "planet" and "plant" share "plant", length 5. Edit distance and many diff-style questions use the same grid with different costs.

function lcsLength(a, b) {
  let prev = new Array(b.length + 1).fill(0);
  for (let i = 1; i <= a.length; i++) {
    const cur = new Array(b.length + 1).fill(0);
    for (let j = 1; j <= b.length; j++) {
      cur[j] = a[i - 1] === b[j - 1]
        ? prev[j - 1] + 1
        : Math.max(prev[j], cur[j - 1]);
    }
    prev = cur;
  }
  return prev[b.length];
}
JavaScript: longest common subsequence keeping only two rows, O(m × n) time, O(n) space.

Family 6: increasing subsequences

The longest strictly increasing subsequence has an O(n²) DP (best[i] is the longest run ending at i) and a well-known O(n log n) refinement: keep, for each length, the smallest possible tail value, and place each new value with a binary search. For [3, 1, 4, 1, 5, 9, 2, 6] the answer is 4, for example 1, 4, 5, 9. The binary search step is the lower-bound template from the binary search pattern.

import bisect

def lis_length(values):
    tails = []   # tails[k]: smallest tail of an increasing run of length k + 1
    for v in values:
        k = bisect.bisect_left(tails, v)
        if k == len(tails):
            tails.append(v)
        else:
            tails[k] = v
    return len(tails)
Length of the longest strictly increasing subsequence, O(n log n).

Top-down or bottom-up?

Top-down means writing the recursion and caching results, for example with functools.lru_cache in Python or a Map in JavaScript. It is often the fastest way to a correct answer in an interview because it reads like the problem statement. Bottom-up fills a table in a loop, avoids recursion limits and makes space savings visible. A good path is to write top-down first, state its complexity, then offer the table version if the interviewer asks about memory or very large inputs.

Complexity

Cost of the examples on this page
FamilyExampleTimeSpace
LinearBest non-neighbor totalO(n)O(1)
GridPaths around blocked cellsO(r × c)O(c)
0/1 choiceSubset reaching TO(n × T)O(T)
Unbounded choiceFewest coins for amount AO(A × k)O(A)
Two sequencesLongest common subsequenceO(m × n)O(n) with two rows
Increasing subsequenceLongest increasing runO(n log n)O(n)
Cost of the examples on this page. Scroll sideways on a small screen.

Common mistakes

  • A state you cannot describe. If dp[i] means "something about i", the transition will be wrong. Write the sentence first.
  • Wrong loop direction in 0/1 problems. Looping totals upward lets an item be used again, which silently turns it into the unbounded problem.
  • Missing base cases, such as an amount of zero needing zero coins, or the first row of a grid.
  • Assuming greedy works. Test it on a small counterexample before relying on it.
  • Answering the wrong cell. Some problems want dp[n], others the maximum over all cells.

How to explain it out loud

Fictional example

Moving from recursion to a table for the coin question
Candidate
Greedy fails here: for 8 with coins 1, 4 and 6, it picks 6 and needs three coins, but 4 plus 4 is two. So I need to consider every last coin.
Candidate
Let best of a be the fewest coins for amount a. The last coin is some c, so best of a is one plus best of a minus c, minimized over c. Base case: best of 0 is 0.
Candidate
Each amount depends only on smaller amounts, so I fill from 1 up to the target. That is amount times number of coins time and one array of space.

Grid DP and grid search look alike; when you need connected regions or shortest paths instead of counts, see graph traversal patterns and Number of Islands. Everything else is on the coding problems hub.

Practicing with Natively

When a DP problem stalls you in practice, Natively can read it from a screenshot on your Mac or Windows computer and suggest a state definition and transition to compare with yours. Recording a mock round as a transcript lets you check whether you said what each cell means before you coded it. Read more about the AI assistant for coding interviews.

Questions people ask

How do you know a problem needs dynamic programming?

It asks for a count, minimum, maximum or yes/no reachability, the answer is built from smaller versions of the same question, and a plain recursion would solve the same sub-question many times.

What are the most common dynamic programming patterns?

Linear sequences, grids, 0/1 choice (knapsack, each item once), unbounded choice (items reusable, such as coins), two sequences (common subsequence, edit distance) and increasing subsequences.

Should I use memoization or tabulation in an interview?

Memoized recursion is often quicker to get right because it mirrors the problem. Tabulation avoids recursion limits and makes space savings easy; offer it if asked about memory.

How do you define the state in dynamic programming?

Write one sentence saying what a cell means, such as the fewest coins needed for amount a. The transition and base cases follow from that sentence.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP