Dp is nothing but modification on top of recursion
How to solve DP questions
Create recursion solution [ if choice at each instance then recursion]
memoize it
[ if the problems overlapping then memoize it, or when we have max,min,longest, largest things to find]
storing the recurive calls
Find out the recursive function and get values which are changing all the time and try to store them in an array or 2-d array
then in between the base condition and the choice digram we will check if that value is present in the array if not then we will store it in the array
ex— for 0-1 knap sack w and h
How to solve recursion problem
then find a base condition
to write the base condition think of the smallest valid input
then make sure for each recursive call the input size is getting reduced
Clear, Concise, pattern-wise summary of important Dynamic Programming (DP) patterns along with a short intro and similar problems you can practice under each category.
1. 0/1 Knapsack Pattern
Used when you must choose items under some constraint (usually weight, time, cost), and each item can be taken at most once.
The DP is usually of the form:
dp[i][w] = best value using first i items and capacity w.
Similar Problems
Partition Equal Subset Sum
Count Subsets with Given Sum
Minimum Subset Sum Difference
Rod Cutting (bounded version)
Assignments with constraints where you either take or skip an item
2. Unbounded Knapsack Pattern
Same as knapsack except you can take an item unlimited times.
Often solved with 1D DP where you iterate capacities first.
Similar Problems
Minimum Cost for Tickets (if unlimited passes allowed)
Brick stacking / tiling with infinite tiles
3. Fibonacci / Simple Recurrence DP
Problems that follow a simple recurrence like:
dp[n] = dp[n-1] + dp[n-2].
Mostly single-dimensional DP with overlapping subproblems.
Similar Problems
Minimum/Maximum Jumps to Reach End
Decode Ways (number of ways to decode string)
Tiling Problems (2xn tiling)
Counting paths with step constraints
4. LCS (Longest Common Subsequence) Pattern
DP on two strings where you compare characters at i and j.
Usually dp[i][j] means: result for first i chars of A and first j chars of B.
Similar Problems
Longest Palindromic Subsequence
Shortest Common Supersequence
Delete Operations for Two Strings
Regular Expression Matching
5. LIS (Longest Increasing Subsequence) Pattern
Sequential DP where for each index you look at previous indices.
Optimizable using binary search (O(n log n)).
Similar Problems
Maximum Sum Increasing Subsequence
Longest Bitonic Subsequence
6. Kadane’s Algorithm (Maximum Subarray)
A greedy + DP optimization to find maximum sum subarray in O(n).
DP relation:
dp[i] = max(arr[i], arr[i] + dp[i-1]).
Similar Problems
Maximum Circular Subarray Sum
Longest Subarray With Sum K (sliding window, but related)
Maximum Absolute Subarray Sum
Best Time to Buy and Sell Stock (variations use Kadane ideas)
Maximum Sum Rectangle in 2D Matrix (Kadane inside)
7. Matrix Chain Multiplication (MCM
DP for partitioning problems where order matters.
Common pattern:
dp[i][j] = min over k (dp[i][k] + dp[k+1][j] + cost).
Similar Problems
Minimum Score Triangulation
Evaluate to True (expression parsing)
Stick Cutting / Minimum Cost to Cut Stick
DP where the structure is a tree, solved using DFS post-order traversal.
State is often:
dp[node] depends on children.
Similar Problems
Maximum Path Sum in Binary Tree
Tree DP with states (e.g., “Rob houses in a tree”)
DP on subtree sizes, number of ways, distances
Distribute Coins in a Binary Tree
9. DP on Graphs
DP on DAGs or weighted graphs using longest/shortest path DP.
Requires topological ordering to ensure dependencies.
Similar Problems
Shortest Path in DAG (DP-like)
DP on bitmasking over graph (e.g., Travelling Salesman Problem)
Hamiltonian Path / Cycle variations
Counting walks of length K
DP with graph transitions (Markov-like)
10. Other Important DP Patterns
Used when state depends on subsets.
Similar Problems
Traveling Salesman Problem (TSP)
Maximum Compatibility of Students
Assignments / matching problems
Counting numbers with constraints.
Similar Problems
Count numbers with digit sum
Count numbers without consecutive digits
Same as MCM but without explicit matrix context.
Similar Problems
Classic 2D DP.
Problems
How to solve DP problems
Choice at each strep - Recursion
100+ Dynamic Programming Problems — Grouped by Patterns
1. Fibonacci / Simple Recurrence DP
Core idea: dp[n] depends on dp[n−1], dp[n−2], …
N-th Stair Problem (taking 1, 2, or 3 steps)
Number of Ways to Reach Destination (hop 1 or 2 or 3)
Tiling With 2×1 and 2×2 tiles
Count Balanced Parentheses (Catalan DP)
Number of Binary Trees with N nodes
2. 0/1 Knapsack Pattern
Core idea: pick or skip, finite items.
Partition Equal Subset Sum
Minimum Subset Sum Difference
Count Subsets With Given Sum
Assign Tasks With Constraints
Students–Exam Assignment (take/not take)
Pick Movies/Songs With Time Limit
3. Unbounded Knapsack Pattern
Core idea: pick item unlimited times.
Coin Change (Number of Ways)
Coin Change (Minimum Coins)
Perfect Squares (Min count)
Tiling M×N Wall (infinite bricks)
Minimum Cost for Train Tickets
Word Break (unbounded dictionary)
4. Longest Increasing Sequence (LIS) Pattern
dp[i] = best answer ending at i.
Maximum Sum Increasing Subsequence
Longest Bitonic Subsequence
Minimum Deletions to Make Array Sorted
Minimum Number of Removals to Make Mountain Array
5. Longest Common Subsequence (LCS) Pattern
Compare characters of two sequences.
Shortest Common Supersequence
Min Insertions to Make String Palindrome
Longest Palindromic Subsequence
Delete Operation for Two Strings
Regular Expression Matching (DP)
Minimum Window Subsequence
6. Kadane’s Algorithm Style DP
dp[i] = max(arr[i], arr[i] + dp[i-1]).
Maximum Circular Subarray Sum
Max Sum of Non-Adjacent Elements (Kadane variant)
Best Time to Buy and Sell Stock I
Best Time to Buy and Sell Stock II
Best Time to Buy and Sell Stock III
Best Time to Buy and Sell Stock IV
Maximum Subarray After One Deletion
Maximum Sum Rectangle in Matrix (Kadane inside)
7. Matrix Chain Multiplication (MCM) Pattern
Interval DP — recursively break into left + right partitions.
Matrix Chain Multiplication
Palindrome Partitioning (min cuts)
Minimum Palindromic Partitioning II
Evaluate Expression for True
Minimum Score Triangulation of Polygon
Stick Cutting / Minimum Cost to Cut a Stick
Scrambled String Verification
Use DFS and compute dp from children.
Maximum Path Sum in Binary Tree
Sum of Root-to-Leaf Paths
DP on Tree: Height, Depth, Parent
Distribute Coins in Binary Tree
Maximum Independent Set in Tree
Minimum Vertex Cover (trees)
9. DP on Graphs (DAG DP + Paths)
Topological order DP.
Number of Paths in Grid With Obstacles
Counting Paths in Directed Acyclic Graph
Hamiltonian Path with Bitmask DP
Traveling Salesman Problem (TSP)
DP for Weighted DAG path counting
Word Ladder II (DP on graph levels)
Cherry Pickup (graph-like transitions)
Minimum Cost to Travel Between Cities (DAG DP variant)
10. Grid DP (2D DP)
✔ State represented by subsets.
Traveling Salesman Problem
Maximum Compatibility of Students
Partition to K Equal Sum Subsets
Sudoku Solvers using bitmask DP
Count Ways to Visit All Nodes (state compression DP)
✔ Count numbers with certain digit patterns.
Count numbers ≤ N with digit sum K
Count numbers with no consecutive digits
Count numbers divisible by X
Count numbers with limited set of digits
13. Probability DP
✔ DP on outcomes of events.
Dice Throw (ways to get sum)
Probability of Winning a Game
Knight Probability on Chessboard
Number of Ways to Reach Target Score
14. Game Theory DP
Removing Stones (Nim-like DP)
15. Interval Scheduling / Segmented DP
✔ DP on intervals sorted by start time.
Maximum Profit in Job Scheduling
Interval DP for merging intervals
16. Advanced Patterns
(Rare but very powerful)
DP + Greedy hybrid (e.g., scheduling + DP)
DP + Prefix Sum optimisation
DP + Monotonic Queue Optimisation
DP + Binary Lifting (tree DP optimisation)
DP + Divide and Conquer Optimisation
Batch 1 — Full solutions (20 problems covering main DP patterns)
Each solution includes: short statement, DP idea (state + recurrence), Python implementation, complexity, and a tiny test.
1) Fibonacci Numbers
Problem: Compute F(n) (0-indexed: F(0)=0, F(1)=1).
DP idea: simple recurrence F(n)=F(n-1)+F(n-2). Use iterative O(1) space.
Time: O(n), Space: O(1).
2) Climbing Stairs
Problem: Number ways to reach n-th stair taking 1 or 2 steps.
DP idea: dp[i] = dp[i-1] + dp[i-2].
Time: O(n), Space: O(1).
3) Min Cost Climbing Stairs
Problem: Given cost[i], min cost to reach top (can start at 0 or 1).
DP idea: dp[i] = cost[i] + min(dp[i-1], dp[i-2]). Answer = min(dp[n-1], dp[n-2]) (or optimized).
Time: O(n), Space: O(1).
4) House Robber
Problem: Max sum of non-adjacent elements.
DP idea: dp[i] = max(dp[i-1], dp[i-2] + nums[i]).
Time: O(n), Space: O(1).
Problem: Count ways to decode digits -> letters (1->A … 26->Z).
DP idea: dp[i] = dp[i-1] if single valid + dp[i-2] if two-digit valid.
Time: O(n), Space: O(1).
6) 0/1 Knapsack (classic)
Problem: Given weights w[i] and values v[i], capacity W, maximize value picking each item at most once.
DP idea: dp[w] = max(dp[w], dp[w-wi] + vi) iterating items then capacity (reverse capacity to avoid reuse).
Time: O(nW), Space: O(W).
7) Subset Sum (decision)
Problem: Given nums and target sum S, is subset sum S possible?
DP idea: 1D boolean dp: dp[s] |= dp[s - num].
Time: O(nS), Space: O(S).
8) Coin Change — Minimum Coins (Unbounded Knapsack)
Problem: Given coins, min # coins to make amount.
DP idea: dp[a] = min(dp[a], dp[a-coin] + 1).
Time: O(amount * len(coins)). Space: O(amount).
9) Coin Change — Number of Ways (combinations)
Problem: Count ways to make amount (order doesn’t matter).
DP idea: iterate coins outer, amount inner (unbounded).
Time/Space: O(amount * len(coins)), O(amount).
10) Longest Increasing Subsequence (LIS) — O(n log n)
Problem: Length of LIS in array.
DP idea: patience sorting tails + binary search.
Time: O(n log n), Space: O(n).
11) Longest Common Subsequence (LCS)
Problem: LCS length of strings A,B.
DP idea: 2D dp dp[i][j] = dp[i-1][j-1]+1 if A[i-1]==B[j-1] else max(dp[i-1][j], dp[i][j-1]). Use rolling array for space.
Time: O(mn), Space: O(n).
12) Maximum Subarray (Kadane)
Problem: Max contiguous subarray sum.
DP idea: cur = max(a[i], cur + a[i]).
Time: O(n), Space: O(1).
13) Matrix Chain Multiplication (MCM)
Problem: Min cost to compute product of matrices with dimensions p0 x p1, p1 x p2,....
DP idea: interval DP dp[i][j] = min(dp[i][k] + dp[k+1][j] + p[i-1]*p[k]*p[j]).
Time: O(n^3), Space: O(n^2).
14) Palindrome Partitioning II (min cuts)
Problem: Min cuts to partition string into palindromic substrings.
DP idea: Precompute is_pal[i][j]. cuts[i] = min cuts for s[:i+1].
Time: O(n^2), Space: O(n^2).
15) House Robber on Tree
Problem: Max sum of nodes with no two adjacent (tree).
DP idea: DFS returns tuple (rob, not_rob) for each node.
Time: O(n), Space: O(h) recursion.
16) Longest Path in DAG
Problem: Longest path length in a DAG (weighted or unweighted).
DP idea: Topological sort then dp[v] = max(dp[u] + w(u->v)) over incoming edges.
Time: O(V+E), Space: O(V).
17) Traveling Salesman Problem (TSP) — Bitmask DP
Problem: Shortest Hamiltonian cycle visiting all nodes (small n).
DP idea: dp[mask][i] = min cost to reach i with visited mask. Transition: dp[mask|1<<j][j] = min(dp[mask][i] + cost[i][j]).
Time: O(n^2 * 2^n), Space: O(n * 2^n).
18) Unique Paths (Grid DP)
Problem: Number of ways from top-left to bottom-right moving only down/right.
DP idea: dp[i][j] = dp[i-1][j] + dp[i][j-1].
Time: O(mn), Space: O(n).
19) Weighted Job Scheduling (Interval DP)
Problem: Given jobs (start, end, profit), schedule non-overlapping jobs maximizing profit.
DP idea: Sort by end, dp[i] = max(dp[i-1], profit[i] + dp[p]) where p is last job ending before i (binary search).
Time: O(n log n), Space: O(n).
20) Digit DP — count numbers ≤ N with digit sum = S
Problem: Count non-negative integers ≤ N whose digits sum to S.
DP idea: classic digit DP: dp[pos][tight][sum]. I’ll implement memoized DFS.
Time: O(len(N) * 10 * S) roughly with memoization. Space: memo size.
21) Number of Longest Increasing Subsequences (count of LIS)
Problem: Count how many increasing subsequences achieve the LIS length.
DP idea: For each index i, track length[i] = length of LIS ending at i and count[i] = number of LIS ending at i. Update by scanning previous j < i.
Time: O(n²), Space: O(n).
22) Maximum Sum Increasing Subsequence (MSIS)
Problem: Find max-sum increasing subsequence.
DP idea: dp[i] = nums[i] + max(dp[j]) for j<i and nums[j] < nums[i].
Time: O(n²), Space: O(n).
23) Longest Bitonic Subsequence
Problem: Longest sequence which increases then decreases.
DP idea: Compute LIS ending at i and LIS from right (LDS) starting at i, combine.
Time: O(n²), Space: O(n).
24) Russian Doll Envelopes (LIS on pairs)
Problem: Max number of envelopes you can nest (w,h) — both strictly increasing.
DP idea: Sort by width asc and height desc for equal widths, then LIS on heights.
Time: O(n log n), Space: O(n).
25) Longest Common Substring
Problem: Longest contiguous substring appearing in both strings.
DP idea: dp[i][j] = dp[i-1][j-1]+1 if chars equal, else 0. Use rolling arrays.
Time: O(mn), Space: O(n).
26) Edit Distance (Levenshtein)
Problem: Minimum operations (insert/delete/replace) to convert a -> b.
DP idea: dp[i][j] = min(dp[i-1][j]+1, dp[i][j-1]+1, dp[i-1][j-1] + cost).
Time: O(mn), Space: O(n).
27) Shortest Common Supersequence (SCS) length
Problem: Shortest string that has both a and b as subsequences.
DP idea: len(SCS) = m + n - LCS(a,b).
Time: O(mn), Space: O(n).
28) Distinct Subsequences
Problem: Count ways s can form t as subsequence.
DP idea: dp[i][j] ways using s[:i] to form t[:j]. Optimize to 1D backwards.
Time: O(mn), Space: O(n).
29) Maximum Product Subarray
Problem: Max product of contiguous subarray (negatives flip sign).
DP idea: Track both max_ending_here and min_ending_here.
Time: O(n), Space: O(1).
30) Maximum Sum Rectangle in 2D Matrix
Problem: Max sum submatrix in 2D array.
DP idea: Fix top and bottom rows, collapse to 1D by summing columns, run Kadane.
Time: O(n² * m), Space: O(m).
31) Burst Balloons (MCM-like)
Problem: Max coins by bursting balloons; bursting order matters.
DP idea: Interval DP with dp[i][j] max coins bursting between i and j.
Time: O(n³), Space: O(n²).
32) Boolean Parenthesization (count ways to get True)
Problem: Count ways to parenthesize boolean expression to true.
DP idea: Interval DP tracking counts of true/false for each substring.
Time: O(n³), Space: O(n²).
33) Scramble String (interval DP with memo)
Problem: Check if s2 is scramble of s1 (recursive partitioning).
DP idea: Try splits and both swapped/unswapped partitions; memoize.
Time: Exponential worst-case but memoized; pruning by char-check reduces branching.
34) Minimum Falling Path Sum (grid)
Problem: From top row to bottom choose a path (down-left/down/down-right) minimize sum.
DP idea: row-by-row DP.
Time: O(n²), Space: O(n).
35) Cherry Pickup (two-person DP on grid)
Problem: Two people start at (0,0) and move to bottom-right and back, collecting cherries (can’t double collect).
DP idea: Transform to two people moving from start to end simultaneously; state by total steps t and positions r1,r2 (or columns), memoize.
Time: O(n³), Space: O(n³) memo.
36) Count Paths in DAG
Problem: Count number of paths from s to t in a DAG (mod large).
DP idea: Topological order and dp[v] = sum dp[u] over predecessors.
Time: O(V+E), Space: O(V).
37) Partition Equal Subset Sum
Problem: Can array be partitioned into two equal-sum subsets?
DP idea: Subset sum to total//2 using 1D boolean dp.
Time: O(n * target), Space: O(target).
38) Partition to K Equal Sum Subsets (bitmask DP)
Problem: Partition nums into k subsets each with equal sum.
DP idea: Bitmask DP tracking current remainder sum; dp[mask] true if mask can form some number of full groups.
Time: O(n * 2^n) worst, Space: O(2^n).
39) New 21 Game (Probability DP)
Problem: Alice draws numbers 1..W until sum >= K. Probability sum <= N.
DP idea: dp[x] probability of reaching x; sliding window sum optimization.
Time: O(K+W), Space: O(K+W).
40) Stone Game (simple game-theory DP)
Problem: Two players pick from ends of array; both play optimally. Decide winner or best score difference.
DP idea: dp[i][j] = max(nums[i]-dp[i+1][j], nums[j]-dp[i][j-1]) (score difference).
Time: O(n²), Space: O(n²).
38) Partition to K Equal Sum Subsets (bitmask DP)
Problem: Can we split nums into k subsets, each summing to the same value?
DP idea:
Total sum must be divisible by k.
Sort descending (pruning).
Use bitmask DP + memo:
dfs(mask, curr_sum) tells if remaining elements in mask can complete valid buckets.
When curr_sum == target, restart a new bucket with curr_sum = 0.
Time: ~O(n * 2ⁿ)
Space: O(2ⁿ)
39) Word Break (can segment string)
DP idea:
dp[i] = True if s[:i] can be segmented.
Check dictionary words.
40) Word Break II (print all segmentations)
DP idea: DFS + memo: build sentences from end.
41) Decode Ways (ways to decode digit string)
DP idea:
dp[i] = dp[i-1] (single digit if valid) + dp[i-2] (two digits if valid).
42) Decode Ways II (with ‘*’)
* can mean 1–9. Hard DP but standard.
43) Domino and Tromino Tiling
DP idea:
dp[n] = dp[n-1] + dp[n-2] + 2*sum(dp[0..n-3])
Use optimized recurrence:
dp[n] = 2*dp[n-1] + dp[n-3].
44) Paint Fence
DP idea:
Two states: same-color and diff-color.
Final: dp[n] = (k-1)*(dp[n-1] + dp[n-2]).
45) Remove Boxes (hard DP)
DP idea:
3D DP: dp[l][r][k]: max points in boxes[l..r] with k equal boxes appended at right.
46) Palindrome Partitioning II (minimum cuts)
DP idea:
dp[i] = min cuts for prefix ending at i.
47) Count Palindromic Subsequences (DP)
DP idea:
If s[i] == s[j], include inner + two ends; else subtract overlap.
48) Minimum ASCII Delete Sum for Two Strings
DP idea:
dp[i][j]: min delete sum to equalize s1[:i] and s2[:j].
49) Maximum Sum of Non-Adjacent Elements (House Robber I)
DP idea:
Classic: dp[i] = max(dp[i-1], dp[i-2] + nums[i]).
50) House Robber II (circular)
DP idea: rob either [0..n-2] or [1..n-1].