Skip to content
Commitwise
Menu

How do you approach a dynamic programming problem?

AlgorithmsMid-level

In shortCheck for overlapping subproblems, then define the state, the transition from the last decision, the base cases and the evaluation order; implement top-down with memoization or bottom-up with a table, and optimize space once it works.

Model answer

A recipe that works for most interview DP problems:

  1. Recognize it: the brute force is recursive and solves the same subproblems repeatedly (count paths, minimum cost, maximum value, number of ways).
  2. State: the smallest description of a subproblem the rest depends on, like “the fewest coins for amount a” or “the edit distance between the first i and j characters”.
  3. Transition: ask what the last decision was. “The last coin was c” gives fewest(a) = 1 + min over c of fewest(a − c).
  4. Base cases: the trivially known states (amount 0, empty strings).
  5. Order and answer: compute states after their dependencies; say which state is the answer.

Then implement it top-down (the recursion plus a shared memo, natural to write, visits only reachable states) or bottom-up (a table filled in order, no recursion depth issues, easy to space-optimize). Complexity is the number of states times the work per transition.

Say the trade-offs: rolling arrays reduce space (often O(n·m) to O(m)) but make reconstructing the actual choices harder; sentinels like Int.MAX_VALUE overflow when you add to them; and greedy is tempting but needs a proof, while DP doesn’t.

What they're looking for

A repeatable method rather than recalled solutions, the ability to derive a recurrence on an example, complexity as states times transition cost, and practical concerns like space optimization and overflow.

Common mistakes

  • Jumping to code without defining the state.
  • Using greedy without checking a counterexample.
  • Memoization caches that aren't shared, or recursion too deep for the input size.

More algorithms questions

Esc

Type to search the whole site.