Designing States & Transitions
Choosing what to remember: prefixes, suffixes, ranges and extra parameters.
The loop of a dynamic program is the easy part; deciding what a cell means is the whole art. "The best profit after day " breaks the moment tomorrow's options depend on today's choice, and one extra parameter, the right one, repairs it. This lesson treats state design as a discipline: what a state must remember, how to prove that a transition misses nothing, and how to tell when no small state can exist.
What you’ll learn
- Define a dynamic program precisely (states, options, base states, an acyclic dependency order) and prove a transition exact from soundness, completeness and monotonicity.
- Choose among the standard subproblem families (prefixes, suffixes, intervals, prefix pairs, subtrees, subsets) and count states and options before coding.
- Restore optimal substructure with an extra parameter: the last choice, a count of actions used, or the state of a finite machine.
- Prove that the longest palindromic subsequence of has the length of , design transitions with options, and state the fine-grained limits of prefix-pair DPs.
What a state must remember
Induct along a topological order, assuming is the optimum over for every state before ; take opt = max (min is symmetric). Upper bound. An optimal decomposes through some option (completeness), and monotonicity lets each part be replaced by an optimal one:
Lower bound. For the option that attains , combine optimal solutions of its subproblems; soundness makes the combination feasible:
So a state must be a sufficient summary of the past: all partial solutions that reach it must have the same feasible completions, with the same values. If two partial solutions in one state have different futures, completeness or soundness fails, and the state is missing a parameter.
| Input | Subproblem family | Number of states |
|---|---|---|
| A sequence of length | Prefixes or suffixes | |
| A sequence | Substrings (intervals) | |
| Two sequences, lengths and | Pairs of prefixes | |
| A rooted tree on nodes | Subtrees | |
| A set of items | Subsets, as bitmasks | |
| Any of the above | × an extra parameter | × its range: transactions, a budget , a machine with states |
Add a parameter: a state machine
You trade one stock with daily prices : hold at most one share, buy and sell at the day's price, and after a sale wait one full day before buying again (a cooldown). Maximize the profit.
"The best profit after day " is not sufficient: tomorrow's legal moves depend on whether you hold a share and whether you sold today, so two histories with equal profit can have different futures. Add that information as a mode, the state of a three-state machine: free (no share, may buy), hold (own a share), cool (sold today, must rest tomorrow).
def max_profit_cooldown(p):
free, hold, cool = 0, float('-inf'), float('-inf')
for x in p: # one day: every legal move of the machine
free, hold, cool = max(free, cool), max(hold, free - x), hold + x
return max(free, cool)
print(max_profit_cooldown([1, 2, 3, 0, 2])) # 3: buy 1, sell 2, rest, buy 0, sell 2The simultaneous assignment reads yesterday's three values before overwriting any of them: a rolling array over the mode dimension.
More rules, more parameters. With at most transactions, add the number of buys so far: states with , so time. A fee per sale changes the values but not the state. In general, any rule that a finite automaton can check while reading the decisions left to right can be enforced by pairing the index with the automaton's state, which multiplies the states by the automaton's size.
A variant of house robber: you may rob two adjacent houses, but never three in a row. Which state is sufficient, with the fewest values?
- , the best total from the first houses
- , where is the length of the run of robbed houses at the end of the prefix
- , where is the set of houses robbed so far
- , where is the total robbed so far
Show the answer
B. , where is the length of the run of robbed houses at the end of the prefix
The future depends on the past only through the current run: after a run of 2 the next house must be skipped. So , and : states with work each. On the best is 15, skipping house 2 (or house 1).
Intervals and pairs of prefixes
When a choice can happen at both ends, use intervals. A longest palindromic subsequence of has states for the substring , inclusive:
with and for the empty substring. Filling in order of increasing length gives states with work each: interval DP. For "character" the answer is 5, for example "carac".
At most. A palindromic subsequence of is also a subsequence of : the reversed positions spell . So it is a common subsequence:
At least. Take a common subsequence of length . Its copy in uses positions ; its copy in , translated back to positions of , uses ; and . The difference strictly increases with , so the indices split into three consecutive groups:
The first group is nested, , with equal letters at each pair of ends: it spells a palindrome of length , plus the middle letter if . The last group, read as , is nested the same way. The two palindromes have lengths and , which average to :
With two sequences, use pairs of prefixes. A wildcard pattern uses ? for any one letter and * for any string, the empty one included. Let say whether matches exactly:
def matches(s, p):
"""Does p ('?' = any one letter, '*' = any string) match all of s?"""
n, m = len(s), len(p)
M = [[False] * (m + 1) for _ in range(n + 1)]
M[0][0] = True
for j in range(1, m + 1): # the empty text: only stars
M[0][j] = M[0][j - 1] and p[j - 1] == '*'
for i in range(1, n + 1):
for j in range(1, m + 1):
if p[j - 1] == '*': # nothing, or eat s[i-1]
M[i][j] = M[i][j - 1] or M[i - 1][j]
elif p[j - 1] in ('?', s[i - 1]):
M[i][j] = M[i - 1][j - 1]
return M[n][m]
print(matches('dynamic', 'd*m?c'), matches('programming', '*g?m*')) # True FalseTested against Python's fnmatch.fnmatchcase on thousands of random texts and patterns over a, b, ? and *.
When no small state exists
Counting states also shows when a DP cannot be small. For the longest simple path in a graph with cycles, two partial paths ending at the same vertex have the same futures only if they used the same vertices, so a sufficient state includes the visited set: states, a bitmask DP practical up to about . Since the problem is NP-hard, no polynomial-size state with a polynomial-time transition exists unless P = NP.
A polynomial state space, in turn, is not always the last word:
- Dominance. If one partial solution is at least as good as another in everything the future depends on, the worse one can be dropped. A DP does this for partial solutions with equal states. With two criteria, such as weight and value in knapsack, keep the Pareto front of non-dominated pairs, often far smaller than the full table (Nemhauser & Ullmann, 1969).
- Reachable states only. Top-down evaluation, or a hash map of the states actually reached, touches only states that some sequence of choices can produce, which can be far fewer than the table's cells.
- A better algorithm outside DP. For patterns with stars but no ?, the pieces between stars can be placed greedily at their leftmost occurrences, found with KMP, in total time instead of the table's .
Key takeaways
- A state must be sufficient: partial solutions that reach the same state must have the same feasible futures with the same values. If they do not, add the missing parameter.
- Soundness (every option builds a feasible solution), completeness (every solution goes through some option) and monotone combining functions make a transition exact, by induction along a topological order.
- The standard families are prefixes or suffixes (), intervals (), prefix pairs (), subtrees () and subsets (), times the range of each extra parameter. Count states times options before coding.
- Transitions with options, such as peeling one letter off a star, can save a factor of . In the other direction, reuses one table for another problem, and under SETH prefix-pair DPs such as LCS and edit distance cannot be made strongly subquadratic.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why is "the best profit after day " not a valid state for the cooldown problem?
- It has too many values to store
- Two histories with the same profit can differ in whether you hold a share or just sold, and those allow different moves tomorrow
- Profits can be negative, which a table cannot hold
- The days must be processed backward
Show the answer
B. Two histories with the same profit can differ in whether you hold a share or just sold, and those allow different moves tomorrow
A state must summarize everything the future depends on. Holding a share allows a sale but not a buy, and having sold today forbids a buy tomorrow, so the mode is part of the state. With it, completeness and soundness hold, and the DP is exact.
A friend computes a longest common subsequence of and its reverse and reports it as a longest palindromic subsequence of . What is true?
- It is always correct: every common subsequence of and is a palindrome
- Its length is right, but the string itself may not be a palindrome: for , is a longest common subsequence of and
- Its length can be too large, because and may share more than a palindrome
- It is correct only for strings of odd length
Show the answer
B. Its length is right, but the string itself may not be a palindrome: for , is a longest common subsequence of and
as numbers, by the mirroring argument, but an arbitrary LCS need not be a palindrome. To report a palindrome, run the interval DP and trace it back, or apply the proof's construction to the LCS found.
In the wildcard DP, a star's transition is rather than a disjunction over every length the star could absorb. What does that buy, and why is it still complete?
- Nothing: both take time
- Two options per state instead of , so instead of ; complete because a star that absorbs a nonempty also matches , leaving the state
- It is faster but incomplete: a star can no longer absorb more than one letter
- It avoids recursion, which the disjunction would need
Show the answer
B. Two options per state instead of , so instead of ; complete because a star that absorbs a nonempty also matches , leaving the state
The state keeps the star at the end of the pattern prefix, so it can keep eating letters one at a time: repeated applications cover every length. Peeling one letter off a flexible piece is a standard way to cut a transition from options to .
Stock trading with at most transactions over days uses states (day, buys so far, holding or not). How long does the DP take?
Show the answer
B.
There are states, and each has two options (rest, or trade from the matching state of the day before), so the total is time. A rolling array over the days keeps space.
Further reading
- E. Demaine, J. Ku & J. Solomon, 6.006 Introduction to Algorithms, Spring 2020, lectures 15–18 (MIT OpenCourseWare).
- J. Erickson, Algorithms (2019), chapter 3.
- A. Backurs & P. Indyk, "Which regular expression patterns are hard to match?", FOCS 2016.
- A. Abboud, A. Backurs & V. Vassilevska Williams, "Tight hardness results for LCS and other sequence similarity measures", FOCS 2015.
- K. Bringmann, F. Grandoni, B. Saha & V. Vassilevska Williams, "Truly sub-cubic algorithms for language edit distance and RNA folding via fast bounded-difference min-plus product", FOCS 2016.