Part 11•Chapter 6 of 9•Advanced
Dynamic Programming Master Class (60 Problems)
60 classical DP problems: 0/1 Knapsack, Unbounded Knapsack, LCS, LIS, Matrix Chain Multiplication, and Digit DP.
~23 min read
4,425 words
8 Sections
Reviewed & Verified (2024 Syllabus)
60 Solved Problems0/1 Knapsack VariantsLongest Common Subsequence
Optimal substructure and overlapping subproblems allow dynamic programming to solve intractable combinatorial explosions in polynomial time. This volume compiles 60 benchmark interview problems spanning 1D linear recurrences, 2D grid pathing, knapsack variations, sequence alignments, interval partitions, and advanced tree and digit state formulations.
1. Executive Summary & Learning Objectives
#This problem bank codifies 60 essential dynamic programming challenges classified by structural state formulation and topological iteration direction.
By completing this problem set, you will be able to:
- Define Multi-Dimensional States: Isolate independent state parameters capturing prefix decisions, remaining capacities, and boundary constraints.
- Execute Space Compression: Compress 2D state matrices into 1D rolling buffers using directional iteration to preserve single-use invariants.
- Formulate String & Sequence Alignments: Solve Longest Common Subsequence, Edit Distance, and Interleaving Strings in time.
- Architect Non-Linear DP Systems: Formulate Interval DP for matrix chains, Bitmask DP for permutation graphs, and Postorder Tree DP for hierarchical node monitoring.
- Construct Digit DP Solvers: Count constrained integers using position, tight-bound, and leading-zero state flags in logarithmic digit steps.
2. Problem Taxonomy & Architecture Guide
#| Section | Problem Range | Primary Patterns Covered | Target Complexity Range |
|---|---|---|---|
| Section 1 | Q411 – Q420 | 1D DP, Linear Recurrences & State Machines | Time, to Space |
| Section 2 | Q421 – Q440 | 2D Grid DP & Knapsack Archetypes (0/1 & Unbounded) | or Time, Space |
| Section 3 | Q441 – Q455 | String Alignments, LCS & Edit Distance | Time, Space |
| Section 4 | Q456 – Q470 | Interval DP, Bitmask DP, Tree DP & Digit DP | to Time, Exponential to Polynomial Space |
Section 1: 1D DP & Linear Recurrences (Q411 – Q420)
#Q411: Climbing Stairs
- Difficulty:
[Easy]| Pattern:[Fibonacci 1D DP] - Statement: Distinct ways to climb steps taking 1 or 2 steps at a time.
- Optimal Approach: . Maintain two rolling variables
aandb. - Complexity: Time: | Space:
- Edge Cases: .
Q412: Min Cost Climbing Stairs
- Difficulty:
[Easy]| Pattern:[Rolling Cost DP] - Statement: Pay
cost[i]to step on stair ; climb 1 or 2 steps. Reach top minimizing cost. - Optimal Approach: . Rolling two variables.
- Complexity: Time: | Space:
- Edge Cases: Length 2 (pay ).
Q413: House Robber
- Difficulty:
[Medium]| Pattern:[State Machine / Non-Adjacent DP] - Statement: Max money to rob without robbing two adjacent houses.
- Optimal Approach: . Rolling variables
robPrev1androbPrev2. - Complexity: Time: | Space:
- Edge Cases: Single house, two houses.
Q414: House Robber II
- Difficulty:
[Medium]| Pattern:[Circular Reduction to Linear DP] - Statement: Houses arranged in a circle (house 0 is adjacent to house ).
- Optimal Approach: .
- Complexity: Time: | Space:
- Edge Cases: Single house (return
nums[0]).
Q415: House Robber III
- Difficulty:
[Medium]| Pattern:[Tree DP Dual State] - Statement: Houses form a binary tree. Adjacent linked nodes cannot be robbed.
- Optimal Approach: Postorder helper returns pair
(robRoot, skipRoot).robRoot = val + left.skip + right.skip.skipRoot = max(left.rob, left.skip) + max(right.rob, right.skip). - Complexity: Time: | Space:
- Edge Cases: Empty tree (returns
(0, 0)).
Q416: Decode Ways
- Difficulty:
[Medium]| Pattern:[1D DP with Valid Digit Substrings] - Statement: Count ways to decode string mapped by .
- Optimal Approach: represents ways for prefix . Add if single digit ; add if two digits .
- Complexity: Time: | Space: rolling
- Edge Cases: Leading zero
"06"(cannot decode, returns 0).
Q417: Word Break
- Difficulty:
[Medium]| Pattern:[1D Boolean Prefix DP] - Statement: Determine if string can be segmented into space-separated dictionary words.
- Optimal Approach: if there exists where and .
- Complexity: Time: | Space:
- Edge Cases: Single letter words, no valid segmentation.
Q418: Word Break II
- Difficulty:
[Hard]| Pattern:[Memoized DFS Backtracking] - Statement: Return all possible sentence segmentations using dictionary words.
- Optimal Approach: Memoized DFS returning list of sentences for each suffix. Loop over prefix words in dictionary, recurse on remainder.
- Complexity: Time: worst case | Space:
- Edge Cases: Impossible string (memoized check prunes early).
Q419: Coin Change
- Difficulty:
[Medium]| Pattern:[Unbounded Knapsack Min Cost] - Statement: Find fewest coins needed to make up
amount. - Optimal Approach: with . Initialize array with .
- Complexity: Time: | Space:
- Edge Cases: Amount 0 (returns 0), impossible amount (returns ).
Q420: Coin Change II
- Difficulty:
[Medium]| Pattern:[Unbounded Knapsack Combination Count] - Statement: Count number of combinations that make up
amount. - Optimal Approach: Outer loop over each coin , inner loop over amount from to
amount: . (Coin in outer loop ensures combinations, not permutations!). - Complexity: Time: | Space:
- Edge Cases: Amount 0 (1 combination: empty set).
Section 2: 2D Grid DP & Matrix Paths (Q421 – Q430)
#Q421: Unique Paths
- Difficulty:
[Medium]| Pattern:[Grid DP / Combinatorics] - Statement: Count paths from top-left to bottom-right moving only right or down.
- Optimal Approach: . Space optimized to 1D array of size . Or combinatorics .
- Complexity: Time: | Space:
- Edge Cases: or (1 path).
Q422: Unique Paths II
- Difficulty:
[Medium]| Pattern:[Grid DP with Obstacles] - Statement: Count unique paths avoiding cells with obstacle 1.
- Optimal Approach: If , ; else .
- Complexity: Time: | Space:
- Edge Cases: Start or end cell has obstacle (returns 0).
Q423: Minimum Path Sum
- Difficulty:
[Medium]| Pattern:[2D Grid Min DP] - Statement: Find path from top-left to bottom-right minimizing sum of numbers along path.
- Optimal Approach: . Compress to 1D array.
- Complexity: Time: | Space:
- Edge Cases: Single row or single column matrix.
Q424: Triangle
- Difficulty:
[Medium]| Pattern:[Bottom-Up Triangle DP] - Statement: Find minimum path sum from top to bottom of triangle.
- Optimal Approach: Bottom-up from second-to-last row up to apex: . Result is .
- Complexity: Time: | Space: in-place
- Edge Cases: Triangle with 1 row.
Q425: Dungeon Game
- Difficulty:
[Hard]| Pattern:[Bottom-Right to Top-Left Reverse DP] - Statement: Find minimum initial health required for knight to reach princess.
- Optimal Approach: Reverse DP from princess back to . Health needed to exit cell is . Health needed to enter cell is .
- Complexity: Time: | Space:
- Edge Cases: Large positive demon or magic cells.
Q426: Cherry Pickup
- Difficulty:
[Hard]| Pattern:[Dual Simultaneous Paths DP] - Statement: Collect cherries from to and back to .
- Optimal Approach: Equivalent to two people walking from to simultaneously! At step , state is . Add cherries once if .
- Complexity: Time: | Space:
- Edge Cases: No path exists (blocked by ).
Q427: Cherry Pickup II
- Difficulty:
[Hard]| Pattern:[3D Grid DP (Two Robots)] - Statement: Two robots start at and moving down. Maximize cherries.
- Optimal Approach: State row-by-row. Try all combinations of moves for . Add cells once if .
- Complexity: Time: | Space:
- Edge Cases: Both robots land on same cell.
Q428: Maximal Square
- Difficulty:
[Medium]| Pattern:[Min of 3 Neighbors DP] - Statement: Find largest square of 1s in binary matrix; return area.
- Optimal Approach: If , . Result is .
- Complexity: Time: | Space:
- Edge Cases: Matrix of all 0s.
Q429: Minimum Falling Path Sum
- Difficulty:
[Medium]| Pattern:[Row-by-Row 3-Direction DP] - Statement: Find falling path from top to bottom picking directly below or diagonally adjacent cells.
- Optimal Approach: .
- Complexity: Time: | Space:
- Edge Cases: Negative numbers.
Q430: Out of Boundary Paths
- Difficulty:
[Medium]| Pattern:[3D State DP with Modulo] - Statement: Count paths to move ball off grid in at most moves.
- Optimal Approach: State for moves remaining. For boundary steps, add 1 to count; for interior steps, sum over 4 directions.
- Complexity: Time: | Space:
- Edge Cases: .
Section 3: Knapsack & Subsets (Q431 – Q440)
#Q431: 0/1 Knapsack Classical
- Difficulty:
[Medium]| Pattern:[0/1 Knapsack 1D Reverse Walk] - Statement: Maximize value under weight capacity where each item can be chosen at most once.
- Optimal Approach: Reverse 1D DP array from down to : .
- Complexity: Time: | Space:
- Edge Cases: Item weight exceeds capacity.
Q432: Partition Equal Subset Sum
- Difficulty:
[Medium]| Pattern:[0/1 Knapsack Target Sum/2] - Statement: Check if array can be partitioned into two subsets with equal sum.
- Optimal Approach: Total sum must be even; target . Boolean 1D DP: traversing down to .
- Complexity: Time: | Space:
- Edge Cases: Total sum is odd (immediately false).
Q433: Target Sum
- Difficulty:
[Medium]| Pattern:[Subset Sum Reduction] - Statement: Assign or to each element so sum equals .
- Optimal Approach: Let be positive subset, negative. and . Reduces to Subset Sum!
- Complexity: Time: | Space:
- Edge Cases: is odd or .
Q434: Ones and Zeroes
- Difficulty:
[Medium]| Pattern:[2D Knapsack Reverse Walk] - Statement: Maximize strings formed using at most 0s and 1s.
- Optimal Approach: 2D array reverse walked from down to and down to : .
- Complexity: Time: | Space:
- Edge Cases: Single string uses all capacity.
Q435: Last Stone Weight II
- Difficulty:
[Medium]| Pattern:[Subset Sum Nearest Half] - Statement: Smash stones together; minimize final stone weight.
- Optimal Approach: Find subset sum closest to . Result is .
- Complexity: Time: | Space:
- Edge Cases: Array with 1 stone.
Q436: Combination Sum IV
- Difficulty:
[Medium]| Pattern:[Permutations 1D DP] - Statement: Find number of sequences summing to target (different orders counted as different combinations).
- Optimal Approach: Target in outer loop, numbers in inner loop: for all .
- Complexity: Time: | Space:
- Edge Cases: 32-bit integer overflow during addition.
Q437: Unbounded Knapsack
- Difficulty:
[Medium]| Pattern:[Unbounded Knapsack Forward Walk] - Statement: Maximize value with unlimited supply of each item under capacity .
- Optimal Approach: Forward walk from to : .
- Complexity: Time: | Space:
- Edge Cases: .
Q438: Rod Cutting Problem
- Difficulty:
[Medium]| Pattern:[Unbounded Knapsack] - Statement: Cut rod of length into pieces maximizing total revenue.
- Optimal Approach: .
- Complexity: Time: | Space:
- Edge Cases: Rod of length 0.
Q439: Perfect Squares
- Difficulty:
[Medium]| Pattern:[Unbounded Knapsack Min Coins] - Statement: Find least number of perfect square numbers summing to .
- Optimal Approach: . Or Lagrange's Four-Square Theorem in time!
- Complexity: Time: | Space:
- Edge Cases: is already a perfect square (returns 1).
Q440: Integer Break
- Difficulty:
[Medium]| Pattern:[Math / 1D DP] - Statement: Break integer into sum of positive integers maximizing product.
- Optimal Approach: . (Greedy math: break into as many 3s as possible!).
- Complexity: Time: or math | Space:
- Edge Cases: (break ), (break ).
Section 4: Strings & Sequence DP (Q441 – Q455)
#Q441: Longest Common Subsequence (LCS)
- Difficulty:
[Medium]| Pattern:[2D String Alignment DP] - Statement: Find length of longest common subsequence between and .
- Optimal Approach: If , ; else .
- Complexity: Time: | Space:
- Edge Cases: No common characters (returns 0).
Q442: Longest Increasing Subsequence (LIS)
- Difficulty:
[Medium]| Pattern:[Patience Sorting with BS] - Statement: Find length of strictly increasing subsequence.
- Optimal Approach: Binary search
lower_boundon tails array. If element all tails, append; else overwrite first element . - Complexity: Time: | Space:
- Edge Cases: Strictly decreasing array (length 1).
Q443: Edit Distance
- Difficulty:
[Medium]| Pattern:[Levenshtein Distance 2D DP] - Statement: Minimum operations (insert, delete, replace) to convert to .
- Optimal Approach: If , . Else .
- Complexity: Time: | Space:
- Edge Cases: One word is empty string (return length of other word).
Q444: Distinct Subsequences
- Difficulty:
[Hard]| Pattern:[2D Matching Count DP] - Statement: Count distinct subsequences of that equal .
- Optimal Approach: If , (reverse walk 1D array).
- Complexity: Time: | Space:
- Edge Cases: (returns 0).
Q445: Wildcard Matching
- Difficulty:
[Hard]| Pattern:[2D DP / Greedy Two Pointers] - Statement: Match string against pattern with
?(any single char) and*(any sequence). - Optimal Approach: Two pointers tracking last
*position. Or 2D DP: if , . - Complexity: Time: average | Space:
- Edge Cases: Pattern composed entirely of
***.
Q446: Regular Expression Matching
- Difficulty:
[Hard]| Pattern:[2D DP with Kleene Star] - Statement: Match string with
.(any char) and*(zero or more of preceding char). - Optimal Approach: For
c*: (zero copies) (one or more copies). - Complexity: Time: | Space:
- Edge Cases: Pattern
"a*b*c*"matching empty string"".
Q447: Interleaving String
- Difficulty:
[Medium]| Pattern:[2D Boolean Grid DP] - Statement: Check if is formed by interleaving and .
- Optimal Approach: .
- Complexity: Time: | Space:
- Edge Cases: (immediately false).
Q448: Shortest Common Supersequence
- Difficulty:
[Hard]| Pattern:[LCS Table Backtracking] - Statement: Find shortest string that has both and as subsequences.
- Optimal Approach: Build LCS table. Backtrack from : if characters match, take once; else take character corresponding to the max DP branch.
- Complexity: Time: | Space:
- Edge Cases: One string is a substring of the other.
Q449: Minimum ASCII Delete Sum for Two Strings
- Difficulty:
[Medium]| Pattern:[LCS Maximum ASCII Keep] - Statement: Delete characters to make two strings equal minimizing ASCII sum of deleted chars.
- Optimal Approach: Equivalent to maximizing the ASCII sum of the Common Subsequence!
- Complexity: Time: | Space:
- Edge Cases: No common characters.
Q450: Longest Palindromic Subsequence
- Difficulty:
[Medium]| Pattern:[Interval DP / LCS with Reversed String] - Statement: Find length of longest palindromic subsequence in .
- Optimal Approach: If , ; else .
- Complexity: Time: | Space:
- Edge Cases: Single character (length 1).
Q451: Palindrome Partitioning II
- Difficulty:
[Hard]| Pattern:[1D DP + Palindrome Expand] - Statement: Minimum cuts needed for palindrome partitioning of .
- Optimal Approach: Precompute palindromic substrings. .
- Complexity: Time: | Space:
- Edge Cases: String already a palindrome (0 cuts).
Q452: Count Different Palindromic Subsequences
- Difficulty:
[Hard]| Pattern:[Interval DP with 4-Character Alphabets] - Statement: Count non-empty distinct palindromic subsequences modulo .
- Optimal Approach: for interval . If , handle interior occurrences of character .
- Complexity: Time: | Space:
- Edge Cases: Duplicate subsequences avoided.
Q453: Number of Longest Increasing Subsequences
- Difficulty:
[Medium]| Pattern:[Dual DP (Length & Count)] - Statement: Count total number of longest increasing subsequences.
- Optimal Approach: Maintain
len[i]andcount[i]. When : if , update length and copy count; if equal, add count. - Complexity: Time: | Space:
- Edge Cases: All elements identical.
Q454: Longest String Chain
- Difficulty:
[Medium]| Pattern:[Hash Map DP + String Deletion] - Statement: Find longest word chain where each word is formed by adding 1 letter to predecessor.
- Optimal Approach: Sort words by length. Map stores
{word: maxChain}. For each word, generate all predecessors by deleting 1 char; query map. - Complexity: Time: | Space:
- Edge Cases: Words with length 1.
Q455: Maximum Length of Pair Chain
- Difficulty:
[Medium]| Pattern:[Interval Greedy / LIS] - Statement: Longest chain of pairs where next pair starts .
- Optimal Approach: Sort pairs by second element (greedy activity selection). Greedily pick next pair starting .
- Complexity: Time: | Space:
- Edge Cases: Overlapping intervals.
Section 5: Interval, Bitmask & Tree DP (Q456 – Q470)
#Q456: Matrix Chain Multiplication (MCM)
- Difficulty:
[Hard]| Pattern:[Interval DP Split Search] - Statement: Find minimum scalar multiplications to multiply chain of matrices.
- Optimal Approach: . Loop on chain length .
- Complexity: Time: | Space:
- Edge Cases: Chain of 1 matrix (0 multiplications).
Q457: Burst Balloons
- Difficulty:
[Hard]| Pattern:[Interval DP Last Burst Element] - Statement: Burst balloons for coins: bursting gives .
- Optimal Approach: Think backwards: which balloon is burst LAST in interval ? .
- Complexity: Time: | Space:
- Edge Cases: Single balloon.
Q458: Minimum Cost to Merge Stones
- Difficulty:
[Hard]| Pattern:[Interval DP with K Parts] - Statement: Merge consecutive piles of stones until 1 pile remains. Minimize cost.
- Optimal Approach: Valid iff . maintains cost to merge subarray .
- Complexity: Time: | Space:
- Edge Cases: Impossible configurations (returns ).
Q459: Remove Boxes
- Difficulty:
[Hard]| Pattern:[3D Interval DP with Suffix Match Count] - Statement: Remove contiguous boxes of same color; boxes gives points. Maximize score.
- Optimal Approach: State : max points from where has adjacent boxes of same color following it.
- Complexity: Time: | Space:
- Edge Cases: All boxes same color.
Q460: Strange Printer
- Difficulty:
[Hard]| Pattern:[Interval DP Match Collapse] - Statement: Printer prints sequence of same characters at once. Find minimum turns to print string.
- Optimal Approach: . If for some , .
- Complexity: Time: | Space:
- Edge Cases: Repeated characters (collapse consecutive identical chars).
Q461: Can I Win
- Difficulty:
[Medium]| Pattern:[Minimax Game Theory + Bitmask DP] - Statement: Pick integers without replacement; first to make running total wins.
- Optimal Approach: Memoized DFS on
(usedMask, remainingTotal). If choosing makes remaining OR opponent cannot win on next state, current player wins! - Complexity: Time: | Space:
- Edge Cases: (impossible to win, returns
false).
Q462: Partition to K Equal Sum Subsets
- Difficulty:
[Medium]| Pattern:[Bitmask DP / Backtracking Pruning] - Statement: Partition array into subsets of equal sum.
- Optimal Approach: Sort descending. Backtrack filling buckets, or Bitmask DP state storing current bucket remainder.
- Complexity: Time: | Space:
- Edge Cases: Total sum not divisible by .
Q463: Matchsticks to Square
- Difficulty:
[Medium]| Pattern:[4-Subset Partitioning Bitmask DP] - Statement: Form square using all matchsticks without breaking.
- Optimal Approach: Equivalent to Partition to Equal Subsets with and side .
- Complexity: Time: pruned to | Space:
- Edge Cases: Single matchstick larger than side length.
Q464: Shortest Path Visiting All Nodes
- Difficulty:
[Hard]| Pattern:[Bitmask BFS State Space] - Statement: Shortest path visiting every node in undirected graph.
- Optimal Approach: BFS state
(node, mask). Pop and visit all neighbors withnextMask = mask | (1 << neighbor). - Complexity: Time: | Space:
- Edge Cases: (0 steps).
Q465: Find the Shortest Superstring (Traveling Salesman Problem)
- Difficulty:
[Hard]| Pattern:[TSP Bitmask DP with Overlap Costs] - Statement: Shortest string containing all words in dictionary as substrings.
- Optimal Approach: Precompute pairwise string overlaps. TSP on directed graph: storing maximum overlap. Reconstruct string from path.
- Complexity: Time: | Space:
- Edge Cases: One word completely contained within another.
Q466: Smallest Sufficient Team
- Difficulty:
[Hard]| Pattern:[Bitmask DP Set Cover] - Statement: Form smallest team possessing all required skills.
- Optimal Approach: Map each skill to bit. stores list of people forming skill mask. For each person, .
- Complexity: Time: | Space:
- Edge Cases: Single person possesses all skills.
Q467: Maximum Students Taking Exam
- Difficulty:
[Hard]| Pattern:[Bitmask DP on Grid Rows] - Statement: Seat students so no one can see neighbors (left, right, upper diagonals).
- Optimal Approach: State . Mask valid if no adjacent 1s and no student on broken seat. Transition ensures no diagonal cheating from previous row mask.
- Complexity: Time: | Space:
- Edge Cases: All seats broken.
Q468: Binary Tree Cameras
- Difficulty:
[Hard]| Pattern:[Tree DP 3-State Greedy] - Statement: Place minimum cameras on nodes so every node is monitored.
- Optimal Approach: Postorder DFS returning state: 0 = unmonitored, 1 = has camera, 2 = covered. If either child is 0, must place camera (state 1). If either child has camera, covered (state 2).
- Complexity: Time: | Space:
- Edge Cases: Root remains unmonitored at end (must place camera at root).
Q469: Distribute Coins in Binary Tree
- Difficulty:
[Medium]| Pattern:[Tree DP Net Balance Postorder] - Statement: Move coins between adjacent nodes so every node has exactly 1 coin. Minimize moves.
- Optimal Approach: Postorder DFS returns net coin balance:
node.val + leftBalance + rightBalance - 1. Total moves accumulates . - Complexity: Time: | Space:
- Edge Cases: All coins located in single node.
Q470: Numbers At Most N Given Digit Set (Digit DP)
- Difficulty:
[Hard]| Pattern:[Digit DP with Tight & Leading Zeroes] - Statement: Count positive integers written using only digits from given set.
- Optimal Approach: Count numbers with strictly fewer digits than (). For numbers with same length, match digits with tight constraint.
- Complexity: Time: | Space:
- Edge Cases: Digit set does not contain any valid matching digit.
References & Academic Attribution
#- Skiena, S. S. (2020). The Algorithm Design Manual (3rd ed.). Springer.
- Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. (2022). Introduction to Algorithms (4th ed.). MIT Press.
- USA Computing Olympiad (USACO) & CP-Algorithms Archives (2024). Curated Competitive Programming and Algorithm Verification Standards.