Interval DP, DP on Trees and Bitmask DP
Handle the harder DP families that appear in top product-company rounds: partition and interval DP, DP on trees and bitmask DP.
Advanced · about 8 hours · difficulty 5/5
Learn first: DP on Subsequences and Strings: LIS, LCS, Edit Distance, Tree Problem Patterns
These families separate strong candidates in top product-company interviews. Learn them after the classic DPs feel easy.
Interval (partition) DP
State is a range (i, j); try every split point k inside it. Usually O(n^3).
- Matrix Chain Multiplication (the template).
- Minimum Cost to Cut a Stick, Burst Balloons (think of the last balloon burst), Palindrome Partitioning II, Boolean Parenthesization (Evaluate expression to true), Partition Array for Maximum Sum.
DP on trees
Compute answers bottom-up with DFS, often returning a pair (take node, skip node).
- House Robber III, Binary Tree Cameras, Maximum Path Sum (revisited), tree diameter.
- Rerooting: compute an answer for every node as root in O(n) (Sum of Distances in Tree).
DP on grids, revisited
Longest Increasing Path in a Matrix is DFS plus memo on a grid with no fixed direction.
Bitmask DP
When n is up to about 20, a mask can represent the set of chosen items.
- Travelling Salesman (dp[mask][last]), Shortest Path Visiting All Nodes (BFS over (node, mask)), Partition to K Equal Sum Subsets, assignment problems.
Pitfalls
- In Burst Balloons, choosing the first balloon to burst instead of the last makes subproblems dependent.
- Memory blow-up in bitmask DP: 2^20 x 20 ints is about 80 MB.
You are ready to move on when you can write Matrix Chain Multiplication from the recurrence and explain why Burst Balloons picks the last balloon.
Key concepts
- Matrix chain multiplication
- Partition DP over ranges
- Burst Balloons
- DP on trees
- Rerooting
- Memoised DFS on grids
- Bitmask DP
Mini project
Solve these 8 in 10 days, log time and pattern: Matrix Chain Multiplication (GfG), Minimum Cost to Cut a Stick, Palindrome Partitioning II, Burst Balloons, Partition Array for Maximum Sum, House Robber III, Longest Increasing Path in a Matrix, Shortest Path Visiting All Nodes.
Check yourself
What is the state and transition for Matrix Chain Multiplication, and what is its time complexity?
Free resources
- takeUforward DP series (takeUforward)
- AtCoder Educational DP Contest (AtCoder)
- USACO Guide (USACO Guide)