DP patterns

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

  • Top-Down

How to solve recursion problem

  • Choice digram

  • 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

  • Subset Sum

  • Partition Equal Subset Sum

  • Count Subsets with Given Sum

  • Minimum Subset Sum Difference

  • Target Sum (Leetcode)

  • 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

  • Coin Change (ways)

  • Coin Change (min coins)

  • Unbounded Rod Cutting

  • 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

  • Climbing Stairs

  • Minimum/Maximum Jumps to Reach End

  • Decode Ways (number of ways to decode string)

  • House Robber

  • Paint Fence

  • Tiling Problems (2xn tiling)

  • Tribonacci-like problems

  • 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 Common Substring

  • Edit Distance

  • Longest Palindromic Subsequence

  • Shortest Common Supersequence

  • Delete Operations for Two Strings

  • Distinct Subsequences

  • Wildcard Matching

  • 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

  • Number of LIS

  • Russian Doll Envelopes

  • Longest Chain of Pairs

  • Building Bridges

  • Box Stacking

  • 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

  • Maximum Product Subarray

  • 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

  • Burst Balloons

  • Boolean Parenthesization

  • Palindrome Partitioning

  • Minimum Score Triangulation

  • Evaluate to True (expression parsing)

  • Optimal BST

  • Stick Cutting / Minimum Cost to Cut Stick


8. DP on Trees

DP where the structure is a tree, solved using DFS post-order traversal.

State is often:

dp[node] depends on children.

Similar Problems

  • Diameter of a Tree

  • Maximum Path Sum in Binary Tree

  • Count Paths / Sum Paths

  • Tree DP with states (e.g., “Rob houses in a tree”)

  • LCA-based DP problems

  • DP on subtree sizes, number of ways, distances

  • Binary Tree Cameras

  • 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

  • Longest Path in a DAG

  • Shortest Path in DAG (DP-like)

  • Number of Paths in a DAG

  • 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

a) Bitmask DP

Used when state depends on subsets.

Similar Problems

  • Traveling Salesman Problem (TSP)

  • DP on subsets

  • Maximum Compatibility of Students

  • Assignments / matching problems

b) Digit DP

Counting numbers with constraints.

Similar Problems

  • Count numbers with digit sum

  • Count numbers without consecutive digits

  • Numbers divisible by X

c) Interval DP

Same as MCM but without explicit matrix context.

Similar Problems

  • Merge Stones

  • Stone Game variations

  • DP for choosing segments

d) DP on Grids

Classic 2D DP.

Problems

  • Unique Paths

  • Minimum Path Sum

  • Cherry Pickup

  • Gold Mine Problem


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], …

  1. Fibonacci Numbers

  2. Climbing Stairs

  3. Min Cost Climbing Stairs

  4. House Robber

  5. House Robber II

  6. Decode Ways

  7. Tribonacci Number

  8. N-th Stair Problem (taking 1, 2, or 3 steps)

  9. Number of Ways to Reach Destination (hop 1 or 2 or 3)

  10. Tiling With Dominoes

  11. Tiling With 2×1 and 2×2 tiles

  12. Painting Fence

  13. Count Balanced Parentheses (Catalan DP)

  14. Unique BST (Catalan)

  15. Number of Binary Trees with N nodes


2. 0/1 Knapsack Pattern

Core idea: pick or skip, finite items.

  1. 0/1 Knapsack

  2. Subset Sum

  3. Partition Equal Subset Sum

  4. Minimum Subset Sum Difference

  5. Target Sum

  6. Count Subsets With Given Sum

  7. Rod Cutting (bounded)

  8. Assign Tasks With Constraints

  9. Students–Exam Assignment (take/not take)

  10. Pick Movies/Songs With Time Limit


3. Unbounded Knapsack Pattern

Core idea: pick item unlimited times.

  1. Coin Change (Number of Ways)

  2. Coin Change (Minimum Coins)

  3. Unbounded Knapsack

  4. Rod Cutting (unbounded)

  5. Minimum Cost to Reach N

  6. Perfect Squares (Min count)

  7. Combination Sum

  8. Tiling M×N Wall (infinite bricks)

  9. Minimum Cost for Train Tickets

  10. Word Break (unbounded dictionary)


4. Longest Increasing Sequence (LIS) Pattern

dp[i] = best answer ending at i.

  1. LIS

  2. Number of LIS

  3. Maximum Sum Increasing Subsequence

  4. Longest Bitonic Subsequence

  5. Russian Doll Envelopes

  6. Box Stacking Problem

  7. Building Bridges

  8. Largest Divisible Subset

  9. Minimum Deletions to Make Array Sorted

  10. Minimum Number of Removals to Make Mountain Array


5. Longest Common Subsequence (LCS) Pattern

Compare characters of two sequences.

  1. LCS

  2. Longest Common Substring

  3. Edit Distance

  4. Shortest Common Supersequence

  5. Distinct Subsequences

  6. Min Insertions to Make String Palindrome

  7. Longest Palindromic Subsequence

  8. Delete Operation for Two Strings

  9. Regular Expression Matching (DP)

  10. Wildcard Matching

  11. Interleaving Strings

  12. Scramble String

  13. Minimum Window Subsequence


6. Kadane’s Algorithm Style DP

dp[i] = max(arr[i], arr[i] + dp[i-1]).

  1. Maximum Subarray

  2. Maximum Circular Subarray Sum

  3. Maximum Product Subarray

  4. Max Sum of Non-Adjacent Elements (Kadane variant)

  5. Best Time to Buy and Sell Stock I

  6. Best Time to Buy and Sell Stock II

  7. Best Time to Buy and Sell Stock III

  8. Best Time to Buy and Sell Stock IV

  9. Maximum Subarray After One Deletion

  10. Maximum Sum Rectangle in Matrix (Kadane inside)


7. Matrix Chain Multiplication (MCM) Pattern

Interval DP — recursively break into left + right partitions.

  1. Matrix Chain Multiplication

  2. Palindrome Partitioning (min cuts)

  3. Minimum Palindromic Partitioning II

  4. Burst Balloons

  5. Boolean Parenthesization

  6. Evaluate Expression for True

  7. Minimum Score Triangulation of Polygon

  8. Stick Cutting / Minimum Cost to Cut a Stick

  9. Optimal BST

  10. Scrambled String Verification


8. DP on Trees

Use DFS and compute dp from children.

  1. Maximum Path Sum in Binary Tree

  2. Diameter of Binary Tree

  3. Sum of Root-to-Leaf Paths

  4. House Robber on Trees

  5. Count BSTs in a subtree

  6. DP on Tree: Subtree Size

  7. DP on Tree: Height, Depth, Parent

  8. Distribute Coins in Binary Tree

  9. Binary Tree Cameras

  10. Maximum Independent Set in Tree

  11. Minimum Vertex Cover (trees)


9. DP on Graphs (DAG DP + Paths)

Topological order DP.

  1. Longest Path in a DAG

  2. Shortest Path in a DAG

  3. Number of Paths in Grid With Obstacles

  4. Counting Paths in Directed Acyclic Graph

  5. Hamiltonian Path with Bitmask DP

  6. Traveling Salesman Problem (TSP)

  7. DP for Weighted DAG path counting

  8. Word Ladder II (DP on graph levels)

  9. Frog Jump

  10. Cherry Pickup (graph-like transitions)

  11. Minimum Cost to Travel Between Cities (DAG DP variant)


10. Grid DP (2D DP)

  1. Unique Paths

  2. Unique Paths II

  3. Minimum Path Sum

  4. Dungeon Game

  5. Gold Mine Problem

  6. Cherry Pickup

  7. Maximal Square

  8. Largest Rectangle of 1s

  9. Minimum Falling Path Sum

  10. Increasing Paths in Grid


11. Bitmask DP

✔ State represented by subsets.

  1. Traveling Salesman Problem

  2. Minimum Incompatibility

  3. Assign Workers to Jobs

  4. Maximum Compatibility of Students

  5. Partition to K Equal Sum Subsets

  6. Sudoku Solvers using bitmask DP

  7. Count Ways to Visit All Nodes (state compression DP)


12. Digit DP

✔ Count numbers with certain digit patterns.

  1. Count numbers ≤ N with digit sum K

  2. Count numbers with no consecutive digits

  3. Count numbers divisible by X

  4. Count numbers with limited set of digits

  5. Count stepping numbers


13. Probability DP

✔ DP on outcomes of events.

  1. Dice Throw (ways to get sum)

  2. Probability of Winning a Game

  3. Knight Probability on Chessboard

  4. New 21 Game

  5. Number of Ways to Reach Target Score


14. Game Theory DP

✔ Min-max DP.

  1. Stone Game

  2. Stone Game II

  3. Stone Game III

  4. Predict the Winner

  5. Removing Stones (Nim-like DP)

  6. Coins in a Line


15. Interval Scheduling / Segmented DP

✔ DP on intervals sorted by start time.

  1. Weighted Job Scheduling

  2. Maximum Profit in Job Scheduling

  3. Video Stitching

  4. Taxi Earnings (Leetcode)

  5. Interval DP for merging intervals


16. Advanced Patterns

(Rare but very powerful)

  1. DP + Greedy hybrid (e.g., scheduling + DP)

  2. DP + Prefix Sum optimisation

  3. DP + Monotonic Queue Optimisation

  4. DP + Binary Lifting (tree DP optimisation)

  5. DP + Convex Hull Trick

  6. 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).


5) Decode Ways

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.

Solution

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:

  • Precompute palindromes.

  • 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].


Last updated