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