When DP works

3 properties Β· Part of Strategies

Key idea

Practice

6 questions Β· about 3 min

Explained step by step

Dynamic programming

Divide and conquer, dynamic programming and backtracking all split a problem, but differently. Divide and conquer splits into independent subproblems and combines their solutions. Dynamic programming also splits, but its subproblems depend on one another and repeat a lot. Backtracking tries every sequence of choices and undoes the ones that fail. In Fibonacci of 30, subproblems repeat over 1 million times: that is dynamic programming territory.

Dynamic programming works because the problems have no aftereffect: given a state, what can happen next depends only on that state, not on how it was reached. In stair climbing, from stair i you can go to i + 1 or i + 2, no matter which stairs you landed on before. Whether you went through 2 or 1 to reach 3, from 3 the options are the same.

If the rule Β«you cannot climb 1 stair twice in a rowΒ» is added, state i is no longer enough: if the last move was 1, the next must be 2. A 3-stair staircase can be climbed in 2 ways, because 1 + 1 + 1 is out. The fix is to extend the state: [i, j] is being on stair i with a last move of j. Then: dp[i, 1] = dp[i βˆ’ 1, 2] and dp[i, 2] = dp[i βˆ’ 2, 1] + dp[i βˆ’ 2, 2].

Some problems depend on the whole past. If every time you land on stair i an obstacle appears on 2i, each move changes what can be done later: landing on 2 and 3 blocks 4 and 6. No small state sums all that up, and dynamic programming usually fails. It happens in problems like the traveling salesperson. For them, heuristic search, genetic algorithms or reinforcement learning are used, which find a good solution in reasonable time.

Optimal substructure

Each stair has a cost, and you want to reach the top spending as little as possible, climbing 1 or 2 at a time. Stair i is reached from i βˆ’ 1 or i βˆ’ 2, so the cheapest is the cheaper of those 2 plus the cost of i: dp[i] = min(dp[i βˆ’ 1], dp[i βˆ’ 2]) + cost[i]. That is optimal substructure: the best solution is built from the best ones of the subproblems. If stairs 1, 2 and 3 cost 1, 10 and 1, reaching 3 costs 2.

The optimization problems dynamic programming solves well have 3 properties. Overlapping subproblems: the same ones show up many times, and storing them saves work. Optimal substructure: the best solution is built from the best of the subproblems. And no aftereffect: from a state, what comes next depends only on it. If the third is missing, sometimes the state can be extended to recover it.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

3 properties