Python 3D Academyবাংলা

Designing a DP: the state, the choice, the base case

🌍 In real life. A temple on a hill has a toll on each step: pay a step's toll and you may climb 1 or 2 steps from it. You may begin on the first or the second step for free. With tolls 10, 15 and 20, how little can you pay to reach the top, just past the last step?

The idea in one sentence: most of the work in DP is choosing what one cell means; say it in one sentence ("dp[i] is the least it costs to stand on step i"), and the recurrence, the base cases and the answer cell follow from that sentence.

Its words:

  • the meaning of a cell: one sentence that says what dp[i] holds; write it as a comment
  • the answer cell: the state that is the whole question; here the top, step n, one past the last toll
  • counting DP: adding the ways of the options (Lessons 57.1, 57.2); optimising DP: taking the min or max of them (Lesson 57.3 and here)

The toll steps, step by step:

  1. meaning: dp[i] is the least it costs to stand on step i
  2. you reach step i from step i − 1 (paying its toll) or from step i − 2 (paying that toll)
  3. dp[i] = min(dp[i − 1] + cost[i − 1], dp[i − 2] + cost[i − 2])
  4. bases: dp[0] = dp[1] = 0, the free starts; the answer is dp[n]

Start on step 1, pay 15, and jump straight to the top:

When a state can't be reached. Some cells have no answer at all. With only 4 and 5 taka coins, 1, 2, 3, 6 and 7 can't be made. The table marks them ∞, and an ∞ cell passes nothing useful on: 7 = 3 + 4 = 2 + 5, and both 3 and 2 are ∞, so 7 is ∞ too, and the answer is −1:

Reading a code. A secret message turns letters into numbers, A = 1 up to Z = 26, and runs them together: "226" could be BZ (2, 26), VF (22, 6) or BBF (2, 2, 6). Let dp[i] be the number of ways to read the first i digits. The last letter is either the last digit alone (if it isn't 0) or the last two digits (if they make 10 to 26), so dp[i] adds dp[i − 1] and dp[i − 2] when each is allowed, with dp[0] = 1 for the empty start. A 0 can't stand alone, so "06" has no reading at all.

What it costs, by counting. All three fill one cell per state with a fixed number of lookups: O(n) for n steps or digits, and O(amount × k) for coins. A code of 1,000 digits takes about 2,000 lookups, though it can have more readings than there are atoms on Earth.

def min_cost_stairs(cost):
    n = len(cost)
    dp = [0] * (n + 1)                         # dp[i]: least cost to stand on step i
    for i in range(2, n + 1):                  # steps 0 and 1 are free starts
        dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2])
    return dp[n]                               # step n is the top

def num_decodings(s):
    dp = [1] + [0] * len(s)                    # dp[i]: ways to read the first i digits
    for i in range(1, len(s) + 1):
        if s[i - 1] != "0":                    # the last digit alone is a letter (1-9)
            dp[i] += dp[i - 1]
        if i >= 2 and 10 <= int(s[i - 2:i]) <= 26:   # the last two digits are a letter
            dp[i] += dp[i - 2]
    return dp[len(s)]

print(min_cost_stairs([10, 15, 20]))
print(num_decodings("226"), num_decodings("06"))

Mistakes and edge cases.

  • the wrong answer cell: the top is step n, past the last toll; returning dp[n − 1] stops one step short
  • paying the wrong toll: you pay the toll of the step you leave, so arriving from i − 1 adds cost[i − 1]
  • zeros in a code: "10" is one reading (J), "06" none; int("06") is 6, so the range check 10 <= ... <= 26 is what rules out a leading 0
  • a vague cell meaning: if you can't say what dp[i] holds in one sentence, the recurrence will be wrong; fix the sentence first

Quiz

  1. What does this print?

    def min_cost_stairs(cost):
        n = len(cost)
        dp = [0] * (n + 1)                         # dp[i]: least cost to stand on step i
        for i in range(2, n + 1):                  # steps 0 and 1 are free starts
            dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2])
        return dp[n]                               # step n is the top
    
    print(min_cost_stairs([1, 100, 1, 1, 1, 100, 1, 1, 100, 1]))
  2. What does this print?

    def num_decodings(s):
        dp = [1] + [0] * len(s)                    # dp[i]: ways to read the first i digits
        for i in range(1, len(s) + 1):
            if s[i - 1] != "0":                    # the last digit alone is a letter (1-9)
                dp[i] += dp[i - 1]
            if i >= 2 and 10 <= int(s[i - 2:i]) <= 26:   # the last two digits are a letter
                dp[i] += dp[i - 2]
        return dp[len(s)]
    
    print(num_decodings("11106"))
  3. What should you write first when designing a DP?

    • One sentence saying what dp[i] means
    • The loop
    • The return line
  4. With coins 4 and 5, which amount from 1 to 10 can't be made?

    • 7
    • 8
    • 9
  5. min_cost_stairs([10, 15, 20]) gives 10 instead of 15. Which line is wrong?

    def min_cost_stairs(cost):
        n = len(cost)
        dp = [0] * (n + 1)
        for i in range(2, n + 1):
            dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2])
        return dp[n - 1]

Coding tasks

  1. Write min_cost_stairs(cost): cost[i] is the toll on step i; pay it to climb 1 or 2 steps from there. You may start on step 0 or step 1 for free. Return the least total to reach the top, the step just past the last one.

  2. Write num_decodings(s): s is a string of digits made by writing A = 1, B = 2, …, Z = 26 with no spaces. Return how many ways it can be read back as letters. A letter is never written with a leading 0, so "06" can't be read.