DSA · Patterns, not puzzles

What is dynamic programming?

Mediumdynamic-programmingoptimizationstateUpdated Oct 2026
Quiz this track

Short answer

Dynamic programming solves problems by defining overlapping subproblems and combining their optimal results. It requires optimal substructure and a way to avoid recomputing the same states.

DP is not a specific algorithm; it is a way of organising a solution. You define a state that captures everything needed to describe a subproblem, write a recurrence that relates that state to smaller states, and compute states in an order that makes the answers available.

The two ingredients

  • Overlapping subproblems: the same state is needed more than once
  • Optimal substructure: the best answer can be built from best answers to subproblems
  • State: the minimum information that separates one subproblem from another
  • Transition: how a state is computed from smaller states
  • Base cases: the smallest states that can be answered directly
js
function climbStairs(n) {
  if (n <= 2) return n;
  let prev = 1;
  let current = 2;
  for (let step = 3; step <= n; step++) {
    const next = prev + current;
    prev = current;
    current = next;
  }
  return current;
}
The recurrence is ways(n) = ways(n - 1) + ways(n - 2), and only the last two values are needed.

Start by writing the recurrence and the base cases before optimising memory. Once the table is correct, you can often reduce it to a few rolling variables. That order avoids clever but incorrect code.

DP is unnecessary when subproblems do not overlap or when a greedy choice is provably optimal. Naming those cases shows judgement, not just memorised patterns.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1How do you define the state for a DP problem?
  2. 2What is the difference between overlapping subproblems and optimal substructure?
  3. 3How do you reduce a DP table to O(1) space?
  4. 4When is greedy a better choice than DP?

Say it in the interview

Dynamic programming is about identifying overlapping subproblems and building answers from smaller states. I define what a state means, write the recurrence and base cases, then decide whether to memoize or fill a table. For climbing stairs, the state is the number of steps and the transition adds the previous two answers. I start with the straightforward table and only optimise space after the recurrence is correct.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live DSA mock interview and get scored feedback on depth, clarity and confidence.