Six interview problems with a table over choices: budgets, holding states and string prefixes. The move: keep in the state only what the future needs from the past.
You work on an ad planner, a trading desk, a dispatch service, a log store and a router. The six problems on this street come from them. Each one chooses among options, and each one is solved by a table over a state.
Here is the state of each problem, and the moves that lead out of it.
| Problem | The state | The moves |
|---|---|---|
| Most items within two budgets | display units left, review minutes left | take the ad, or skip it |
| Best profit with a holding cost | holding a unit, or free | buy, sell or wait |
| Best resale profit with a lockout | free, holding, or locked | buy, sell or wait |
| Crew plans that reach the profit target | drivers used, profit so far (capped) | take the campaign, or skip it |
| Ways a pattern appears as a subsequence | how much of the pattern is matched | use this letter, or not |
| Match a route against a wildcard | route prefix, pattern prefix | a letter, a question mark, a star |
A state is a summary of the past. If two different pasts lead to the same state, the future cannot tell them apart.
Notice that the first three rows ask for a best value, and the fourth asks for a count. A count adds the counts of the states it comes from, where a best value takes the larger one. The state is the same in both cases.
Exercise · Predict the output: Ways to spell the route. Cell j counts the ways to pick letters of the text so far that spell the first j letters of the pattern. The inner loop runs from the end down. What does the code print?
text = "rabbbit"
pattern = "rabbit"
m = len(pattern)
ways = [1] + [0] * m
for ch in text:
for j in range(m, 0, -1):
if pattern[j - 1] == ch:
ways[j] += ways[j - 1]
print(ways[m])Ask what the future needs to know about the past, and nothing more. That is the state.
The state holds exactly what the remaining choices depend on: the budgets left, whether you hold a unit, or how much of the pattern is matched. Each move maps a state to a few next states, and the answer is read where nothing is left to decide.
The six problems differ in their state, not in their method.
Cell j counts the ways to spell the first j letters of the pattern: update from the end so each letter counts once.
Exercise · Find the bug: One letter used twice. This counts the ways the text can spell the pattern by picking letters in order. It gives too large a count for some inputs. Which line is wrong?
def count_occurrences(text, pattern):
m = len(pattern)
ways = [1] + [0] * m
for ch in text:
for j in range(1, m + 1):
if pattern[j - 1] == ch:
ways[j] += ways[j - 1]
return ways[m]The Academy lessons Dynamic programming from recursion, Knapsack and String DP teach one budget, one holding choice and two strings. This street changes three things.
The state grows by one part. With 100 ads and two budgets of 100, the table has 100 × 101 × 101 = 1,020,100 cells, while the choices are 2^100 subsets, about 1.3 × 10^30. A second budget did not change the method.
The state has a hidden part. With the prices 1 2 3 0 2, the best profit is 4 when you may buy at once after a sale. It is 3 when a pause of 1 day follows each sale. The lockout is the third value of the state: free, holding or locked.
The update order is part of the answer. Counting the ways to spell rabbit from rabbbit gives 3 when the cells are updated downwards, and 6 when they are updated upwards. A grid of 1,000 route letters and 1,000 pattern letters has 1,002,001 cells.
A star may match no letters: it reads the cell to its left as well as the cell above.
Exercise · Break it: The star that needs a letter. This tests whether a route matches a pattern. A question mark matches one letter, and a star matches any run of letters, including none. Find an input where it answers wrongly.
def route_matches(route, pattern):
n = len(route)
m = len(pattern)
match = [[False] * (m + 1) for _ in range(n + 1)]
match[0][0] = True
for i in range(n + 1):
for j in range(1, m + 1):
p = pattern[j - 1]
if p == "*":
match[i][j] = i > 0 and (match[i - 1][j] or match[i - 1][j - 1])
elif i > 0 and (p == "?" or p == route[i - 1]):
match[i][j] = match[i - 1][j - 1]
return match[n][m]Solve them in this order. The first three choose among items and states, the fourth counts, and the last two work on strings.
Before you code each problem, write the state in one line, and the moves out of it in another. If the state is larger than the future needs, a number in it is redundant.
The wildcard problem has the largest table, since each cell depends on the route and on the pattern. A star reads two neighbours, and a letter or a question mark reads one.
Give each problem about 25 minutes. Spend the first five on the two lines and one table filled by hand for a tiny input.
Test the empty case, an input where every choice is equal, and an input at the limit of each budget. Most wrong answers come from a state that forgets something the future needs, or from an update order that reads a cell too early or too late.
Checkpoint · DP on choices and strings
Q1/5 How many ways can the text rabbbit spell the pattern rabbit by picking letters in order?
Answer: B
The text has three b letters and the pattern needs two of them in order, which is 3 ways. Updating the cells upwards instead of downwards would count 6.
Q2/5 Why must the cells be updated from the largest index down when each letter of the text may be used once?
Answer: B
Updating upwards lets the changed cell feed the next one, so the same letter fills two positions of the pattern.
Q3/5 A trader may not buy for a pause after each sale. What does the state need beyond holding or not?
Answer: B
After a sale you can neither buy nor sell until the pause ends. That is a third value of the state: locked.
Q4/5 Does the pattern ab* match the route ab?
Answer: B
A star matches any run of letters, including none, so ab followed by an empty star matches ab. In the table the star reads the cell to its left.
Q5/5 With 100 ads and two budgets of 100, about how many cells does the table have?
Answer: C
The table has 100 × 101 × 101 = 1,020,100 cells. The number of subsets of ads is 2^100, about 1.3 × 10^30.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.