Lesson 22 of 30
Dynamic programming, stripped of the scary name: remember answers you've already worked out, so you never redo the same work twice.
12 min read
Every option explains itself — why the right one is right, and why each wrong one is wrong. Miss one and it comes back later on a spaced-repetition schedule.
This topic is about judgment and practical tradeoffs more than a single right answer — a mock interview is the better way to test yourself on it.
Be interviewed on this →Hints without spoilers, and a plain explanation of why a wrong answer was wrong — answered only from this lesson. Free account, no card.
Sign up freeWhat interviewers actually ask about this, and what a strong answer has to cover.
A strong answer covers
Likely follow-ups
Imagine someone reads you a phone number, digit by digit, and you write it down. Later, when you need it again, would you call them back and ask them to repeat the whole thing? No — you'd look at what you already wrote. That's the entire idea behind dynamic programming: remember answers you've already worked out, so you never redo the same work twice.
A lot of problems, solved the first way that comes to mind, end up asking the exact same sub-question over and over without realizing it. Dynamic programming means noticing that, and writing the answer down the first time so every later ask is instant.
If the words "dynamic programming" sound like something only computer science majors understand, here's the honest truth: the name is intimidating, the idea underneath it is not. It's closer to "don't repeat yourself" than to anything mathematical. You already do this in daily life — that's the whole trick.
Say you're climbing a staircase, one or two steps at a time, and you want to know how many different ways there are to reach the top.
// How many ways can you climb `n` stairs, taking 1 or 2 steps at a time?
// Without memory, this recalculates the same smaller staircases again
// and again. With memory, we write each answer down once.
function waysToClimb(n, alreadySolved = {}) {
if (n === 0) return 1; // standing at the top counts as 1 way
if (n < 0) return 0; // overshot the stairs — not a valid way
if (alreadySolved[n] !== undefined) {
return alreadySolved[n]; // solved this one before — look it up
}
// otherwise, solve it: we either took a 1-step or a 2-step to get here
const result = waysToClimb(n - 1, alreadySolved) + waysToClimb(n - 2, alreadySolved);
alreadySolved[n] = result; // write it down before we need it again
return result;
}
console.log(waysToClimb(5)); // 8 ways to climb a 5-step staircase
This builds directly on recursion from the JavaScript track — a function calling smaller versions of itself. Dynamic programming is that same idea with one addition: a notebook it checks before doing any piece of work twice.