Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views16 pages

DP Patterns

Uploaded by

IIB2024501
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views16 pages

DP Patterns

Uploaded by

IIB2024501
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Dynamic Programming Patterns –

Complete Master Guide


This guide breaks down the most important and frequently asked DP patterns, each
forming the foundation of many problems seen in interviews and competitive programming.

🔷 1. Take / Not Take (Subset-Based DP)


🔹 Core Idea:

 For each element, decide to take it or not take it.


 Works best with boolean or max/min value goals.

🔹 Recurrence:
dp[i][j] = dp[i-1][j] (not take) || dp[i-1][j-arr[i]] (take if j >= arr[i])

🔹 Used In:

 Subset Sum
 0/1 Knapsack
 Equal Subset Partition
 House Robber
 Target Sum

🔷 2. Match / Not Match (String-Based DP)


🔹 Core Idea:

 Compare characters of two strings (or one string and a pattern).


 If characters match: move both
 Else: try skipping characters (or handle pattern wildcards)

🔹 Recurrence:
dp[i][j] = dp[i-1][j-1] (if match)
Else: dp[i][j] = min(dp[i-1][j], dp[i][j-1])

🔹 Used In:

 Longest Common Subsequence (LCS)


 Edit Distance
 Distinct Subsequences
 Wildcard Matching
 Regular Expression Matching

🔷 3. Try All Previous (LIS-Based DP)


🔹 Core Idea:

 Build answer by extending all valid smaller subsequences.

🔹 Recurrence:
dp[i] = max(dp[j] + 1) for all j < i and arr[j] < arr[i]

🔹 Used In:

 Longest Increasing Subsequence (LIS)


 Maximum Sum Increasing Subsequence
 Longest Bitonic Subsequence
 Russian Doll Envelopes

🔷 4. K Jumps / Frog Jump / Climbing


🔹 Core Idea:

 Move from i to i+1, i+2, ..., i+k based on jump range and cost.

🔹 Recurrence:
dp[i] = min(dp[i-1] + cost1, dp[i-2] + cost2, ...)

🔹 Used In:

 Climbing Stairs
 Minimum Cost Climbing Stairs
 Frog Jump
 Minimum Jumps to End

🔷 5. Count Ways (Combinatorics-Based DP)


🔹 Core Idea:
 Count number of distinct ways to reach a state.

🔹 Recurrence:

dp[i] = dp[i-1] + dp[i-2] + ... (based on steps or coin values)

🔹 Used In:

 Coin Change (Number of Ways)


 Decode Ways
 Unique Paths
 Dice Throw
 Number of Ways to Climb Stairs

🔷 6. Kadane's / Running Result


🔹 Core Idea:

 Track maximum (or minimum) contiguous subarrays using rolling sum.

🔹 Used In:

 Maximum Subarray Sum


 Maximum Product Subarray
 Maximum Circular Subarray Sum

🔷 7. All Cuts / Partitioning (Matrix Chain Multiplication


Pattern)
🔹 Core Idea:

 Try every partition/cut in a range and combine results.

🔹 Recurrence:
dp[i][j] = min(dp[i][k] + dp[k+1][j] + cost(i,j)) for all k in [i,j-1]

🔹 Used In:

 Matrix Chain Multiplication


 Palindrome Partitioning
 Burst Balloons
 Boolean Parenthesization
🔷 8. Bitmask DP
🔹 Core Idea:

 Use a bitmask to represent selected elements/states.

🔹 Used In:

 Traveling Salesman Problem (TSP)


 Assignment Problem
 XOR Subsets
 Minimum Cost to Connect Cities

🔷 9. Digit DP
🔹 Core Idea:

 Work on digits of a number, track tight/loose bounds.


 Use recursion + memoization for numbers ≤ N.

🔹 Used In:

 Count numbers ≤ N with K non-zero digits


 Sum of digits in range
 Count numbers without consecutive 1s

🔷 10. DP on Trees
🔹 Core Idea:

 Use post-order DFS to calculate values bottom-up from children to parent.

🔹 Used In:

 Tree Diameter
 Max Path Sum in Tree
 Counting Subtrees
 Tree Coloring / DP on Rooted Trees
🔷 11. Palindrome DP
🔹 Core Idea:

 Use 2D DP where dp[i][j] stores results for s[i..j].

🔹 Used In:

 Longest Palindromic Subsequence


 Longest Palindromic Substring
 Palindrome Partitioning

🔷 12. DP on Grids
🔹 Core Idea:

 Move in a grid (usually right and down).


 Use dp[i][j] = value[i][j] + min(dp[i-1][j], dp[i][j-1])

🔹 Used In:

 Minimum Path Sum


 Unique Paths
 Gold Mine Problem
 Cherry Pickup

💡 Bonus Tips:

 Convert recursive + memoization to iterative + tabulation.


 Space optimize when possible.
 Always define:
o Base case
o Recurrence relation
o State parameters

Some more patterns


1. Fibonacci Sequence
✨ The Fibonacci sequence pattern is handy when solving a problem that
relies on smaller subproblems. 🔄🔢

It follows a clear recursive relationship, much like the classic Fibonacci


formula: F(n) = F(n-1) + F(n-2). ➕🔁

LeetCode Problems:
 LeetCode 70: Climbing Stairs
 LeetCode 509: Fibonacci Number
 LeetCode 746. Min Cost Climbing Stairs
2. Kadane's Algorithm
Kadane’s Algorithm
🚀 Kadane's Algorithm is mainly used to solve the Maximum Subarray
Problem 🧩 and its variations, where the goal is to find the optimal
contiguous subarray 📊 within a one-dimensional numeric array 🔢.
LeetCode Problems:
 LeetCode 53: Maximum Subarray
 LeetCode 918: Maximum Sum Circular Subarray
 LeetCode 152: Maximum Product Subarray
3. 0/1 Knapsack
0/1 Knapsack
🧳 0/1 Knapsack Pattern is Handy When:
✅ You have a collection of items, each with a specific weight ⚖️and value
💰.
✅ You need to pick a subset of these items.
✅ There's a weight limit ⏳ (or another resource constraint) you must
follow.
✅ Your goal is to maximize 🔝 (or minimize 🔽) the total value of the
chosen items.
✅ Each item can be selected only once 🎯 (hence "0/1"—you either take it
or leave it).
LeetCode Problems:
 LeetCode 416: Partition Equal Subset Sum
 LeetCode 494: Target Sum
 LeetCode 1049. Last Stone Weight II
4. Unbounded Knapsack
🔹 Unbounded Knapsack Pattern is helpful when:
📦 You have a set of items, each with a specific weight ⚖️and value 💰.
🎯 Your goal is to maximize total value while selecting items.
⛔ There's a weight limit ⏳ (or another resource constraint) you must
follow.
🔄 Unlike 0/1 Knapsack, you can pick the same item multiple
times 🔁.
♾️The supply of each item is unlimited! 🚀
LeetCode Problems:
 LeetCode 322: Coin Change
 LeetCode 518: Coin Change 2
 LeetCode 279. Perfect Squares
5. Longest Common Subsequence (LCS)

Longest Common Subsequence


🔍 The Longest Common Subsequence (LCS) pattern helps when you
have two sequences 📜 and need to find a subsequence that appears in
both while maintaining the same order 🔢✅.
LeetCode Problems:
 LeetCode 300: Longest Increasing Subsequence
 LeetCode 673: Number of Longest Increasing Subsequence
 leetCode 354: Russian Doll Envelopes
6. Longest Increasing Subsequence (LIS)
The Longest Increasing Subsequence pattern is used to solve
problems that involve finding the longest subsequence of elements in a
sequence where the elements are in increasing order.
LeetCode Problems:
 LeetCode 300: Longest Increasing Subsequence
 LeetCode 673: Number of Longest Increasing Subsequence
 leetCode 354: Russian Doll Envelopes
7. Palindromic Subsequence
🔁 Palindromic Subsequence Pattern 🔁 This pattern helps solve
problems where you need to find a subsequence in a sequence (typically a
string) that remains the same when read forward and backward. 🔄✨
LeetCode Problems:
 LeetCode 516: Longest Palindromic Subsequence
 LeetCode 647: Palindromic Substrings
 LeetCode 1312: Minimum Insertion Steps to Make a String
Palindrome
8. Edit Distance
📝 Edit Distance Pattern helps solve problems where you transform one
sequence (📄➡️📜) into another with the least number of operations.
🔧 Allowed operations: ➕ Insertion ➖ Deletion 🔄 Substitution
LeetCode Problems:
 LeetCode 72: Edit Distance
 LeetCode 583: Delete Operation for Two Strings
 LeetCode 712: Minimum ASCII Delete Sum for Two Strings
9. Subset Sum
🧩 The Subset Sum pattern helps in solving problems where you need to
check if a subset of elements from a given set adds up to a specific target
value. 🎯✅

LeetCode Problems:
 LeetCode 416: Partition Equal Subset Sum
 LeetCode 494: Target Sum
 LeetCode 698: Partition to K Equal Sum Subsets
10. String Partition
🧩 String Partition Pattern 🧩
The String Partition pattern helps in solving problems where a string
needs to be divided into smaller substrings that meet specific
conditions. 📏✂️
🔹 When to Use It?
✅ Dealing with strings or sequences 🔤
✅ Need to split a string into valid substrings or subsequences 🔪
✅ Looking to optimize properties like cost 💰 or value 📈
✅ The solution for the whole string depends on solving smaller
substring problems 🔄
✅ Considering different ways to partition the string
This pattern is key to efficiently solving many dynamic programming
problems! 🚀
LeetCode Problems:
 LeetCode 139: Word Break
 LeetCode 132. Palindrome Partitioning II
 LeetCode 472: Concatenated Words
11. Catalan Numbers
🌟 Catalan Number Pattern 🌟
The Catalan Number pattern helps in solving combinatorial problems
by breaking them into smaller, similar subproblems. 🔄✨
🔹 Use Cases:
1. ✅ Counting the number of valid parentheses expressions for a given
length 🧩🔢
2. ✅ Finding the number of unique binary search trees that can be formed
with n nodes 🌳
3. ✅ Determining the ways to triangulate a polygon with n+2 sides 🔺📐
LeetCode Problems:
 LeetCode 96: Unique Binary Search Trees
 LeetCode 22: Generate Parentheses
12. Matrix Chain Multiplication
🔄 Optimal Order Strategy
This pattern helps solve problems where you need to determine the best
sequence of operations to minimize 🔽 the overall cost 💰.

✨ It’s inspired by the well-known Matrix Chain Multiplication problem.


📌 When to Use:
1. ✅ You're working with a sequence of elements that can be merged
pairwise 🔗.
2. ✅ The cost 💲 of merging depends on the order in which elements are
combined 🔄.
3. ✅ You need to find the most efficient way to merge them ⚡.
4. ✅ The goal is to minimize (or maximize) the cost of operations 📉📈.
LeetCode Problems:
 LeetCode 1039: Minimum Score Triangulation of Polygon
 LeetCode 312: Burst Balloons
 LeetCode 1000: Minimum Cost to Merge Stones
13. Count Distinct Ways
🔹 Use this pattern when:
✅ You need to count the different ways to achieve a goal or reach a
specific state 🎯.
✅ The problem requires making a series of choices or steps to reach a
target 🚶♂️➡️🏁.
✅ There are multiple valid paths or combinations to solve the problem
🔀.
✅ The problem can be broken down into smaller subproblems with
overlapping solutions 🧩.
✅ You’re solving combinatorial problems that ask, “In how many ways
can this be done?” 🔢.
LeetCode Problems:
 LeetCode 91: Decode Ways
 LeetCode 2266. Count Number of Texts
14. DP on Grids
DP on Grids
🟩 DP on Grids is a pattern used for solving problems that involve
navigating or optimizing paths in a 2D grid.

down ⏬, diagonal ↘️), and each cell’s solution depends on the values of
➡️In these problems, movement can be in multiple directions (right ⏩,

its neighboring cells.


LeetCode Problems:
 LeetCode 62: Unique Paths
 LeetCode 64: Minimum Path Sum
 LeetCode 329. Longest Increasing Path in a Matrix
15. DP on Trees
🌳 DP on Trees Pattern is Handy When:
✅ You're dealing with tree-structured data represented by nodes &
edges. 🌲🔗
✅ The problem can be split into smaller subproblems, each forming its
own tree-based challenge. 🌿🧩
✅ You need to make decisions at each node that impact its children or
parent. 🤔🔄
✅ Values for nodes must be computed based on their children or
ancestors. 📊🔢
LeetCode Problems:
 LeetCode 337: House Robber III
 LeetCode 124: Binary Tree Maximum Path Sum
 LeetCode 968: Binary Tree Cameras
16. DP on Graphs
🚀 The DP on Graphs pattern is handy when:
1. You're solving problems that involve graph structures.
2. The task requires finding optimal paths, longest paths, cycles, or
other optimized properties.
3. You need to compute values for nodes or edges based on their
neighbors or connected components.
4. The problem involves traversing a graph while keeping track of some
state.
LeetCode Problems:
 LeetCode 787: Cheapest Flights Within K Stops
 LeetCode 1334. Find the City With the Smallest Number of
Neighbors at a Threshold Distance
17. Digit DP
🔢 The Digit DP Pattern is handy when:
✅ You need to count or sum numbers within a given range.
🔍 The problem requires analyzing each digit individually.
📊 You must identify patterns or properties in the digits of numbers.
📈 The number range is huge (often up to 10¹⁸), making brute-force
methods impractical.
⚡ The problem includes specific constraints on the digits.
LeetCode Problems:
 LeetCode 357: Count Numbers with Unique Digits
 LeetCode 233: Number of Digit One
 LeetCode 902. Numbers At Most N Given Digit Set
18. Bitmasking DP
🧩 Bitmasking DP Pattern is a powerful technique for solving problems
with numerous states or combinations, where each state can be efficiently
represented using bits in an integer.
✨ When to Use It?
1. Ideal for problems involving subsets or combinations of elements.
2. Works best when the total number of elements is small (typically ≤ 20-
30).
3. Helps efficiently represent & manipulate sets of elements.
4. Useful for decisions like include/exclude or tracking visited/unvisited
states.
5. Optimizes space usage in DP solutions. 🚀
LeetCode Problems:
 LeetCode 1986: Minimum Number of Work Sessions to Finish the
Tasks
 LeetCode 2305. Fair Distribution of Cookies
 LeetCode 847: Shortest Path Visiting All Nodes
19. Probability DP
🔥 This pattern is handy when:

🎲 You're tackling problems that involve probability calculations.


🔄 The probability of a state depends on previous states.
📊 You need to determine the expected value of an outcome.
🎮 The problem includes random processes or games of chance.

LeetCode Problems:
 LeetCode 688: Knight Probability in Chessboard
 LeetCode 808: Soup Servings
 LeetCode 837. New 21 Game
20. State Machine DP
🔄 State Machine DP Pattern is useful when:
✅ The problem can be represented as a set of states with transitions
between them. 🔁
✅ There are well-defined rules for shifting from one state to another. ⚖️
✅ The best solution relies on choosing the optimal sequence of state
transitions. 🎯
✅ Decisions impact future states, making strategic choices crucial. 🔮
✅ The number of possible states is limited, and each state is clearly
defined. 🔢

LeetCode Problems:
 LeetCode 309: Best Time to Buy and Sell Stock with Cooldown
 LeetCode 123: Best Time to Buy and Sell Stock III

You might also like