dp-pattern-library
A specialized skill for dynamic programming pattern recognition, matching problems to known DP patterns, generating template code, and providing optimization guidance for DP solutions.
Purpose
Assist with dynamic programming by:
- Matching problems to 50+ classic DP patterns
- Generating template code for matched patterns
- Detecting problem variants (knapsack variants, LCS variants, etc.)
- Providing state design recommendations
- Suggesting optimization techniques
Capabilities
Core Features
Pattern Recognition
- Analyze problem statement for DP indicators
- Match to known pattern categories
- Identify problem variants and transformations
- Suggest state representation
Pattern Categories
- Linear DP (1D array)
- Grid/Matrix DP (2D paths)
- String DP (LCS, edit distance)
- Interval DP (ranges, parenthesization)
- Tree DP (subtree problems)
- Bitmask DP (subset enumeration)
- Digit DP (number counting)
- Knapsack variants
- DP with state machine
Code Generation
- Template code for recognized patterns
- Multiple language support (Python, C++, Java)
- Comments explaining state and transitions
- Space-optimized variants
Optimization Guidance
- Rolling array technique
- Convex hull trick
- Divide and conquer optimization
- Monotonic queue/stack optimization
- Knuth optimization
Pattern Library
Linear DP Patterns
| Pattern |
State |
Transition |
Example Problems |
| Fibonacci |
dp[i] = answer for position i |
dp[i] = dp[i-1] + dp[i-2] |
Climbing Stairs, House Robber |
| Min/Max Path |
dp[i] = best answer ending at i |
dp[i] = opt(dp[j]) + cost(j,i) |
Minimum Path Sum |
| Counting |
dp[i] = ways to reach state i |
dp[i] = sum(dp[j]) |
Unique Paths, Decode Ways |
| LIS |
dp[i] = LIS ending at i |
dp[i] = max(dp[j]) + 1 where j < i, a[j] < a[i] |
Longest Increasing Subsequence |
String DP Patterns
| Pattern |
State |
Example Problems |
| Edit Distance |
dp[i][j] = distance for s1[0..i], s2[0..j] |
Edit Distance, One Edit Distance |
| LCS |
dp[i][j] = LCS of s1[0..i], s2[0..j] |
Longest Common Subsequence |
| Palindrome |
dp[i][j] = is s[i..j] palindrome |
Longest Palindromic Substring |
| Regex Match |
dp[i][j] = s[0..i] matches p[0..j] |
Regular Expression Matching |
Knapsack Patterns
| Variant |
State |
Transition |
| 0/1 Knapsack |
dp[i][w] = max value with items 0..i, capacity w |
dp[i][w] = max(dp[i-1][w], dp[i-1][w-wt[i]] + val[i]) |
| Unbounded |
dp[w] = max value with capacity w |
dp[w] = max(dp[w], dp[w-wt[i]] + val[i]) |
| Bounded |
dp[i][w] = max value with limited items |
Use binary representation or deque |
| Subset Sum |
dp[i][s] = can reach sum s with items 0..i |
dp[i][s] = dp[i-1][s] or dp[i-1][s-a[i]] |
Grid DP Patterns
| Pattern |
State |
Example Problems |
| Path Count |
dp[i][j] = ways to reach (i,j) |
Unique Paths, Unique Paths II |
| Path Min/Max |
dp[i][j] = best path to (i,j) |
Minimum Path Sum |
| Multi-path |
dp[i][j][k][l] = two paths simultaneously |
Cherry Pickup |
Interval DP Patterns
| Pattern |
State |
Example Problems |
| MCM |
dp[i][j] = cost for range [i,j] |
Matrix Chain Multiplication |
| Burst |
dp[i][j] = max coins from balloons[i..j] |
Burst Balloons |
| Merge |
dp[i][j] = cost to merge range [i,j] |
Minimum Cost to Merge Stones |
Tree DP Patterns
| Pattern |
State |
Example Problems |
| Subtree |
dp[v] = answer for subtree rooted at v |
Binary Tree Maximum Path Sum |
| Rerooting |
dp[v] = answer when v is root |
Sum of Distances in Tree |
| Parent-Child |
dp[v][0/1] = answer with constraint |
House Robber III |
Bitmask DP Patterns
| Pattern |
State |
Example Problems |
| TSP |
dp[mask][last] = min cost visiting mask cities ending at last |
Traveling Salesman Problem |
| Assignment |
dp[mask] = min cost assigning tasks to subset |
Task Assignment |
| SOS |
dp[mask] = sum over subsets |
Subset Sum over Subsets |
Usage
Pattern Matching
# Match problem to DP pattern
dp-pattern-library match --problem "Given an array of integers, find the longest increasing subsequence"
# Output:
# Pattern: Linear DP - Longest Increasing Subsequence (LIS)
# State: dp[i] = length of LIS ending at index i
# Transition: dp[i] = max(dp[j] + 1) for all j < i where arr[j] < arr[i]
# Time: O(n^2) naive, O(n log n) with binary search
# Space: O(n)
Template Generation
# Generate template code
dp-pattern-library template --pattern "lis" --language python
# Output:
def lengthOfLIS(nums):
if not nums:
return 0
n = len(nums)
# dp[i] = length of LIS ending at index i
dp = [1] * n
for i in range(1, n):
for j in range(i):
if nums[j] < nums[i]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
Optimization Suggestions
# Get optimization recommendations
dp-pattern-library optimize --pattern "lis"
# Output:
# Current: O(n^2) time, O(n) space
# Optimizations:
# 1. Binary Search: O(n log n) time
# - Maintain sorted list of smallest tail elements
# - Binary search for insertion point
# 2. Segment Tree: O(n log n) time
# - For coordinate compression + range max query
Output Schema
{
"match": {
"pattern": "Linear DP - LIS",
"confidence": 0.95,
"category": "linear",
"variants": ["LIS", "LDS", "LNDS"]
},
"state": {
"description": "dp[i] = length of LIS ending at index i",
"dimensions": 1,
"meaning": "LIS length ending at position i"
},
"transition": {
"formula": "dp[i] = max(dp[j] + 1) for j < i, arr[j] < arr[i]",
"baseCase": "dp[i] = 1 for all i",
"order": "left to right"
},
"complexity": {
"time": "O(n^2)",
"space": "O(n)",
"optimized": {
"time": "O(n log n)",
"technique": "binary search on patience sort"
}
},
"template": {
"python": "...",
"cpp": "...",
"java": "..."
},
"similarProblems": [
"Longest Increasing Subsequence",
"Number of Longest Increasing Subsequence",
"Russian Doll Envelopes",
"Maximum Length of Pair Chain"
]
}
Integration with Processes
This skill enhances:
dp-pattern-matching - Core pattern matching workflow
dp-state-optimization - State space optimization
dp-transition-derivation - Deriving transitions
leetcode-problem-solving - DP problem identification
classic-dp-library - Building a personal DP library
Pattern Recognition Indicators
| Indicator |
Likely Pattern |
| "maximum/minimum" + "subarray/subsequence" |
Linear DP |
| "number of ways" |
Counting DP |
| "can reach/achieve" |
Boolean DP |
| "edit/transform string" |
String DP |
| "merge/combine intervals" |
Interval DP |
| "tree/subtree" |
Tree DP |
| "select subset" + small n |
Bitmask DP |
| "count numbers with property" |
Digit DP |
| "items + capacity" |
Knapsack |
References
Error Handling
| Error |
Cause |
Resolution |
NO_PATTERN_MATCH |
Problem doesn't fit known patterns |
Consider greedy or other approaches |
AMBIGUOUS_MATCH |
Multiple patterns could apply |
Provide more problem details |
COMPLEX_STATE |
State too complex for templates |
Manual state design needed |
Best Practices
- Start with brute force - Understand recurrence before optimizing
- Draw state diagram - Visualize transitions
- Verify base cases - Most DP bugs are in base cases
- Check state uniqueness - Each state should be uniquely defined
- Consider space optimization - Often can reduce dimension
- Test with small inputs - Trace through by hand
1---2name: dp-pattern-library3description: Maintain and match against a library of classic dynamic programming patterns. Provides pattern matching, template code generation, variant detection, and problem-to-pattern mapping for DP problems.4---5
6# dp-pattern-library
7
8A specialized skill for dynamic programming pattern recognition, matching problems to known DP patterns, generating template code, and providing optimization guidance for DP solutions.
9
10## Purpose
11
12Assist with dynamic programming by:
13- Matching problems to 50+ classic DP patterns
14- Generating template code for matched patterns
15- Detecting problem variants (knapsack variants, LCS variants, etc.)
16- Providing state design recommendations
17- Suggesting optimization techniques
18
19## Capabilities
20
21### Core Features
22
231. **Pattern Recognition**
24 - Analyze problem statement for DP indicators
25 - Match to known pattern categories
26 - Identify problem variants and transformations
27 - Suggest state representation
28
292. **Pattern Categories**
30 - Linear DP (1D array)
31 - Grid/Matrix DP (2D paths)
32 - String DP (LCS, edit distance)
33 - Interval DP (ranges, parenthesization)
34 - Tree DP (subtree problems)
35 - Bitmask DP (subset enumeration)
36 - Digit DP (number counting)
37 - Knapsack variants
38 - DP with state machine
39
403. **Code Generation**
41 - Template code for recognized patterns
42 - Multiple language support (Python, C++, Java)
43 - Comments explaining state and transitions
44 - Space-optimized variants
45
464. **Optimization Guidance**
47 - Rolling array technique
48 - Convex hull trick
49 - Divide and conquer optimization
50 - Monotonic queue/stack optimization
51 - Knuth optimization
52
53## Pattern Library
54
55### Linear DP Patterns
56
57| Pattern | State | Transition | Example Problems |
58|---------|-------|------------|------------------|
59| **Fibonacci** | dp[i] = answer for position i | dp[i] = dp[i-1] + dp[i-2] | Climbing Stairs, House Robber |
60| **Min/Max Path** | dp[i] = best answer ending at i | dp[i] = opt(dp[j]) + cost(j,i) | Minimum Path Sum |
61| **Counting** | dp[i] = ways to reach state i | dp[i] = sum(dp[j]) | Unique Paths, Decode Ways |
62| **LIS** | dp[i] = LIS ending at i | dp[i] = max(dp[j]) + 1 where j < i, a[j] < a[i] | Longest Increasing Subsequence |
63
64### String DP Patterns
65
66| Pattern | State | Example Problems |
67|---------|-------|------------------|
68| **Edit Distance** | dp[i][j] = distance for s1[0..i], s2[0..j] | Edit Distance, One Edit Distance |
69| **LCS** | dp[i][j] = LCS of s1[0..i], s2[0..j] | Longest Common Subsequence |
70| **Palindrome** | dp[i][j] = is s[i..j] palindrome | Longest Palindromic Substring |
71| **Regex Match** | dp[i][j] = s[0..i] matches p[0..j] | Regular Expression Matching |
72
73### Knapsack Patterns
74
75| Variant | State | Transition |
76|---------|-------|------------|
77| **0/1 Knapsack** | dp[i][w] = max value with items 0..i, capacity w | dp[i][w] = max(dp[i-1][w], dp[i-1][w-wt[i]] + val[i]) |
78| **Unbounded** | dp[w] = max value with capacity w | dp[w] = max(dp[w], dp[w-wt[i]] + val[i]) |
79| **Bounded** | dp[i][w] = max value with limited items | Use binary representation or deque |
80| **Subset Sum** | dp[i][s] = can reach sum s with items 0..i | dp[i][s] = dp[i-1][s] or dp[i-1][s-a[i]] |
81
82### Grid DP Patterns
83
84| Pattern | State | Example Problems |
85|---------|-------|------------------|
86| **Path Count** | dp[i][j] = ways to reach (i,j) | Unique Paths, Unique Paths II |
87| **Path Min/Max** | dp[i][j] = best path to (i,j) | Minimum Path Sum |
88| **Multi-path** | dp[i][j][k][l] = two paths simultaneously | Cherry Pickup |
89
90### Interval DP Patterns
91
92| Pattern | State | Example Problems |
93|---------|-------|------------------|
94| **MCM** | dp[i][j] = cost for range [i,j] | Matrix Chain Multiplication |
95| **Burst** | dp[i][j] = max coins from balloons[i..j] | Burst Balloons |
96| **Merge** | dp[i][j] = cost to merge range [i,j] | Minimum Cost to Merge Stones |
97
98### Tree DP Patterns
99
100| Pattern | State | Example Problems |
101|---------|-------|------------------|
102| **Subtree** | dp[v] = answer for subtree rooted at v | Binary Tree Maximum Path Sum |
103| **Rerooting** | dp[v] = answer when v is root | Sum of Distances in Tree |
104| **Parent-Child** | dp[v][0/1] = answer with constraint | House Robber III |
105
106### Bitmask DP Patterns
107
108| Pattern | State | Example Problems |
109|---------|-------|------------------|
110| **TSP** | dp[mask][last] = min cost visiting mask cities ending at last | Traveling Salesman Problem |
111| **Assignment** | dp[mask] = min cost assigning tasks to subset | Task Assignment |
112| **SOS** | dp[mask] = sum over subsets | Subset Sum over Subsets |
113
114## Usage
115
116### Pattern Matching
117
118```bash
119# Match problem to DP pattern
120dp-pattern-library match --problem "Given an array of integers, find the longest increasing subsequence"
121
122# Output:
123# Pattern: Linear DP - Longest Increasing Subsequence (LIS)
124# State: dp[i] = length of LIS ending at index i
125# Transition: dp[i] = max(dp[j] + 1) for all j < i where arr[j] < arr[i]
126# Time: O(n^2) naive, O(n log n) with binary search
127# Space: O(n)
128```
129
130### Template Generation
131
132```bash
133# Generate template code
134dp-pattern-library template --pattern "lis" --language python
135
136# Output:
137def lengthOfLIS(nums):
138 if not nums:
139 return 0
140
141 n = len(nums)
142 # dp[i] = length of LIS ending at index i
143 dp = [1] * n
144
145 for i in range(1, n):
146 for j in range(i):
147 if nums[j] < nums[i]:
148 dp[i] = max(dp[i], dp[j] + 1)
149
150 return max(dp)
151```
152
153### Optimization Suggestions
154
155```bash
156# Get optimization recommendations
157dp-pattern-library optimize --pattern "lis"
158
159# Output:
160# Current: O(n^2) time, O(n) space
161# Optimizations:
162# 1. Binary Search: O(n log n) time
163# - Maintain sorted list of smallest tail elements
164# - Binary search for insertion point
165# 2. Segment Tree: O(n log n) time
166# - For coordinate compression + range max query
167```
168
169## Output Schema
170
171```json
172{
173 "match": {
174 "pattern": "Linear DP - LIS",
175 "confidence": 0.95,
176 "category": "linear",
177 "variants": ["LIS", "LDS", "LNDS"]
178 },
179 "state": {
180 "description": "dp[i] = length of LIS ending at index i",
181 "dimensions": 1,
182 "meaning": "LIS length ending at position i"
183 },
184 "transition": {
185 "formula": "dp[i] = max(dp[j] + 1) for j < i, arr[j] < arr[i]",
186 "baseCase": "dp[i] = 1 for all i",
187 "order": "left to right"
188 },
189 "complexity": {
190 "time": "O(n^2)",
191 "space": "O(n)",
192 "optimized": {
193 "time": "O(n log n)",
194 "technique": "binary search on patience sort"
195 }
196 },
197 "template": {
198 "python": "...",
199 "cpp": "...",
200 "java": "..."
201 },
202 "similarProblems": [
203 "Longest Increasing Subsequence",
204 "Number of Longest Increasing Subsequence",
205 "Russian Doll Envelopes",
206 "Maximum Length of Pair Chain"
207 ]
208}
209```
210
211## Integration with Processes
212
213This skill enhances:
214- `dp-pattern-matching` - Core pattern matching workflow
215- `dp-state-optimization` - State space optimization
216- `dp-transition-derivation` - Deriving transitions
217- `leetcode-problem-solving` - DP problem identification
218- `classic-dp-library` - Building a personal DP library
219
220## Pattern Recognition Indicators
221
222| Indicator | Likely Pattern |
223|-----------|----------------|
224| "maximum/minimum" + "subarray/subsequence" | Linear DP |
225| "number of ways" | Counting DP |
226| "can reach/achieve" | Boolean DP |
227| "edit/transform string" | String DP |
228| "merge/combine intervals" | Interval DP |
229| "tree/subtree" | Tree DP |
230| "select subset" + small n | Bitmask DP |
231| "count numbers with property" | Digit DP |
232| "items + capacity" | Knapsack |
233
234## References
235
236- [Dynamic Programming Patterns](https://github.com/aatalyk/Dynamic-Programming-Patterns)
237- [DP Visualization Tools](https://dp.debkbanerji.com/)
238- [LeetCode DP Patterns](https://leetcode.com/discuss/general-discussion/458695/dynamic-programming-patterns)
239- [CP Algorithms - DP](https://cp-algorithms.com/dynamic_programming.html)
240- [CSES DP Section](https://cses.fi/problemset/list/)
241
242## Error Handling
243
244| Error | Cause | Resolution |
245|-------|-------|------------|
246| `NO_PATTERN_MATCH` | Problem doesn't fit known patterns | Consider greedy or other approaches |
247| `AMBIGUOUS_MATCH` | Multiple patterns could apply | Provide more problem details |
248| `COMPLEX_STATE` | State too complex for templates | Manual state design needed |
249
250## Best Practices
251
2521. **Start with brute force** - Understand recurrence before optimizing
2532. **Draw state diagram** - Visualize transitions
2543. **Verify base cases** - Most DP bugs are in base cases
2554. **Check state uniqueness** - Each state should be uniquely defined
2565. **Consider space optimization** - Often can reduce dimension
2576. **Test with small inputs** - Trace through by hand