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:
- Recognize it: the brute force is recursive and solves the same subproblems repeatedly (count paths, minimum cost, maximum value, number of ways).
- State: the smallest description of a subproblem the rest depends on, like “the fewest coins for amount
a” or “the edit distance between the firstiandjcharacters”. - Transition: ask what the last decision was. “The last coin was c” gives
fewest(a) = 1 + min over c of fewest(a − c). - Base cases: the trivially known states (amount 0, empty strings).
- 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
- How do you work out and explain the time and space complexity of your solution?Junior
- What's the difference between a stack and a queue, and when would you use each?Junior
- How do you find the first occurrence of a value in a sorted array that has duplicates?Mid-level
- When would you use BFS instead of DFS, and vice versa?Mid-level