Dynamic programming

State definition first, transition second, memo vs tabulation last. Knapsack, LIS, edit distance, and interval DP cover most of what gets asked.

About 32 min read3-question knowledge check

The mental model

Dynamic programming is **not recomputing what you already know.** That is the whole idea, stripped of jargon. The classic illustration: computing the 50th Fibonacci number by the naive recursion fib(n) = fib(n-1) + fib(n-2) recomputes fib(3) about 10 billion times, because the recursion tree re-solves the same small problems over and over. Write each answer down the first time and read it back after — a scratchpad — and the same computation goes from taking minutes or hours (about 40 billion calls for fib(50)) to finishing in microseconds. DP is that scratchpad, formalized.

The analogy that sticks: climbing a staircase where you can take 1 or 2 steps. How many ways to reach step n? The number of ways to reach step n is (ways to reach n−1) + (ways to reach n−2), because your last move was either a single or a double step. Notice two things: the answer to a big problem is built from answers to *smaller* problems (a step depends on lower steps), and the same smaller problems appear again and again (step 5 is used by both step 6 and step 7). Those two properties — optimal substructure (the big answer is composed of sub-answers) and overlapping subproblems (the same sub-answers recur) — are the two conditions under which DP gives a correct and efficient solution. If both hold, DP turns an exponential brute force into a polynomial solution by solving each distinct subproblem once.

Why does this exist as a named technique? Because an enormous class of optimization and counting problems — "the best way to…", "the number of ways to…", "the minimum cost to…", "can we reach…" — have this structure, and the brute force (try every combination) is exponential. DP is the systematic way to collapse that exponential search by memoizing. The interview reality: DP is the topic candidates fear most, and the fear comes from trying to *see the whole solution at once*. The cure is a discipline the roadmap states exactly: define the state first, write the transition second, choose memoization versus tabulation last. Get the state and transition right and the code writes itself; guess at code without them and you flail. Knapsack, longest-increasing-subsequence, edit distance, and interval DP cover the overwhelming majority of what gets asked — learn those patterns and you have covered the ground.

The full lesson continues with 15 more sections
  • Deep dive
  • Internal architecture
  • Real-world use cases
  • Best practices
  • Common mistakes
  • Performance
  • Security
  • Production troubleshooting
  • Advantages & disadvantages
  • Alternatives
  • Interview expectations
  • Interview questions
  • Facts to remember
  • Cheat sheet
  • Quick revision