Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

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 ii" 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 ss has the length of LCS(s,sR)\mathrm{LCS}(s, s^R), design transitions with O(1)O(1) options, and state the fine-grained limits of prefix-pair DPs.

What a state must remember

DerivationProof
  1. val(x⋆)=go(val(xt)) ≤ go(V(t)) ≤ V(s)\mathrm{val}(x^\star) = g_o\big(\mathrm{val}(x_t)\big) \ \le\ g_o\big(V(t)\big) \ \le\ V(s)

    Induct along a topological order, assuming V(t)V(t) is the optimum over Sol(t)\mathrm{Sol}(t) for every state tt before ss; take opt = max (min is symmetric). Upper bound. An optimal x⋆∈Sol(s)x^\star \in \mathrm{Sol}(s) decomposes through some option oo (completeness), and monotonicity lets each part be replaced by an optimal one:

  2. V(s)=go(V(t))=val(combination) ≤ val(x⋆)V(s) = g_o\big(V(t)\big) = \mathrm{val}(\text{combination}) \ \le\ \mathrm{val}(x^\star)

    Lower bound. For the option oo that attains V(s)V(s), combine optimal solutions of its subproblems; soundness makes the combination feasible:

  3. same state ⟹ same feasible futures, same values\text{same state} \ \Longrightarrow\ \text{same feasible futures, same values}

    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.

InputSubproblem familyNumber of states
A sequence of length nnPrefixes x[0..i)x[0..i) or suffixes x[i..n)x[i..n)n+1n + 1
A sequenceSubstrings (intervals) x[i..j]x[i..j]Θ(n2)\Theta(n^2)
Two sequences, lengths nn and mmPairs of prefixes (i,j)(i, j)(n+1)(m+1)(n + 1)(m + 1)
A rooted tree on nn nodesSubtreesnn
A set of nn itemsSubsets, as bitmasks2n2^n
Any of the above× an extra parameter× its range: kk transactions, a budget WW, a machine with qq states
The standard menu of subproblems, as in MIT's 6.006. Multiply the states by the options per state before writing any code: that product is the running time.

Add a parameter: a state machine

You trade one stock with daily prices p[0],…,p[n−1]p[0], \dots, p[n-1]: 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 ii" 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).

freei=max⁡(freei−1, cooli−1)holdi=max⁡(holdi−1, freei−1−p[i])cooli=holdi−1+p[i]\begin{aligned} \text{free}_i &= \max\big(\text{free}_{i-1},\ \text{cool}_{i-1}\big) \\ \text{hold}_i &= \max\big(\text{hold}_{i-1},\ \text{free}_{i-1} - p[i]\big) \\ \text{cool}_i &= \text{hold}_{i-1} + p[i] \end{aligned}
Before day 0, free=0\text{free} = 0 and hold=cool=−∞\text{hold} = \text{cool} = -\infty (impossible); the answer is max⁡(freen−1,cooln−1)\max(\text{free}_{n-1}, \text{cool}_{n-1}). Each term is one legal move: rest, buy (only from free, never from cool), or sell.
python
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 2

The 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 kk transactions, add the number of buys so far: states (i,j,holding)(i, j, \text{holding}) with 0≤j≤k0 \le j \le k, so O(nk)O(nk) 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.

Check your understanding

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?

  1. x(i)x(i), the best total from the first ii houses
  2. x(i,r)x(i, r), where r∈{0,1,2}r \in \{0, 1, 2\} is the length of the run of robbed houses at the end of the prefix
  3. x(i,S)x(i, S), where SS is the set of houses robbed so far
  4. x(i,t)x(i, t), where tt is the total robbed so far
Show the answer

B. x(i,r)x(i, r), where r∈{0,1,2}r \in \{0, 1, 2\} 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 x(i,0)=max⁡rx(i−1,r)x(i, 0) = \max_r x(i-1, r), x(i,1)=x(i−1,0)+a[i−1]x(i, 1) = x(i-1, 0) + a[i-1] and x(i,2)=x(i−1,1)+a[i−1]x(i, 2) = x(i-1, 1) + a[i-1]: 3(n+1)3(n + 1) states with O(1)O(1) work each. On [5,5,5,5][5, 5, 5, 5] 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 ss has states L(i,j)L(i, j) for the substring s[i..j]s[i..j], inclusive:

L(i,j)={L(i+1,j−1)+2if s[i]=s[j],max⁡(L(i+1,j), L(i,j−1))otherwise,L(i, j) = \begin{cases} L(i+1, j-1) + 2 & \text{if } s[i] = s[j], \\ \max\big(L(i+1, j),\ L(i, j-1)\big) & \text{otherwise,} \end{cases}

with L(i,i)=1L(i, i) = 1 and L(i+1,i)=0L(i+1, i) = 0 for the empty substring. Filling in order of increasing length j−ij - i gives Θ(n2)\Theta(n^2) states with O(1)O(1) work each: interval DP. For "character" the answer is 5, for example "carac".

DerivationProof
  1. LPS(s) ≤ LCS(s,sR)\mathrm{LPS}(s) \ \le\ \mathrm{LCS}(s, s^R)

    At most. A palindromic subsequence ww of ss is also a subsequence of sRs^R: the reversed positions spell wR=ww^R = w. So it is a common subsequence:

  2. at<bt  (t≤k),at=bt  (m∈{0,1} values of t),at>bt  (the remaining ℓ−k−m)a_t < b_t\ \ (t \le k), \qquad a_t = b_t\ \ (m \in \{0, 1\} \text{ values of } t), \qquad a_t > b_t\ \ (\text{the remaining } \ell - k - m)

    At least. Take a common subsequence ww of length ℓ\ell. Its copy in ss uses positions a1<⋯<aℓa_1 < \dots < a_\ell; its copy in sRs^R, translated back to positions of ss, uses b1>⋯>bℓb_1 > \dots > b_\ell; and s[at]=s[bt]=wts[a_t] = s[b_t] = w_t. The difference at−bta_t - b_t strictly increases with tt, so the indices split into three consecutive groups:

  3. LPS(s) ≥ max⁡(2k+m, 2(ℓ−k−m)+m) ≥ ℓ\mathrm{LPS}(s) \ \ge\ \max\big(2k + m,\ 2(\ell - k - m) + m\big) \ \ge\ \ell

    The first group is nested, a1<⋯<ak<bk<⋯<b1a_1 < \dots < a_k < b_k < \dots < b_1, with equal letters at each pair of ends: it spells a palindrome of length 2k2k, plus the middle letter if m=1m = 1. The last group, read as bℓ<⋯<aℓb_\ell < \dots < a_\ell, is nested the same way. The two palindromes have lengths 2k+m2k + m and 2(ℓ−k−m)+m2(\ell - k - m) + m, which average to ℓ\ell:

With two sequences, use pairs of prefixes. A wildcard pattern pp uses ? for any one letter and * for any string, the empty one included. Let M(i,j)M(i, j) say whether p[0..j)p[0..j) matches s[0..i)s[0..i) exactly:

M(i,j)={M(i,j−1) ∨ M(i−1,j)if p[j−1]=*,M(i−1,j−1)if p[j−1]=? or p[j−1]=s[i−1],falseotherwise,M(i, j) = \begin{cases} M(i, j-1)\ \lor\ M(i-1, j) & \text{if } p[j-1] = \texttt{*}, \\ M(i-1, j-1) & \text{if } p[j-1] = \texttt{?} \text{ or } p[j-1] = s[i-1], \\ \text{false} & \text{otherwise,} \end{cases}
for i,j≥1i, j \ge 1, with M(0,0)M(0, 0) true, M(i,0)M(i, 0) false for i>0i > 0, and M(0,j)=M(0,j−1)∧(p[j−1]=*)M(0, j) = M(0, j-1) \land (p[j-1] = \texttt{*}): O(nm)O(nm) states with O(1)O(1) work each.
python
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 False

Tested 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: 2nn2^n n states, a bitmask DP practical up to about n=20n = 20. 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 O(n+m)O(n + m) total time instead of the table's O(nm)O(nm).

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 (nn), intervals (n2n^2), prefix pairs (nmnm), subtrees (nn) and subsets (2n2^n), times the range of each extra parameter. Count states times options before coding.
  • Transitions with O(1)O(1) options, such as peeling one letter off a star, can save a factor of nn. In the other direction, LPS(s)=LCS(s,sR)\mathrm{LPS}(s) = \mathrm{LCS}(s, s^R) 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.

Question 1

Why is "the best profit after day ii" not a valid state for the cooldown problem?

  1. It has too many values to store
  2. Two histories with the same profit can differ in whether you hold a share or just sold, and those allow different moves tomorrow
  3. Profits can be negative, which a table cannot hold
  4. 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.

Question 2

A friend computes a longest common subsequence of ss and its reverse sRs^R and reports it as a longest palindromic subsequence of ss. What is true?

  1. It is always correct: every common subsequence of ss and sRs^R is a palindrome
  2. Its length is right, but the string itself may not be a palindrome: for abcab\texttt{abcab}, acb\texttt{acb} is a longest common subsequence of ss and sRs^R
  3. Its length can be too large, because ss and sRs^R may share more than a palindrome
  4. 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 abcab\texttt{abcab}, acb\texttt{acb} is a longest common subsequence of ss and sRs^R

LCS(s,sR)=LPS(s)\mathrm{LCS}(s, s^R) = \mathrm{LPS}(s) as numbers, by the mirroring argument, but an arbitrary LCS need not be a palindrome. To report a palindrome, run the interval DP L(i,j)L(i, j) and trace it back, or apply the proof's construction to the LCS found.

Question 3

In the wildcard DP, a star's transition is M(i,j)=M(i,j−1)∨M(i−1,j)M(i, j) = M(i, j-1) \lor M(i-1, j) rather than a disjunction over every length the star could absorb. What does that buy, and why is it still complete?

  1. Nothing: both take O(nm)O(nm) time
  2. Two options per state instead of O(n)O(n), so O(nm)O(nm) instead of O(n2m)O(n^2 m); complete because a star that absorbs a nonempty s[k..i)s[k..i) also matches s[k..i−1)s[k..i-1), leaving the state (i−1,j)(i-1, j)
  3. It is faster but incomplete: a star can no longer absorb more than one letter
  4. It avoids recursion, which the disjunction would need
Show the answer

B. Two options per state instead of O(n)O(n), so O(nm)O(nm) instead of O(n2m)O(n^2 m); complete because a star that absorbs a nonempty s[k..i)s[k..i) also matches s[k..i−1)s[k..i-1), leaving the state (i−1,j)(i-1, j)

The state (i−1,j)(i-1, j) 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 O(n)O(n) options to O(1)O(1).

Question 4

Stock trading with at most kk transactions over nn days uses states (day, buys so far, holding or not). How long does the DP take?

  1. O(n)O(n)
  2. O(nk)O(nk)
  3. O(nk2)O(nk^2)
  4. O(n2k)O(n^2 k)
Show the answer

B. O(nk)O(nk)

There are n(k+1)⋅2n(k + 1) \cdot 2 states, and each has two options (rest, or trade from the matching state of the day before), so the total is O(nk)O(nk) time. A rolling array over the days keeps O(k)O(k) 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.