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

Lesson 5 of 5

How to find the state

When a problem does not come with its table, write the slow recursion that tries every choice. Whatever changes between its calls is the state. Memoize it, fill it as a table, keep only the rows you need, and walk the table back to recover the choices.

About 1 hour 50 minutes, with the 2 problems worked in it
By the end you can
  • Write a brute-force recursion that makes one choice and returns the best answer for the rest

  • Find the state by asking what the remaining choices need to know, and count the states to get the cost

  • Turn the recursion into a memo, then into a table filled so that every cell's inputs are ready

  • Shrink a table to the rows it still reads, and walk a full table back to recover the choices

  • Recognize interval DP, where the state is a stretch named by its two ends

Every dynamic programming (DP) solution rests on one sentence, such as house robber's "dp[i] is the most cash from the first i houses". That sentence answers the first of the five questions from the one-dimensional lesson, the state. With the state in hand, the other four answers (transition, base cases, answer, order) follow from it.

In the round, nobody gives you the sentence. You get an unseen problem and a blank editor. The state is the few facts that pin down one smaller question, and they become the key of the memo and the address of a cell in the table. Finding the state is the hard part of DP, and it does not take a flash of insight. It falls out of code you can always write: a slow recursion that tries every choice. This lesson turns that into five steps and runs them on a new problem from a blank page.

Five steps, and a problem to try them on

Here are the five steps. Steps 1 and 2 find the state, and step 3 makes the code fast. Steps 4 and 5 answer common follow-ups.

  1. Brute force with choices. Write a recursive function that makes one choice, calls itself on what is left, and returns the best answer for the rest.
  2. Find the state. List the arguments that change from call to call. They are the state. Count how many different values they can take.
  3. Memoize. Store each answer in a dict keyed by the state, so each state is solved once.
  4. Tabulate. Make a table with one cell per state, and fill it in an order where each cell's inputs are already filled.
  5. Shrink. Keep only the part of the table that later cells still read.

The new problem: a row of houses, three colors, and no two neighbors alike. Number the colors 0 (red), 1 (green) and 2 (blue). costs[i][color] is the price of painting house i that color. Paint every house so that neighboring houses get different colors, for the least total. LeetCode has it as Paint House (256). Here are three houses:

Housered (0)green (1)blue (2)
0216
1519
2852

In code that is costs = [[2, 1, 6], [5, 1, 9], [8, 5, 2]]. Taking the cheapest color for each house in turn does not work. House 0's cheapest is green (1). That pushes house 1 off its own cheap green, to red (5), and then house 2 takes blue (2): a total of 8. Before you read on, find a cheaper plan by hand.

Work it outPaint three houses by hand

Find the least total cost to paint the three houses so that neighbors get different colors.

Housered (0)green (1)blue (2)
0216
1519
2852

There are only 3 × 2 × 2 = 12 valid plans, so you can check them all, but try to guess which ones are worth checking first.

least total cost

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

Step 1: try every choice, return the rest

Make one choice per call, and let the call answer for everything after it. We paint left to right, one house per call. Write the function's promise in words first; it is what you trust when you read the code:

That promise splits into the two parts of every recursion. The base case: the last house has nothing after it, so its answer is its own price. The choice: any other house pays its own price, plus the cheaper of two ways to paint the rest, one per color the next house may take. The list unlike holds those two colors: unlike[0] is (1, 2), because a red house may be followed by green or blue. The whole row costs the smallest of cheapest(0, 0), cheapest(0, 1) and cheapest(0, 2).

On the right, under the Names box, each cheapest( ) box is one call, and the innermost is the one running. Before you step through, guess: how many times does cheapest(1, 2) run?

Step throughEvery choice, every call
Step 1 of 86
Line 1 is about to run.
costs = [[2, 1, 6], [5, 1, 9], [8, 5, 2]]
unlike = [(1, 2), (0, 2), (0, 1)]
def cheapest(i, color):
"""Least cost to paint houses i to the end, when house i gets color."""
if i == len(costs) - 1:
return costs[i][color]
a, b = unlike[color]
rest = min(cheapest(i + 1, a), cheapest(i + 1, b))
return costs[i][color] + rest
print(min(cheapest(0, 0), cheapest(0, 1), cheapest(0, 2)))
Names
no names yet
Output
(nothing printed yet)

The call tree doubles at every house. Three calls start at house 0, each makes 2 calls for house 1, and each of those makes 2 for house 2: 3 + 6 + 12 = 21 calls for three houses. Count one more house yourself.

Work it outOne more house

The brute force made 21 calls for 3 houses. How many calls does it make for 4 houses, still starting with cheapest(0, 0), cheapest(0, 1) and cheapest(0, 2)?

calls

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

Steps 2 and 3: name the state, then remember it

The state is whatever changes between calls. In the trace, costs and unlike never change; only i and color do. So the state is the pair (i, color). Two calls with the same pair do the same work and return the same answer: cheapest(1, 2) returned 14 both times.

Count the states: there are 3n of them. i takes n values and color takes 3: 9 states for three houses, 60 for twenty. Twenty houses make 3 × (220 − 1) = 3,145,725 calls but ask only 60 different questions. Every call after the first for a state repeats work already done, and a memo answers each repeat at once, with no calls below it.

Here is a test for any candidate state: the state is what the rest of the problem needs to know about the choices already made. To paint houses i onward, you need to know where you are and the color house i got, because house i + 1 must differ from it. The colors of earlier houses do not matter, and neither does the money already spent.

Try the test on a problem you have not seen.

Quick checkThe state for a jumping frog

A frog crosses a river on stones at known positions, always jumping forward from stone to stone. If its last jump was k units long, its next jump must be k − 1, k or k + 1 units. You write a recursion that answers "can the frog reach the last stone from here?"

Which arguments make the best state for that recursion?

Choose one answer, then check.

Step 3 changes only a few lines of the brute force. Before doing any work, look the state up in a dict. After working out an answer, store it under its state, then return it. Before you step, guess how many entries the memo holds at the end.

Step throughThe same recursion with a memo
Step 1 of 78
Line 1 is about to run.
costs = [[2, 1, 6], [5, 1, 9], [8, 5, 2]]
unlike = [(1, 2), (0, 2), (0, 1)]
memo = {}
def cheapest(i, color):
if i == len(costs) - 1:
return costs[i][color]
if (i, color) in memo:
return memo[(i, color)]
a, b = unlike[color]
rest = min(cheapest(i + 1, a), cheapest(i + 1, b))
memo[(i, color)] = costs[i][color] + rest
return memo[(i, color)]
print(min(cheapest(0, 0), cheapest(0, 1), cheapest(0, 2)))
Names
no names yet
Output
(nothing printed yet)

Same answer, fewer calls: 15 instead of 21, and the gap grows fast. With the memo, n houses take 6n − 3 calls: 57 for ten houses, against 3,069. The cost is the number of states times the work per state: 3n states with O(1) work each, so O(n) time and O(n) memo entries. Python's @cache from functools, on the line above the def, keeps the same dict for you.

One limit remains: the calls nest n deep. Plain Python stops at about 1,000 nested calls by default (this lab allows 5,000), so a memo on 100,000 houses fails where a table works.

Now run steps 1 to 3 yourself, on a problem where the index alone is not enough.

Code itStairs with no two 2-steps in a row

A staircase has n steps. You climb it with 1-steps and 2-steps, but never two 2-steps in a row. Write knee_climbs(n), the number of different ways to reach the top.

For n = 4 there are 4 ways: 1+1+1+1, 1+1+2, 1+2+1 and 2+1+1. The climb 2+2 is not allowed.

Use the lesson's steps 1 to 3: a recursion that tries each allowed 1-step or 2-step, then the state, then a memo. The last test uses n = 60, far too large for the brute force.

⌘+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.

So far: the brute force makes one choice and returns the best for the rest, the arguments that change are the state, and a memo solves each state once. Steps 4 and 5 change how answers are stored, not what they are.

Steps 4 and 5: a table, then one row

A table is the memo laid out as a grid: one row per house, one column per color, and best[i][color] holds what cheapest(i, color) returns. Without recursion we pick the order ourselves, and the rule is that a cell is filled only after the cells it reads. Each cell reads two cells in the row below, so the bottom row goes first, then each row above it.

Before you step through, predict the bottom row. It reads nothing.

Step throughOne cell per state, bottom row first
Step 1 of 33
Line 1 is about to run.
costs = [[2, 1, 6], [5, 1, 9], [8, 5, 2]]
unlike = [(1, 2), (0, 2), (0, 1)]
n = len(costs)
best = [[0] * 3 for _ in range(n)]
best[n - 1] = costs[n - 1][:]
for i in range(n - 2, -1, -1):
for color in range(3):
a, b = unlike[color]
best[i][color] = costs[i][color] + min(best[i + 1][a], best[i + 1][b])
print(min(best[0]))
Names
no names yet
Output
(nothing printed yet)

Ask about an empty row before you code. With no houses, costs[n - 1] does not exist, so the table code raises IndexError; return 0 first. One house needs nothing extra: the bottom row is the whole table.

Fill one by hand. The order is what matters: bottom row first.

On paperFill a table by hand

On paper, fill the table for a new row of houses, then type the least total cost.

Housered (0)green (1)blue (2)
0971
1241
2714

best[i][color] is the least cost to paint houses i to the end when house i gets color. Fill the bottom row first, then row 1, then row 0.

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.

least total cost

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

Step 5 starts from one observation: row i reads only row i + 1. Once row 1 is filled, row 2 is never read again. So keep one row of answers, below, and build each new row from it alone. Predict what below holds after the first pass of the outer loop.

Step throughKeep one row, not the table
Step 1 of 32
Line 1 is about to run.
costs = [[2, 1, 6], [5, 1, 9], [8, 5, 2]]
unlike = [(1, 2), (0, 2), (0, 1)]
below = costs[-1][:]
for i in range(len(costs) - 2, -1, -1):
row = [0, 0, 0]
for color in range(3):
a, b = unlike[color]
row[color] = costs[i][color] + min(below[a], below[b])
below = row
print(min(below))
Names
no names yet
Output
(nothing printed yet)

Shrinking keeps the O(n) time and cuts the extra space from O(n) to O(1). It also throws rows away, and the next idea needs them.

Recovering the colors

The table stores costs, not colors. A common follow-up is "now return the plan, not only its cost", and the plan is still in the full table. Each cell was built from the cheaper of two cells in the row below, so following the cheaper allowed cell, row by row, retraces the choices. House 0 takes the color with the smallest cell in row 0. Each later house takes the cheaper of the two colors unlike the one before it.

The trace starts from the finished table. Guess the three colors before you step.

Step throughWalking the table to recover the colors
Step 1 of 25
Line 1 is about to run.
The finished table from the trace above.
best = [[5, 8, 9], [7, 3, 14], [8, 5, 2]]
unlike = [(1, 2), (0, 2), (0, 1)]
pick = 0
for c in range(3):
if best[0][c] < best[0][pick]:
pick = c
colors = [pick]
for i in range(1, len(best)):
a, b = unlike[pick]
pick = a
if best[i][b] < best[i][a]:
pick = b
colors.append(pick)
print(colors)
Names
no names yet
Output
(nothing printed yet)

This is why step 5 is optional. Recovering the plan needs the full table, or a second table that records each cell's choice. With one row kept you can report the cost but not the colors. Now walk the table you filled by hand.

PredictWalk your table back

This is the walk from the trace, run on the table you filled in the last exercise. Type exactly what it prints.

best = [[11, 9, 4], [3, 8, 2], [7, 1, 4]]
unlike = [(1, 2), (0, 2), (0, 1)]
pick = 0
for c in range(3):
    if best[0][c] < best[0][pick]:
        pick = c
colors = [pick]
for i in range(1, len(best)):
    a, b = unlike[pick]
    pick = a
    if best[i][b] < best[i][a]:
        pick = b
    colors.append(pick)
print(colors)

So far: a table holds one cell per state, and each cell is filled after the cells it reads. When a row reads only the row below, one row of answers is enough. The full table, walked from house 0, gives back the plan.

The steps on new shapes

Painting houses had a state made of an index and one remembered fact. The same five steps find states of other shapes.

Two ends of a string

The next problem gives you a string and asks for the longest subsequence (letters kept in their original order, the others dropped) that is a palindrome (reads the same forward and backward). In "agbcba", dropping the g leaves "abcba", so the answer is 5. Run the five steps.

Step 1: the choices happen at both ends. Look at the first and last letters of a piece of the string. If they match, they can be the outer pair of a palindrome, and the rest of it lies between them. If they differ, no palindrome uses both, so one end must go: try dropping each, and keep the better.

Step 2: what changes between calls is both ends of the piece. Write the piece as s[i..j], from position i to position j with both included (in Python, s[i:j + 1]). The state is the pair (i, j), not a prefix, because a palindrome is checked from both ends at once. In one sentence: best(i, j) is the length of the longest palindromic subsequence of s[i..j]. A string of n letters has n(n + 1) / 2 pieces, so that many states.

Steps 3 and 4 are yours: memoize on (i, j), then fill a table best[i][j] in an order where the shorter pieces inside each piece are ready.

mediumDynamic programming, 2D target 25 min

Longest palindromic subsequence

You get a string s of lowercase letters. A subsequence keeps some of the letters in their original order and drops the rest. A palindrome reads the same forward and backward, like "level".

Return the length of the longest subsequence of s that is a palindrome.

Example 1
Inputs = "agbcba"Output5

Dropping the g leaves "abcba".

Example 2
Inputs = "abcd"Output1

No letter repeats, so the best palindrome is a single letter.

Example 3
Inputs = "character"Output5

One answer is "carac", from the letters at positions 0, 2, 3, 4 and 5.

Constraints
  • 1 ≤ len(s) ≤ 1,000

  • s holds only lowercase English letters.

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.

The table fills from the bottom row up, because best[i][j] reads row i + 1 and the cell to its left. So step 5 works here too: two rows cut the space from O(n2) to O(n), that problem's memory follow-up. And a memo on 1,000 letters can nest about 1,000 calls deep, right at plain Python's default limit; the table never recurses.

Stretch: the last balloon

This part is a stretch goal, a hard problem. If time is short, skip it and come back after the module.

The palindrome's state was a piece named by its two ends, and DP over such pieces is called interval DP. Each palindrome cell looked only at the two ends of its piece. Harder interval problems try every place to split the piece, and the classic one bursts balloons.

The last problem bursts a row of balloons one at a time. A burst earns coins: the balloon's number times the numbers of its two nearest balloons still standing, with 1 for a missing neighbor. You want the largest total. For [2, 4, 3], bursting the 4 (2 × 4 × 3 = 24), then the 2 (1 × 2 × 3 = 6), then the 3 (1 × 3 × 1 = 3) earns 33, the most any order earns.

Step 1 with the natural choice, "which balloon next?", fails step 2. After some bursts, what is left can be any set of the balloons, and n balloons have 2n sets: still exponential. Worse, bursting a middle balloon makes its two neighbors touch, so the left and right sides keep affecting each other.

Flip the choice: which balloon goes last? Take a stretch of balloons between two balloons that stay put, the walls. When the stretch's last balloon bursts, everything else in it is gone, so its neighbors are exactly the two walls: it earns left wall × last × right wall. Until then it stands between the two sides, so they never touch, and the stretch splits into two smaller stretches, each with its own walls. Pad the row with a 1 at each end, vals = [1] + nums + [1], so the outer balloons have walls too. The state is the pair of walls, (left, right): about n2 / 2 states instead of 2n.

Written out, with last the position of the balloon burst last:

  • State: best[left][right] is the most coins from bursting every balloon strictly between positions left and right of vals, while those two walls still stand.
  • Base case: walls side by side (right = left + 1) have nothing between them, so the cell is 0.
  • Transition: try each last between the walls and keep the largest best[left][last] + vals[left] * vals[last] * vals[right] + best[last][right].

Each stretch reads only shorter stretches, so fill by length. (The palindrome's bottom-up rows would work too: they also fill every piece after the pieces inside it.) The trace prints the walls of each stretch of the padded [2, 4, 3] in the order the table fills them. gap is right - left, so a gap of 2 holds one balloon. Guess the last pair before you step.

Step throughStretches, shortest first
Step 1 of 28
Line 1 is about to run.
The row [2, 4, 3] with a padding 1 at each end.
vals = [1, 2, 4, 3, 1]
n = len(vals)
for gap in range(2, n):
for left in range(n - gap):
right = left + gap
print(left, right)
Names
no names yet
Output
(nothing printed yet)

Try the split rule on two balloons before the full problem.

Work it outWhich balloon goes last

Use the last-balloon rule on nums = [3, 5], so vals = [1, 3, 5, 1]. The one-balloon stretches are already filled: best[0][2] = 1 × 3 × 5 = 15 and best[1][3] = 3 × 5 × 1 = 15. Stretches with nothing inside, like best[0][1], are 0.

What is best[0][3], the most coins for the whole row?

best[0][3]

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

Now the full problem: pad the row, fill stretches by gap, and try every balloon as the last one.

hardDynamic programming, 2D target 40 min

Burst balloons

A row of balloons has a number on each one, given as the list nums. You burst the balloons one at a time, in any order you choose, until none is left.

Bursting a balloon earns coins: its number times the numbers on its two nearest balloons still in the row, one on the left and one on the right. When no balloon is left on a side, use 1 for that side. Return the largest total of coins you can earn.

Example 1
Inputnums = [2, 4, 3]Output33

Burst the 4 first: 2 × 4 × 3 = 24. Now the 2 and the 3 are neighbors. Burst the 2: 1 × 2 × 3 = 6. Burst the 3: 1 × 3 × 1 = 3. Total 24 + 6 + 3 = 33.

Example 2
Inputnums = [1, 5]Output10

Burst the 1 first: 1 × 1 × 5 = 5, then the 5 alone: 1 × 5 × 1 = 5. Bursting the 5 first earns only 5 + 1 = 6.

Example 3
Inputnums = [9, 1, 1, 9]Output180

Burst the two 1s first, while the 9s are their neighbors: 9 × 1 × 1 = 9 and 9 × 1 × 9 = 81. Then 1 × 9 × 9 = 81 and 1 × 9 × 1 = 9. Total 9 + 81 + 81 + 9 = 180.

Constraints
  • 1 ≤ len(nums) ≤ 300

  • 0 ≤ nums[i] ≤ 100

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.

The hard part of burst balloons was step 1, not the table. Splitting on the first burst leaves the two sides tangled; splitting on the last makes them independent. When the state from step 2 comes out exponential, ask whether a different choice would split the input into pieces that do not affect each other.

One more hard problem in this module's practice bank runs the steps on a grid: Longest increasing path in a grid (LeetCode 329). The state is a single cell, because a path that only climbs can never come back to a cell it has passed, and the table fills from the biggest number down.

Last, say the five steps out loud on a changed constraint.

Say itSay it out loud: k colors

The interviewer changes the problem: there are now k colors instead of 3, with costs[i] holding k prices. Say how you would solve it, going through the five steps, and state the cost.

A few sentences first: 0 of 60 characters.

Saved in this browser as you type.

Next: the module checkpoint