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

Lesson 2 of 5

One-dimensional DP

Write the answers to smaller questions in a list, smallest first, and build each new answer from the ones before it. One recipe (state, transition, base cases, answer, order) solves house robber, coin change and decode ways.

About 1 hour 55 minutes, with the 3 problems worked in it
By the end you can
  • Say what dp[i] means in one sentence before writing any code

  • Find the transition by looking at the last choice, and pick the base cases, the answer cell and the order

  • Fill a one-dimensional table bottom-up with a loop

  • Replace the table with two names when each cell reads only the two cells before it

  • Use the same recipe for a best total (max), a fewest count (min) and a number of ways (+)

A street has five houses, and the cash inside them is money = [2, 8, 1, 4, 9]. You may take from any houses you like, but never from two that stand next to each other. What is the most you can collect? Try it before reading on.

The tempting rule is every other house: 2 + 1 + 9 = 12, or 8 + 4 = 12. The best plan is 8 + 9 = 17, and it skips two houses in a row. A rule picks one plan and hopes. To be sure, we have to compare plans, and there are a lot of them: 13 allowed plans for 5 houses (counting the plan that takes nothing), 2,178,309 for 30 houses.

The last lesson made a slow recursion fast with a memo (a dict of answers already worked out). Then it wrote the same climbing stairs answers into a list, smallest first, with a plain loop. This lesson makes that loop the main tool, with one recipe that fills the list for three classic interview problems.

Five questions before any code

How do we compare every plan without listing them? Look at the last house. Every plan either robs it or skips it.

  • Skip the 9, and what is left is the same puzzle on the first four houses, [2, 8, 1, 4].
  • Rob the 9, and its neighbor, the 4, must stay untouched. What is left is the same puzzle on the first three houses, [2, 8, 1], plus the 9.

So the answer for five houses comes from the answers for four houses and for three. Those come from three and two, and so on down to no houses at all. As plain recursion this repeats work: rob the 9 asks for the first three houses directly, and skip the 9 asks for four houses, whose own rob branch asks for the first three again. The same smaller streets come up again and again, as fib(3) did inside fib(6).

A reminder from the last lesson: a smaller version of the same question is a subproblem, and dynamic programming (DP) solves each subproblem once and builds bigger answers from smaller ones. Here each answer goes in one cell of a table.

Five questions turn a problem into a table. Together they are the DP recipe. Answer them in words before you write code:

  1. State: what does one cell mean? dp[i] is the most cash from the first i houses, money[0] to money[i - 1]. If you cannot say the state in one sentence, you are not ready to code.
  2. Transition: how does a cell use smaller cells? (The last lesson called this rule the recurrence.) The newest of the first i houses is money[i - 1]. Skip it, and the best is dp[i - 1]. Rob it, and its left neighbor stays untouched, so the best is dp[i - 2] + money[i - 1]. So dp[i] = max(dp[i - 1], dp[i - 2] + money[i - 1]).
  3. Base cases: which cells are known without the rule? dp[0] = 0 (no houses, no cash) and dp[1] = money[0] (one house: rob it, since cash is never negative).
  4. Answer: which cell holds it? dp[n], where n = len(money).
  5. Order: which cells must be ready first? Each cell reads the two cells to its left, so fill from left to right.

Why "the first i houses" and not "house i"? The shift by one gives dp[0] a meaning, no houses at all, and that makes a clean base case. The price is one thing to keep in your head: the newest house in dp[i] is money[i - 1], not money[i].

The figure fills this table for the street above, one cell per step. The blue cell is being filled, amber arrows point from the cells it reads, and the formula under the table shows the real numbers. The figure calls the list values and counts houses from 1, the way dp counts them, so its "house 2" is values[1], the 8. Before you press Next cell, guess dp[3], the best from the first three houses, [2, 8, 1].

A cell is final the moment it is filled. dp[3] = 8 is the best for [2, 8, 1] whatever comes later, so later cells read it without checking it again. That is the promise the table keeps.

Every other answer is built on the state sentence, so check that you can read it.

Quick checkWhat one cell means

For money = [2, 8, 1, 4, 9], the table above has dp[3] = 8. Which sentence says what dp[3] means?

Choose one answer, then check.

The table as a loop

How does the recipe become code? Each of the five answers becomes a line or two: the state is a list, the base cases are assignments, the order is the range, the transition is the loop body, and the answer is the return.

Before you watch the code run, fill a small table yourself.

Work it outFill a table by hand

Fill the house robber table by hand for money = [3, 1, 4, 2]. Start with dp[0] = 0 and dp[1] = 3, then use dp[i] = max(dp[i - 1], dp[i - 2] + money[i - 1]) for i = 2, 3 and 4. What is dp[4]?

dp[4]

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

The trace runs on that street, [3, 1, 4, 2]. The arrow i under dp marks the cell being filled. Check each cell against your table.

Step throughFilling the house robber table
Step 1 of 20
Line 1 is about to run.
def rob(money):
n = len(money)
dp = [0] * (n + 1)
dp[1] = money[0]
for i in range(2, n + 1):
skip = dp[i - 1]
take = dp[i - 2] + money[i - 1]
dp[i] = max(skip, take)
return dp[n]
Names
no names yet
Output
(nothing printed yet)

This is the bottom-up order from the last lesson: start from the base cases and fill upward with a loop. A memo works top-down: it starts at the big question and recursion reaches down to the base cases. Both compute the same cells, once each. But the loop has no recursion, so no depth limit: a memoized recursion goes one call deeper per house, and on a long street that passes plain Python's default limit of about 1,000 nested calls.

Now write it. The trace above is its heart; the problem adds the edge cases.

mediumDynamic programming, 1D target 25 min

House robber

A thief plans one night on a street of houses in a row. money[i] is the cash in house i. Robbing two houses that stand next to each other sets off an alarm, so the thief never robs two neighbors. Skipping several houses in a row is fine.

Return the most cash the thief can collect.

Example 1
Inputmoney = [3, 10, 3, 1, 2]Output12

Rob houses 1 and 4: 10 + 2 = 12. Robbing every other house gives only 3 + 3 + 2 = 8 or 10 + 1 = 11.

Example 2
Inputmoney = [5, 1, 1, 5]Output10

Rob the first and the last house, skipping the two in the middle.

Example 3
Inputmoney = [6, 7, 6]Output12

Robbing the richest house first takes the 7 and blocks both 6s. The two 6s together are worth more.

Constraints
  • 1 ≤ len(money) ≤ 100

  • 0 ≤ money[i] ≤ 500

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.

One house is the edge case to check. range(2, 2) is empty, so the loop never runs and dp[1] comes back. If you set dp[2] as a third base case, one house raises an IndexError, because the table has only two cells. Example 3 shows the other tempting rule failing: richest house first takes the 7 in [6, 7, 6] and loses both 6s.

Keeping only the last two values

Does the loop need the whole table? dp[i] reads only dp[i - 1] and dp[i - 2]. Once dp[i] is filled, dp[i - 2] is never read again. So two names are enough: one_back holds the cell one to the left, and two_back the cell two to the left. Each house moves the pair one cell to the right.

The trace runs on the same street. Before you step through, write the pair after each house; each pair should be two neighboring cells of [0, 3, 3, 7, 7].

Step throughTwo names instead of a table
Step 1 of 14
Line 1 is about to run.
def rob(money):
two_back, one_back = 0, 0
for cash in money:
two_back, one_back = one_back, max(one_back, two_back + cash)
return one_back
Names
no names yet
Output
(nothing printed yet)

Update both names in one line. Python works out the whole right side, using the old values, before it changes either name. Split the update into two lines and the second line reads the new two_back. Predict what that does.

PredictOne name at a time

This version updates the two names on separate lines. Type exactly what it prints.

def rob(money):
    two_back, one_back = 0, 0
    for cash in money:
        two_back = one_back
        one_back = max(one_back, two_back + cash)
    return one_back

print(rob([3, 1, 4, 2]))

The saving is space, not time: still O(n) time, now O(1) extra space. This is the shape of a streaming job with a little state: each record is read once, and two numbers survive between records.

The price is the plan. To say which houses to rob, walk the full table back from the end. In [0, 3, 3, 7, 7], dp[4] equals dp[3], so skipping the last house, the 2, loses nothing: skip it. dp[3] = 7 is more than dp[2] = 3, so the 4 was robbed. Its neighbor, the 1, stays untouched, and the walk jumps two cells to dp[1]. dp[1] = 3 is more than dp[0] = 0, so the 3 was robbed. With only two numbers left, that walk is impossible. If the interviewer asks for the plan, keep the table.

The same trick works for any cell that reads the two cells before it. Rebuild climbing stairs with two names.

Put in orderClimbing stairs with two names

Climbing stairs: ways(i), the number of ways to reach stair i taking 1 or 2 stairs at a time, is ways(i - 1) + ways(i - 2), with ways(0) = ways(1) = 1. Put the lines in order to build climb(n) with two names instead of a table. Indentation is already part of each line. Three lines do not belong.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • return two_back
    • return one_back
    • two_back, one_back = one_back, one_back + two_back
    • for i in range(2, n + 1):
    • two_back = one_back
    • two_back, one_back = 1, 1
    • def climb(n):
    • one_back = one_back + two_back

    So far: the recipe is state, transition, base cases, answer and order. The loop fills the table from the base cases upward, and when a cell reads only its two left neighbors, two names replace the table.

    More than two choices: coin change

    What if the last step has more than two options? Pay an amount with the fewest coins, using as many coins of each value as you like. With coins [1, 3, 4] and amount 6, the tempting rule is biggest coin first: 4, then 1, then 1, which is three coins. But 3 + 3 is two coins. A rule like this is greedy, module 6's word for taking what looks best right now and never taking it back. Like the every-other-house rule on the street, it commits too early, so compare.

    Look at the last coin. The best mix for 6 ends with a 1, a 3 or a 4. Whichever it is, the coins before it pay the rest (5, 3 or 2), and they should be as few as possible. So the answer for 6 is one more than the smallest of the answers for 5, 3 and 2. The recipe:

    1. State: dp[a] is the fewest coins that add up to a, or infinity when no mix does.
    2. Transition: dp[a] = min(dp[a - c] + 1) over every coin c with c <= a.
    3. Base case: dp[0] = 0. Every other cell starts at infinity.
    4. Answer: dp[amount], with infinity turned into -1.
    5. Order: each cell reads smaller amounts, so fill from 1 upward.

    Infinity marks an amount no mix can make. In Python it is float("inf"), a value bigger than every number. inf + 1 is still inf, so an impossible leftover never wins a min.

    The figure fills the table for coins [1, 3, 4] and amount 6. Now a cell can read three cells, one per coin that fits. Before you press Next cell, guess dp[5], the fewest coins for 5.

    In code, the transition is a loop over the coins inside the loop over amounts. The trace uses coins [2, 3] and amount 4, where one amount cannot be made. Before you step through, find it.

    Step throughFewest coins, amount by amount
    Step 1 of 37
    Line 1 is about to run.
    def coin_change(coins, amount):
    inf = float("inf")
    dp = [0] + [inf] * amount
    for a in range(1, amount + 1):
    for coin in coins:
    if coin <= a:
    dp[a] = min(dp[a], dp[a - coin] + 1)
    if dp[amount] == inf:
    return -1
    return dp[amount]
    Names
    no names yet
    Output
    (nothing printed yet)

    Why start at infinity? Each cell is a minimum, so its starting value must lose to every real count. Here is what happens with a start that wins instead.

    Quick checkWhere should each cell start?

    This version starts every cell at 0 instead of infinity:

    def coin_change(coins, amount):
        dp = [0] * (amount + 1)
        for a in range(1, amount + 1):
            for coin in coins:
                if coin <= a:
                    dp[a] = min(dp[a], dp[a - coin] + 1)
        if dp[amount] == float("inf"):
            return -1
        return dp[amount]

    What does coin_change([2], 3) return?

    Choose one answer, then check.

    Now write it. The problem's tests include the greedy trap and a coin of a billion.

    mediumDynamic programming, 1D target 25 min

    Fewest coins

    You have as many coins as you like of each value in coins, and you need to pay exactly amount. Find the smallest number of coins whose values add up to amount and return that number. When no mix of coins adds up to amount exactly, return -1. Paying 0 takes no coins, so an amount of 0 gives 0.

    Example 1
    Inputcoins = [1, 4, 5], amount = 8Output2

    4 + 4. Taking the biggest coin first gives 5 + 1 + 1 + 1, which is 4 coins.

    Example 2
    Inputcoins = [3, 7], amount = 5Output-1

    One 3 leaves 2, which no coin pays, and two 3s or one 7 are already more than 5.

    Example 3
    Inputcoins = [2, 5], amount = 11Output4

    5 + 2 + 2 + 2. Two 5s make 10, and no coin pays the last 1.

    Constraints
    • 1 ≤ len(coins) ≤ 12

    • 1 ≤ coins[i] ≤ 109, and no value appears twice

    • 0 ≤ amount ≤ 104

    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.

    Coin change cannot shrink to two names: dp[a] reads as far back as the biggest coin. Here the loop also avoids a deep recursion. For amount 10,000 with coins [2, 5, 9], a memoized recursion that tries the 2 first goes about 5,000 calls deep, far past plain Python's default of about 1,000.

    The same recipe works whenever the last step is one of several pieces. Here the pieces are perfect squares.

    Code itThe fewest perfect squares

    A perfect square is a whole number times itself: 1, 4, 9, 16, and so on. Write fewest_squares(n), which returns the fewest perfect squares that add up to n (a square may repeat). For 12 that is 3 (4 + 4 + 4); taking the biggest square first gives 9 + 1 + 1 + 1, which is 4. Use the coin change recipe, with the squares up to n as the coins. 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.

    Counting instead of choosing: decode ways

    What if the question is how many ways, not what is best? A message of capital letters is turned into digits, A as 1 up to Z as 26, written with no gaps. So "BAD" (2, 1, 4) becomes "214", and so do "UD" (21, 4) and "BN" (2, 14). Given the digits, how many messages turn into them? For "214" the answer is 3.

    Look at the last code. It is either the last digit alone (1 to 9, since a lone 0 is not a code) or the last two digits together (10 to 26). No message is in both groups, and every message is in one, so count each group and add the counts. For "214", BAD and UD end with the code 4, and BN ends with the code 14: 2 + 1 = 3.

    1. State: dp[i] is the number of ways to decode the first i digits, s[:i]. A start of the string like this is called a prefix.
    2. Transition: dp[i] is dp[i - 1] when s[i - 1] is not "0", plus dp[i - 2] when s[i - 2:i] is a number from 10 to 26.
    3. Base case: dp[0] = 1. The empty prefix decodes one way, to the empty message. It is the 1 that every first code builds on.
    4. Answer: dp[n].
    5. Order: each cell reads the two cells to its left, so fill from left to right.

    Counting adds where choosing took a max. Before you step through, list every message for "2610" yourself; the trace should end on your count.

    Step throughCounting the messages for "2610"
    Step 1 of 25
    Line 1 is about to run.
    def num_decodings(s):
    n = len(s)
    dp = [0] * (n + 1)
    dp[0] = 1
    for i in range(1, n + 1):
    if s[i - 1] != "0":
    dp[i] += dp[i - 1]
    if i >= 2 and 10 <= int(s[i - 2:i]) <= 26:
    dp[i] += dp[i - 2]
    return dp[n]
    Names
    no names yet
    Output
    (nothing printed yet)

    Why dp[0] = 1 and not 0? With dp[0] = 0, the first digit adds 0 to dp[1], and every later cell is built from zeros: the function returns 0 for every string. One way to decode nothing is what each first code extends.

    Fill a table on paper before you write the code.

    On paperDecode a year

    On paper, fill the decode ways table for s = "2025", from dp[0] = 1 up to dp[4]. For each cell, ask both questions: is the newest digit a code on its own (1 to 9), and are the last two digits one code (10 to 26)? Then list the messages.

    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.

    dp[4]

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

    mediumDynamic programming, 1D target 25 min

    Ways to decode

    A message of capital letters was turned into digits, with A as 1, B as 2, and so on up to Z as 26, and the codes were written one after another with no gaps. So "LAB" becomes "1212", and so does "ABAB".

    You get the digit string s. Count the letter messages that turn into exactly s and return that count. Every code is a number from 1 to 26 written without a leading zero: "8" is H, but "08" is not a code, and neither is "0" on its own. If no message fits, return 0.

    Example 1
    Inputs = "123"Output3

    ABC (1, 2, 3), LC (12, 3) and AW (1, 23).

    Example 2
    Inputs = "2101"Output1

    Only BJA (2, 10, 1). The 0 must join the 1 before it, which leaves the 2 alone, and "01" is not a code.

    Example 3
    Inputs = "50"Output0

    The 0 cannot stand alone, and 50 is bigger than 26.

    Constraints
    • 1 ≤ len(s) ≤ 100

    • s holds only the digits 0 to 9, and it may start with 0.

    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.

    Every 0 must be the second digit of 10 or 20. A 0 can never stand alone, and a pair that starts with 0, such as "01", is the number 1, below 10. So "50" decodes to nothing, and a string that starts with 0 has dp[1] = 0 and never recovers.

    Here are the three problems side by side. Same recipe, three ways to combine: max for a best total, min for a fewest count, + for a number of ways.

    ProblemStateTransitionBase casesCombine
    House robberdp[i]: most cash from the first i housesskip dp[i - 1], or take dp[i - 2] + money[i - 1]dp[0] = 0, dp[1] = money[0]max
    Coin changedp[a]: fewest coins that add up to adp[a - c] + 1 for every coin c <= adp[0] = 0, the rest infinitymin
    Decode waysdp[i]: ways to decode the first i digitsdp[i - 1] if one digit is a code, dp[i - 2] if two digits aredp[0] = 1+

    This module's practice bank has three more problems built on the same recipe. Houses in a circle (LeetCode 213) runs house robber twice. Word break (LeetCode 139) tries each word as the last piece the way coin change tries each coin. Jobs for the most profit (LeetCode 1235), a hard one, is house robber's take or skip on jobs sorted by end time, plus a binary search (module 6) to find the jobs that fit before each one. Practice saying the recipe for word break.

    Say itSay the recipe for word break

    Word break: you get a string s and a list of dictionary words, and you must say whether s can be cut into pieces that are all words (a word may repeat). Before typing, say the recipe out loud: the state, the transition, the base case, the answer and the order, then the cost. Use n for the length of s, w for the number of words and L for the length of the longest word.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: Grids and two strings