Skip to the solution
MediumDSA9 min read

What is dynamic programming?

1.2k views

The problem

Question presented to candidate: "What is dynamic programming? Explain it in your own words, then show me in Python how you would turn a slow recursive Fibonacci into a dynamic-programming solution, and tell me when you would reach for DP at all."

What a strong answer should cover:

  • DP = solve each overlapping subproblem once and reuse the stored answer; it needs overlapping subproblems and optimal substructure.
  • The two styles: memoization (top-down: recursion + cache) and tabulation (bottom-up: fill a table in dependency order), plus the rolling-variable space optimisation.
  • The five-step recipe: state, recurrence, base cases, order, answer β€” and the running-time formula states Γ— work per state.
  • Why plain recursion is exponential (about 2.7 million calls for fib(30)) and DP is O(n).
  • Python specifics: a dict or functools.cache as the memo, the 1000-frame default recursion limit that breaks deep memoized recursion, arbitrary-precision int, and the mutable-default-argument trap (memo={}).

Code / implementation expected: Optional β€” a short Python function (memoized or tabulated Fibonacci) is the usual illustration; the explanation matters more than the code.

  • dynamic-programming

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonFibonacci four ways: naive recursion, memoization, a table and two variables, with call counts
PythonOverlapping subproblems: how often naive recursion re-solves each fib(k), and the finished table
PythonThe DP recipe on a new problem: fewest perfect squares, where greedy fails

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 40 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

What is a trie and when is it useful?

Continue