Advanced DP: Intervals, Trees and Bitmasks
Tackle interval DP, DP on trees, bitmask DP over subsets and digit DP, which show up in hard interview rounds and contests.
Advanced · about 12 hours · difficulty 5/5
Learn first: DP on Sequences and Strings, Binary Trees and Traversals, Bit Manipulation
Once 1D, 2D and sequence DP feel natural, these patterns unlock most remaining "hard" DP problems. They are optional for mass-recruiter placements but valuable for top product companies and contests.
Interval DP
State dp[l][r] = best answer for the subarray from l to r. Transition tries every split point k in between. Fill by increasing interval length. Classics: Matrix Chain Multiplication, Burst Balloons, Minimum Cost to Cut a Stick, Palindrome Partitioning II. Complexity is usually O(n^3).
DP on trees
Compute a value for each node from its children in a post-order DFS. Often the state has two flavours, like "node taken / not taken": House Robber III, maximum independent set, tree diameter, and binary tree cameras. Rerooting computes an answer for every possible root in O(n) with two passes (Sum of Distances in Tree).
Bitmask DP
When n <= 20, represent the set of used items as a mask. State dp[mask][i] might mean "visited set mask, currently at i", which solves travelling salesman in O(2^n * n^2). Other examples: assigning tasks to people, Partition to K Equal Sum Subsets, Shortest Path Visiting All Nodes.
Digit DP
Count numbers in [L, R] with a digit property by walking digits with a "tight" flag. Appears mainly in contests.
Tip: the transition for these problems is rarely obvious. Write the brute-force recursion first and let the parameters of that recursion become your state.
Key concepts
- Interval DP and split points
- Matrix chain multiplication
- DP on trees with post-order
- Rerooting technique
- Bitmask DP over subsets
- Travelling salesman DP
- Digit DP
Mini project
Solve 8 problems: Burst Balloons, Minimum Cost to Cut a Stick, Palindrome Partitioning II, House Robber III, Binary Tree Cameras, Partition to K Equal Sum Subsets, Shortest Path Visiting All Nodes, and CSES Counting Tilings or Sum of Distances in Tree.
Check yourself
In Burst Balloons, why is it easier to choose the balloon burst LAST in an interval rather than first?
Free resources
- USACO Guide: Gold DP modules (USACO Guide)
- Competitive Programmer's Handbook (Ch. 7, 10, 14) (CSES)
- DP on broken profile and bitmasks (cp-algorithms)