iq.lab
Python starts when a code cell comes near or you run one
12 Dynamic programming

Lesson 1 of 5

From recursion to memoization

A recursion that asks the same smaller question again and again can take exponential time. Write each answer down the first time you work it out, and each question is answered once, so Fibonacci drops from exponential to linear time. That one change, memoization, is the first of the two ways to do dynamic programming.

About 1 hour 25 minutes, with the 2 problems worked in it
By the end you can
  • Find the repeated calls in a recursion and count what they cost

  • Add a memo dict, or @cache, to a recursive function so each subproblem is solved once

  • Find a recurrence by asking how the last move of an answer was made

  • Read a finished memo as a table, and fill that table bottom-up with a loop

  • State the walk, notebook, promise and cost of a memoized recursion, and where it stops working

A staircase has 5 steps, and each stride climbs 1 or 2 of them. How many different climbs reach the top? Order matters, so [2, 1, 1, 1] and [1, 2, 1, 1] are two climbs.

Here they all are. Five strides of 1: [1, 1, 1, 1, 1]. One stride of 2 in any of four places: [2, 1, 1, 1], [1, 2, 1, 1], [1, 1, 2, 1], [1, 1, 1, 2]. Two strides of 2 and one of 1: [2, 2, 1], [2, 1, 2], [1, 2, 2]. That is 1 + 4 + 3 = 8. For 45 steps there are 1,836,311,903, so listing is out.

A recursive function counts them in four lines. It is right, and it is hopelessly slow. This lesson finds where its time goes and fixes it with one change: write each answer down the first time you work it out. That change is called memoization, and it is one of the two ways to do dynamic programming (DP): solving a problem from the answers to smaller versions of itself, when the same smaller versions come up again and again, so that each one is solved only once.

Where the time goes

We start with the simplest recursion that makes two calls, Fibonacci, from module 8. A reminder: the Fibonacci numbers start 0, 1, and each later one is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13. As code, fib(n) returns n when n <= 1 (the base cases, answered with no further calls), and fib(n - 1) + fib(n - 2) otherwise. The staircase count follows the same rule, as the climbing stairs section shows, so whatever slows down fib slows it down too.

The figure draws every call of fib(6) as a box, one level below the call that made it. Each call is two steps: one when it is made, one when it returns. The readouts count the calls made so far and the depth: how many calls are on the call stack, started and not yet finished. In module 8, fib(5) made 15 calls. Before you press Next, guess how many fib(6) makes.

The same questions are asked again and again. fib(6) needs only 7 different answers, fib(0) to fib(6), yet it makes 25 calls. A smaller version of the problem, like fib(3) inside fib(6), is called a subproblem. When the same subproblem shows up in more than one place in the call tree, we say the subproblems overlap, and that overlap is where the time goes.

Work it outCalls for fib(8)

With no memo, fib(6) makes 25 calls (the figure above) and fib(7) makes 41. How many calls does fib(8) make with no memo, counting the call of fib(8) itself? Type a whole number.

calls

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

The repeats grow much faster than n. Each step up in n multiplies the calls by about 1.6: fib(30) makes 2,692,537 calls and fib(40) makes 331,160,281. That is exponential time. Yet the stack never holds more than n calls, so this is a time problem, not a memory problem.

Write each answer down

How do we stop answering the same question twice? Keep a notebook of answers: a dict memo from k to fib(k). Each call looks in the notebook first. Only on a miss does it do the work, and it writes the answer down before returning it. That is memoization, the fix module 8 showed on fib(5). The name comes from "memo", a note written to remember something. This time, watch the code do it line by line.

The trace runs fib(6) with a memo. The memo is created inside fib, and the recursion lives in a helper f defined inside it. A reminder from module 8: a function defined inside another can read the outer function's names and add to the dict they point at. So every f call reads and writes the one memo, and every call of fib starts with an empty notebook (the cheapest climb section shows what goes wrong otherwise). Before you step through, guess: when f(4) is needed for the second time, how many lines run before it returns?

Step throughfib(6) with a memo
Step 1 of 52
Line 1 is about to run.
def fib(n):
memo = {}
def f(k):
if k <= 1:
return k
if k in memo:
return memo[k]
memo[k] = f(k - 1) + f(k - 2)
return memo[k]
return f(n)
Names
no names yet
Output
(nothing printed yet)

Each value from 2 to n is now computed once. Every later request for it is one dict lookup. The tree below shows the same run as boxes: the same fib(6) as the first figure, with the memo switched on. Guess first: how many calls now, against 25?

The cost rule for every memoized recursion: the number of different subproblems times the work each one does outside its smaller calls. Here that is n + 1 subproblems times O(1) work (one addition and two checks), so O(n). Every repeat costs one lookup, and each subproblem makes only two calls, so repeats add at most two lookups per subproblem.

A memo only pays off when the same subproblem comes back. Check that on a recursion from module 8.

Quick checkA memo for factorial

Module 8's factorial makes one call per level:

def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

You add a memo by the recipe: memo = {} inside an outer function, a check before computing, a store before returning. What does the memo change for one call of factorial(6)?

Choose one answer, then check.

Let Python keep the notebook

Python can keep the memo for you. cache, from the functools module (Python 3.9 and later), is a decorator: you write @cache on the line above a def, and it wraps the function in extra behavior. Here the extra behavior is a hidden dict keyed by the arguments. A call first looks its arguments up; on a hit the body never runs, and on a miss the body runs and its result is saved.

from functools import cache

def fib(n):
    @cache
    def f(k):
        if k <= 1:
            return k
        return f(k - 1) + f(k - 2)
    return f(n)

The promise and the cost are the same as the hand-written memo. Three details differ:

  • The cache saves base cases too, since it cannot tell them apart from other calls.
  • Every argument must be hashable, the rule for dict keys from module 3: numbers, strings and tuples of them are hashable, lists are not. Passing a list raises TypeError: unhashable type: 'list'. So keep the input list in the outer function, where the helper can read it, and give the helper only small values like k.
  • In this lab each level of a @cache function counts twice against the depth limit, so it reaches about 2,500 levels, not 5,000.

Older code writes @lru_cache(maxsize=None), which does the same thing. If you use @cache in an interview, say what it is: a dict from the arguments to the answer.

Here is the cache seen from the inside. The print runs only when the body runs.

PredictWhat the cache skips

The print sits inside the body, so it runs only when the cache misses. Type exactly what this prints.

from functools import cache

@cache
def fib(n):
    print("computing", n)
    if n <= 1:
        return n
    return fib(n - 1) + fib(n - 2)

print(fib(4))
print(fib(5))

Now assemble one. The tribonacci numbers start 0, 1, 1, and each later one is the sum of the three before it: 0, 1, 1, 2, 4, 7, 13, 24.

Put in orderTribonacci with a cache

Put the lines in order to build tribonacci(n). The sequence starts 0, 1, 1 (for n = 0, 1, 2), and each later number is the sum of the three before it. cache is already imported in every cell, as on LeetCode. Indentation is part of each line, and two lines do not belong.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • @cache
    • return 1
    • if k == 0:
    • def t(k):
    • if k <= 2:
    • return t(n)
    • def tribonacci(n):
    • @cache
    • return t(k - 1) + t(k - 2) + t(k - 3)
    • t(k - 1) + t(k - 2) + t(k - 3)
    • return 0

    So far: plain recursion repeats work when subproblems overlap, and the repeats grow exponentially. A memo dict, checked first and filled before returning, computes each subproblem once. The time becomes the number of subproblems times the work for each.

    Climbing stairs: the same rule

    Back to the staircase. Where does a rule like fib(n) = fib(n - 1) + fib(n - 2) come from in a new problem? A rule that gives the answer for n from the answers for smaller inputs is called a recurrence. To find one, look at the last move.

    Call the number of climbs of n steps ways(n). Every climb ends with a stride of 1 or a stride of 2. Here are the 5 climbs of 4 steps, sorted by their last stride:

    Last stride is 1 (a climb of 3, then 1)Last stride is 2 (a climb of 2, then 2)
    [1, 1, 1, 1][1, 1, 2]
    [1, 2, 1][2, 2]
    [2, 1, 1]

    Remove the last stride and the left column is every climb of 3 steps; the right column is every climb of 2 steps. No climb is in both columns, and none is missing. So ways(4) is ways(3) + ways(2) = 3 + 2 = 5, and in general ways(n) = ways(n - 1) + ways(n - 2).

    The rule reads two smaller answers, so it needs two base cases, or ways(1) would ask for ways(-1). ways(1) = 1: one stride of 1. ways(0) = 1: standing on the floor is one climb, the one with no strides. Check it on 2 steps. The climbs are [1, 1] and [2], and the rule gives ways(1) + ways(0) = 1 + 1 = 2. With ways(0) = 0 the rule would say 1.

    The counts for 0 to 6 steps are 1, 1, 2, 3, 5, 8, 13: the Fibonacci numbers, one place along, so ways(n) is fib(n + 1). Same rule, different base cases, so the same call tree with the same repeats. Writing it fast is the memo recipe above.

    easyDynamic programming, 1DRecursion target 15 min

    Climbing stairs

    A staircase has n steps. Each stride takes you up 1 step or 2 steps, and no stride may go past step n. A climb is the list of strides you take, in order, from the floor to step n. Order matters: [1, 2] and [2, 1] are two different climbs of 3 steps.

    Return the number of different climbs.

    Example 1
    Inputn = 4Output5

    The five climbs are [1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [2, 1, 1] and [2, 2].

    Example 2
    Inputn = 1Output1

    One stride of 1. A stride of 2 would go past the top.

    Example 3
    Inputn = 5Output8

    A climb of 5 ends with a 1 (from step 4, which 5 climbs reach) or a 2 (from step 3, which 3 climbs reach). 5 + 3 = 8.

    Constraints
    • 1 ≤ n ≤ 45

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    Debrief. The solution is the memoized fib with base cases that return 1. For n = 4 it makes 7 calls instead of 9, and for n = 30 it makes 59 instead of 2,692,537. The important step was not the code: it was finding the recurrence from the last stride. Asking how the last move was made is where most DP recurrences start.

    Now flip a constraint, the way a follow-up question would.

    Code itBroken steps

    Some steps of the staircase are broken, and you may not stand on them. Write climb_avoiding(n, broken), which returns the number of climbs from the floor to step n, with strides of 1 or 2 and order mattering, that never stand on a step in the set broken. The floor, step 0, is never broken. If step n itself is broken, the answer is 0.

    For n = 5 and broken = {3} the answer is 2: [1, 1, 2, 1] and [2, 2, 1]. Use a memo, then press Watch it run.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.

    The cheapest climb: min instead of plus

    A new staircase charges a toll on every stair you stand on, cost[i] for stair i. You start on the floor below stair 0 and finish on the landing above the last stair, and each stride goes up 1 or 2. What is the smallest total toll? For cost = [5, 2, 8, 1] it is 3: a stride of 2 onto stair 1 (toll 2), a stride of 2 onto stair 3 (toll 1), and a stride of 1 onto the landing. This is the second problem, and the recipe is the same: find the recurrence from the last move, then memoize.

    Name the positions first. The stairs are 0 to n − 1, where n is len(cost), and the landing is position n. Careful: stair 0 is the first stair, not the floor. Climbing stairs called the floor step 0; here cost is a Python list, so its first stair is index 0 and the floor sits one below it.

    Let reach(i) be the least toll paid on the way to position i, counting the stairs you stood on below i but not stair i itself. The last stride into i came from stair i - 1, which charged cost[i - 1], or from stair i - 2, which charged cost[i - 2]. We want the cheaper of the two:

    reach(i) = min(reach(i - 1) + cost[i - 1], reach(i - 2) + cost[i - 2])

    The base cases are reach(0) = reach(1) = 0, because one stride from the free floor lands on stair 0 or stair 1. The answer is reach(n), since the landing charges nothing.

    Same call tree as climbing stairs, a different combine step. Counting climbs adds the two ways in, because every climb uses one or the other. The cheapest climb keeps the smaller, because we want one climb, the best one. The tree has the same repeats, so the same memo fixes it. Fill a small table by hand before you code it.

    On paperFill reach by hand

    On paper, fill in reach(i) for cost = [6, 1, 1, 8, 2], from i = 0 up to the landing. Use reach(i) = min(reach(i - 1) + cost[i - 1], reach(i - 2) + cost[i - 2]) with reach(0) = reach(1) = 0. Then read back which stairs the cheapest climb stands on.

    Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.

    reach(5)

    Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

    easyDynamic programming, 1DRecursion target 15 min

    Cheapest climb

    A staircase has len(cost) stairs, numbered from 0 at the bottom. You start on the floor, directly below stair 0, and finish on the landing, directly above the last stair. Each stride moves you up 1 or 2 positions. So your first stride lands on stair 0 or stair 1, and you can step onto the landing from either of the last two stairs.

    Every stair you stand on charges a toll: cost[i] for stair i. The floor and the landing are free. Return the smallest total toll of any climb from the floor to the landing.

    Example 1
    Inputcost = [5, 2, 8, 1]Output3

    Stride 2 onto stair 1 (toll 2), stride 2 onto stair 3 (toll 1), stride 1 onto the landing. 2 + 1 = 3.

    Example 2
    Inputcost = [4, 4, 4]Output4

    Stride 2 onto stair 1, then stride 2 onto the landing. Only one stair is paid for.

    Example 3
    Inputcost = [3, 9, 2, 7, 1]Output6

    Stand on stairs 0, 2 and 4: 3 + 2 + 1 = 6. The 9 and the 7 are both stepped over.

    Constraints
    • 2 ≤ len(cost) ≤ 500

    • 0 ≤ cost[i] ≤ 999

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    Debrief. The memoized reach is the climbing stairs helper with min in place of +. One edge case catches people: the answer is reach(len(cost)), not the cost of reaching the last stair. For [1, 1, 50], stepping from stair 1 straight to the landing costs 1, while the cheapest climb that stands on the last stair costs 51. To list the stairs themselves, read the choices back from the landing, as in the paper exercise.

    One more trap, and it is the reason the memo lives inside the function. Predict what this version prints.

    PredictTwo staircases, one notebook

    This cheapest-climb code keeps its memo outside the function. Type exactly what the two print lines show.

    memo = {}
    
    def reach(cost, i):
        if i <= 1:
            return 0
        if i in memo:
            return memo[i]
        from_one_below = reach(cost, i - 1) + cost[i - 1]
        from_two_below = reach(cost, i - 2) + cost[i - 2]
        memo[i] = min(from_one_below, from_two_below)
        return memo[i]
    
    print(reach([5, 2, 8, 1], 4))
    print(reach([9, 9, 9, 9], 4))
    

    The memo is a table

    Back to climbing stairs. When the solution's ways(5) finishes, its memo is {2: 2, 3: 3, 4: 5, 5: 8}. The keys arrived in order 2, 3, 4, 5, and each value was computed from the two before it. So the memo is a table indexed by k that fills from left to right.

    The figure fills that table directly. It starts with the two base cases already written in, and each press of Next cell fills one more cell from the two to its left. No recursion, no call stack. The cell being filled is blue, and the cells it reads are outlined amber.

    There are two ways to fill the same table. Top-down is memoization: start from the big question, recurse, and store answers on the way back up. Bottom-up, also called tabulation, starts from the base cases and loops upward, so each cell's inputs are ready before it is filled:

    def climb_stairs(n):
        dp = [1] * (n + 1)              # dp[k] = ways(k); dp[0] and dp[1] are already right
        for k in range(2, n + 1):
            dp[k] = dp[k - 1] + dp[k - 2]
        return dp[n]

    Both compute the same n − 1 cells in O(n) time. Bottom-up has no recursion, so it has no depth limit. Top-down goes about n calls deep: plain Python stops at about 1,000 nested calls by default (this lab allows 5,000), so a memoized climb_stairs(100_000) fails where the loop does not. Top-down has its own strength: you write the recursion you already reasoned about, and the memo adds only a few lines.

    The next lesson builds every table this way and shrinks this one to two variables.

    Last, say it out loud. The words you write here are the words you will use in the room.

    Say itSay the plan before you type

    The interviewer gives you the cheapest climb. Before typing, say your plan out loud: the brute force and its cost, why it is slow, the fix and its promise, the cost of the fix, and what you would do if the staircase had a million stairs.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: One-dimensional DP