Dynamic programming (DP) is a way to solve problems where the “big” answer can be built from smaller answers that repeat.

Most DP wins come from the same move:

Instead of recomputing the same subproblem many times, compute it once and reuse it.

That sounds simple, but DP can feel hard because you have to choose the right subproblem to cache (the “state”), and the

right way to build answers from it (the “transition”).

This article gives you a repeatable workflow you can apply to most DP problems, plus practical TypeScript examples.

What DP is (and isn’t)

DP is not a specific algorithm. It’s a technique for organizing computation.

Two concepts show up constantly:

  • Overlapping subproblems: different paths of a brute force solution ask for the same smaller answer again and again.
  • Optimal substructure: the best answer to the big problem can be composed from best answers to subproblems.

DP is often introduced with “optimization” problems (min/max), but it also solves:

  • Counting: “How many ways…?”
  • Decision: “Is it possible…?”
  • Shortest/longest: “Smallest cost / longest sequence…?”

Recognizing a DP problem

DP is a good fit when you can describe the solution as:

  • “At position i, my future only depends on a small set of facts…”
  • “I have choices; each choice leads to a smaller version of the same problem…”
  • “There’s a constraint like capacity, remaining budget, steps left, or matching prefixes…”

Some classic DP families:

  • 1D over an array/string: prefix/suffix problems (dp[i])
  • 2D table: pair of indices/capacity (dp[i][j])
  • Grid paths: coordinates + obstacles (dp[r][c])
  • Subsequence DP: “use or skip” (dp[i][j] for prefixes)
  • Knapsack-style: capacity constraints (dp[cap] or dp[item][cap])
  • Interval DP: choose a split inside [l, r] (dp[l][r])
  • Bitmask DP: subset states (dp[mask][i])

The DP workflow (the part to memorize)

When you’re stuck, follow this checklist:

  1. Define the goal precisely (min? max? count? boolean?).
  2. Pick a state: the smallest info that uniquely identifies a subproblem.
  3. Write the recurrence: how to compute a state from “smaller” states.
  4. Choose base cases: states you know without recursion.
  5. Pick an evaluation order:
  • Top-down (memoization): recurse + cache results.
  • Bottom-up (tabulation): fill a table in increasing “size.”
  1. Analyze complexity: number of states × transitions per state.
  2. Optimize space (optional): compress dimensions when only the previous layer is needed.

If you can’t write the recurrence, your state is usually wrong or incomplete.

Memoization vs tabulation

Both compute the same values; the difference is control flow.

Top-down memoization

  • Great when only a small fraction of states are actually reachable.
  • Feels natural if you already have a recursive brute force solution.
  • Beware recursion depth in JS/TS for large inputs.

Bottom-up tabulation

  • Often faster (no recursion overhead, predictable memory).
  • Usually easier to reason about iteration order.
  • Makes space optimization easier.

Example 1: Fibonacci (the “hello world” of DP)

The naive recursive Fibonacci repeats the same subproblems exponentially.

Top-down (memoized recursion)

export function fib(n: number, memo = new Map<number, number>()): number {
  if (n < 0) throw new Error("n must be >= 0");
  if (n <= 1) return n;
  const cached = memo.get(n);
  if (cached !== undefined) return cached;
  const value = fib(n - 1, memo) + fib(n - 2, memo);
  memo.set(n, value);
  return value;
}

Bottom-up (iterative)

export function fibIter(n: number): number {
  if (n < 0) throw new Error("n must be >= 0");
  if (n <= 1) return n;
  let prev2 = 0;
  let prev1 = 1;
  for (let i = 2; i <= n; i++) {
    const next = prev1 + prev2;
    prev2 = prev1;
    prev1 = next;
  }
  return prev1;
}

Both run in O(n) time. The iterative version uses O(1) space.

Note: Fibonacci numbers overflow number quickly. If you need big n, switch to bigint.

Example 2: Coin change (minimum coins)

Problem: given coin denominations, find the minimum number of coins needed to make amount. You can use each coin

unlimited times.

This is a classic unbounded knapsack DP.

State and recurrence

  • State: dp[x] = minimum coins to make amount x.
  • Base: dp[0] = 0 (0 coins to make 0).
  • Transition: for each coin c, if x - c >= 0 then:
  • dp[x] = min(dp[x], dp[x - c] + 1)

Bottom-up implementation (TypeScript)

export function minCoins(coins: number[], amount: number): number {
  if (amount < 0) throw new Error("amount must be >= 0");
  const dp = Array.from({ length: amount + 1 }, () => Number.POSITIVE_INFINITY);
  dp[0] = 0;

  for (let x = 1; x <= amount; x++) {
    for (const c of coins) {
      if (x - c >= 0 && dp[x - c] !== Number.POSITIVE_INFINITY) {
        dp[x] = Math.min(dp[x], dp[x - c] + 1);
      }
    }
  }

  return dp[amount] === Number.POSITIVE_INFINITY ? -1 : dp[amount];
}

Complexity

  • States: amount + 1
  • Transitions per state: coins.length
  • Total: O(amount * coins.length) time, O(amount) space

Example 3: 0/1 knapsack (and why iteration order matters)

Problem: each item can be taken at most once. Maximize value under a weight capacity.

2D state (conceptually)

  • dp[i][cap] = best value using the first i items with capacity cap.

But you can compress to 1D because each row only depends on the previous row.

1D optimized implementation

Key detail: iterate capacities downwards so each item is used at most once.

export function knapsack01(
  weights: number[],
  values: number[],
  capacity: number,
): number {
  if (weights.length !== values.length) throw new Error("weights/values length mismatch");
  const dp = Array.from({ length: capacity + 1 }, () => 0);

  for (let i = 0; i < weights.length; i++) {
    const w = weights[i]!;
    const v = values[i]!;
    for (let cap = capacity; cap >= w; cap--) {
      dp[cap] = Math.max(dp[cap], dp[cap - w] + v);
    }
  }

  return dp[capacity]!;
}

Why descending? If you go upward (cap = w..capacity), then dp[cap - w] might already include the current item, turning

it into the unbounded knapsack by accident.

How to choose a good DP state

A good state is:

  • Small: few dimensions/parameters.
  • Sufficient: enough info so the remainder of the problem is independent of the path taken so far.
  • Unique: if two subproblems are “the same,” they should share the same state key.

Practical heuristics:

  • If your recursion function arguments keep growing (“I need one more flag”), your state is missing information.
  • If your DP table is huge and sparse, you might be caching too much (or need a different view of the problem).
  • If you can’t define “smaller” states, you won’t know how to order tabulation.

Debugging DP (how to get unstuck)

DP bugs are usually:

  • Off-by-one (wrong base cases, wrong loop bounds)
  • Wrong meaning of the state (you think dp[i] means one thing, but transitions assume another)
  • Wrong iteration order (especially when compressing space)

Tactics that work:

  • Write a 2D version first (even if you’ll optimize later). It’s easier to verify.
  • Add a tiny example and print the DP table for it (e.g., amount <= 10, n <= 6).
  • Use sentinel values (Infinity, -Infinity) and guard them to avoid “fake” transitions.
  • Assert invariants (e.g., dp[0] === 0, dp[x] <= dp[x+1] when it should hold).

A quick DP pattern map (cheat sheet)

  • Prefix DP: dp[i] answers for first i items (i from 0..n).
  • Two choices (“take or skip”): dp[i] = best(dp[i-1], dp[i-1] + take(i)).
  • Grid movement: dp[r][c] = combine(dp[r-1][c], dp[r][c-1]).
  • String alignment (LCS/edit distance): dp[i][j] for prefixes of lengths i and j.
  • Intervals: dp[l][r] = best over k in (l..r) (often O(n^3) unless optimized).
  • Bitmask: dp[mask][last] for visiting subsets (traveling salesman variants).

Closing thought

Dynamic programming becomes much easier when you stop trying to “spot the trick” and instead force the problem through the

workflow:

state → recurrence → base cases → order → complexity

Once you can do that, DP stops being a magic topic and becomes a tool you can reliably reach for.