Recognizing DP and choosing the state
Spot when a problem needs DP: optimal or counting answers built from overlapping choices. Then pick a state that captures what matters.
Is it DP, and which family?
The idea
Counting ways up 5 stairs by brute force asks ways(3) twice and ways(2) three times. A question asked twice is the first sign of DP.
Each repeated node has the same answer every time. Storing it once turns an exponential call tree into one value per stair.
Intuition
DP fits when the answer is one number, such as a best value, a count or a yes/no, and it comes from choices whose subproblems repeat.
Words like minimum, maximum, number of ways, longest and can you are the usual signal. Return every solution is the opposite signal: the output itself is huge.
This flowchart asks those questions in order. The last one, what a choice must remember, names the state and the family.
Complexity
DP time is the number of states times the work per state. The state you pick sets that cost: n, n² or 2ⁿ states.
Climbing stairs has n states and 2 choices each: O(n). LCS has n · m states: O(n · m). A bitmask state over n items has 2ⁿ states, so it only works for small n.
Pitfalls
Taking the biggest coin first looks right but fails. With coins 1, 3, 4 and amount 6, greedy pays 4 + 1 + 1; DP finds 3 + 3.
Greedy commits to one choice and never revisits it. When a choice changes what is left for later, try every choice and let the table pick.
A state that forgets what the next choice needs gives wrong answers. Painting houses needs the last colour; the next lesson adds it.
Variations
Each family box has its own topic with worked problems. Open the one your state points to.
Choosing the state: paint the houses
The idea
Paint 4 houses red, green or blue so that no two neighbours share a colour. Each cell is a cost; find the cheapest total.
This is a new problem with no family name on it. The flowchart says: one best value, and the same houses come back. The open question is the state.
Intuition
Picking the cheapest colour per house breaks the rule: houses 2 and 3 would both be green.
dp[i] = cheapest total for houses 0..i is not enough. It does not say which colour house i has, and house i + 1 needs that.
Add the colour to the state: dp[i][k] is the cheapest total with house i in colour k. The rule becomes a min over the other colours.
Ask what the next choice must know about the past. Here it is only the last colour, so the state is (house, last colour): 3 values per house.
Complexity
There are n · k states and each reads k − 1 cells above: O(n · k²) time. Trying every colouring takes about kⁿ.
With k = 3 that is 9n steps. Space can drop to one row of k values, as in rolling-array DP.
Pitfalls
The answer is the smallest value in the last row, not one fixed colour. Here blue gives 18 while red gives 19.
Remembering every colour used so far makes the state count explode. Keep only what the next choice needs: the last colour.
Variations
With k colours, keep the smallest and second smallest of the row above. Each cell then reads one of them: O(n · k).
Stock trading adds a mode to the state the same way: holding a share or not. That family is the state machine DP.
Code
Pseudocode
family(problem):
if problem asks to list every answer
return backtracking
if no subproblem is asked twice
return greedy or divide and conquer
state ← what one choice must remember
return the family named by state
Python
FAMILIES = {
"position": "1-D DP",
"two positions": "string or grid DP",
"capacity left": "knapsack",
"open range": "interval DP",
"used set": "bitmask DP",
"subtree": "tree DP",
"mode": "state machine DP",
}
def family(problem):
if problem.goal == "list all":
return "backtracking"
if not problem.subproblems_repeat:
return "greedy or divide and conquer"
state = problem.what_a_choice_remembers
return FAMILIES[state]
JavaScript
const FAMILIES = {
position: "1-D DP",
twoPositions: "string or grid DP",
capacityLeft: "knapsack",
openRange: "interval DP",
usedSet: "bitmask DP",
subtree: "tree DP",
mode: "state machine DP",
};
function family(problem) {
if (problem.goal === "list all") return "backtracking";
if (!problem.subproblemsRepeat) return "greedy or divide and conquer";
const state = problem.whatAChoiceRemembers;
return FAMILIES[state];
}
Practice problems (7)
Classify problems Warm-up
Match each problem to the DP family its state points to. Ask what one choice must remember.
Pick the state Warm-up
prices[i] is a share's price on day i. You may hold at most one share, and buy and sell as often as you like, but after a sale you must wait one day before buying again.
Which state lets a DP find the best profit?
Write the recurrence Standard
Step i of a staircase costs cost[i] to stand on. You start on step 0 or step 1 and climb 1 or 2 steps at a time. The top is just past the last step.
The state is dp[i], the cheapest way to reach step i. Fill the blanks: the base cases, the recurrence and the answer.
Courier tolls Standard
A courier crosses a city laid out as blocks. Entering block (r, c) costs tolls[r][c], the start block included. The courier starts at the top-left block, ends at the bottom-right one, and only moves east or south.
Return the smallest total toll. First decide which DP family this is.
Domino tilings Standard
A board is 2 cells tall and n cells wide. A domino covers 2 cells and may stand upright or lie flat.
Return the number of ways to cover the whole board with dominoes. Look for a DP family you have seen before.
Walk the flowchart Standard
Can [1, 5, 11, 5] be split into two groups with equal sums? Walk the flowchart for this problem and answer each question before the step plays.
Design a DP: paint the houses Challenge
A row of houses must each be painted red, green or blue, and no two neighbours may share a colour. costs[i][k] is the price of painting house i with colour k.
Return the cheapest total. Design the DP yourself: choose a state, write the recurrence, then code it.
Next on the path: LRU and LFU caches