Dynamic Programming
1D, grid, knapsack, LCS, LIS, interval, tree, bitmask and digit DP across 24 patterns.
DSAAdvanced84 hrs24 patterns · 120 problems
0%
your progressCore idea
Write the recursive brute force, name its parameters as the state, memoise, then convert to a table and compress dimensions if only the previous row is needed.
Reach for it when
- Count ways, min/max cost, or feasibility over choices
- Overlapping subproblems in the brute-force recursion
- Sequences, grids, knapsacks, intervals, trees
Template
def lcs(a, b):
prev = [0] * (len(b) + 1)
for i in range(1, len(a) + 1):
cur = [0] * (len(b) + 1)
for j in range(1, len(b) + 1):
cur[j] = prev[j-1] + 1 if a[i-1] == b[j-1] else max(prev[j], cur[j-1])
prev = cur
return prev[-1]Complexity
States × transitions — e.g. O(n·m) for LCS, O(n·W) for knapsack.
Common pitfalls
- A state that doesn't capture everything the future depends on
- Wrong iteration order for 0/1 vs unbounded knapsack
- Off-by-one between 1-indexed tables and 0-indexed strings
Patterns in this course
1D / Fibonacci · 9Kadane / Subarray DP · 3State Machine / Stocks · 8Grid DP · 10Triangle / Pascal · 30/1 Knapsack / Subset Sum · 10Unbounded Knapsack · 6String DP / Word Break · 11LCS · 11LIS · 9Palindrome / Interval DP · 4Partition DP · 3MCM / Interval Partition · 4DP on Squares / Matrix · 3Tree DP · 4Game DP · 6Catalan / Counting DP · 1Graph / DAG DP · 4Bitmask DP · 1Digit DP · 3Probability DP · 30/1 Knapsack · 1DP on Array · 2Weighted Interval Scheduling (DP + Binary Search) · 1
Recognition cues
1DGridKnapsackLCSLISState MachineIntervalPartitionTree/GraphBitmaskDigit