Topic · 11 patterns
Dynamic Programming patterns
Dynamic programming is recursion that remembers: name the state, write the transition, fill the table. These eleven patterns are the state shapes that keep coming back: a line, a knapsack over capacity, two sequences, increasing subsequences, palindromes, grids, intervals, state machines (the stock problems), bitmasks over a small set, and the digits of a number.
The patterns
1D / Fibonacci-style
O(n)
Define dp[i] from dp[i−1]/dp[i−2]; usually collapsible to two rolling variables.
Spot it: Count ways or best value along a line where step i depends on i-1, i-2: stairs, house robber, decode ways, word break, take-or-skip.
0/1 Knapsack
O(n · W)
dp over (item, capacity) choosing include vs exclude; iterate capacity backward for the 1D rolling version.
Spot it: Each item take-or-skip under a capacity; can a subset hit exact target T; partition into equal halves; +/- target sum.
Learn first: 1D / Fibonacci-style
Unbounded Knapsack
O(n · W)
Same as 0/1 but iterate capacity forward so an item can be picked again within the same state.
Spot it: Items reusable any number of times: coin change, perfect squares, rod cutting; min count or number of ways to reach a total.
Learn first: 0/1 Knapsack
LCS / Two-Sequence
O(n · m)
2D dp on prefixes (i, j); match advances both, mismatch takes the best of skipping one side.
Spot it: Two strings/arrays compared, aligned, or interleaved: LCS, edit distance, transform A→B, count occurrences as a subsequence.
Learn first: 1D / Fibonacci-style
Longest Increasing Subsequence
O(n log n)
O(n²) dp[i] = best ending at i, or O(n log n) patience: binary-search each value into tails[].
Spot it: Longest increasing or chain subsequence in one array (increasing, divisible, nested envelopes), or min deletions to make it sorted.
Learn first: 1D / Fibonacci-style, Binary Search
Palindromic Substrings
O(n²)
Expand around centers, or 2D dp where dp[i][j] depends on dp[i+1][j−1] plus matching ends.
Spot it: Longest palindromic substring/subsequence, count palindromic substrings, or min cuts to split into palindromes.
Learn first: Interval DP
Grid / Matrix DP
O(n · m)
dp[r][c] combines the cell value with the best of the cells you could have come from.
Spot it: 2D grid with restricted moves (right/down): count paths, min/max-cost path, largest square of ones, triangle top-to-bottom.
Learn first: 1D / Fibonacci-style
Interval DP
O(n³)
dp[i][j] = best over all k of (left part + right part + cost of combining); fill by increasing length.
Spot it: Solve a range [i..j] by trying every split k: burst balloons, matrix chain, cut a stick, merge stones, two players taking from ends.
Learn first: 1D / Fibonacci-style
State Machine DP (Stocks)
O(n · k)
Track dp for each state (holding / sold / rest) and transition day by day.
Spot it: Buy/sell with rules (cooldown, fee, at most k transactions), or a few modes per position that change what you can do next.
Learn first: 1D / Fibonacci-style
Bitmask DP
O(2ⁿ · n)
Encode the set of used/visited elements as an integer bitmask and memoize over (mask, position).
Spot it: Tiny n (<= ~20, sometimes 15-16 with an extra factor); visit/assign/order everything: TSP, Hamiltonian path, k-partition.
Learn first: Bit Tricks & Bitmasking, Subsets / Permutations / Combinations, 1D / Fibonacci-style
Digit DP
O(digits · states)
Build the number digit by digit with a 'tight' flag tracking whether you're still bounded by the limit.
Spot it: Count integers in [L, R] (N up to 1e18) whose digits satisfy a constraint; answer = f(R) - f(L-1).
Learn first: 1D / Fibonacci-style, Math / Number Theory
Which one? Match the signal
| If the problem says | Reach for |
|---|---|
| Count ways / max value where state depends on the previous one or two | DP · 1D / Fibonacci |
| Each item is take-or-skip under a capacity; subset hits a target; equal partition | DP · 0/1 Knapsack |
| Items reusable any number of times: coin change, perfect squares, rod cutting | DP · Unbounded Knapsack |
| Two strings/arrays compared: edit distance, longest common subsequence, align | DP · LCS family |
| Longest increasing / chain subsequence in one ordered array | DP · LIS |
| Longest palindromic sub-string/-sequence, or fewest palindrome cuts | DP · Palindrome |
| 2D grid, move right/down: count paths or min/max-cost path | DP · Grid |
| Solve a range [i..j] by trying every split point k (burst balloons, matrix chain) | DP · Interval |
| Buy/sell stock with states — cooldown, fees, or at-most-k transactions | DP · State Machine |
| Tiny n (≤ ~20) and you must "visit all" / assign everything | DP · Bitmask |
| Count how many numbers in [L, R] satisfy a digit constraint | DP · Digit |
Easy to confuse
Maximum Length of Pair Chain looks like Longest Increasing Subsequence, but it’s Interval Scheduling (sort by end)
LIS DP works in O(n2) but sorting by end and greedy is optimal in O(n log n).
Russian Doll Envelopes looks like Greedy, but it’s Longest Increasing Subsequence
Greedy by width fails; sort (w asc, h desc) and run LIS on heights.
Longest Increasing Path in a Matrix looks like Grid / Matrix DP, but it’s Topological Sort
Moves go in four directions, so there is no row-major order; the strict increase makes a DAG for memo DFS / Kahn.
House Robber III looks like 1D / Fibonacci-style, but it’s DP on Trees
Same take/skip idea but on a tree: dp[v] = (take, skip) from children.
Delete and Earn looks like Greedy, but it’s 1D / Fibonacci-style
Taking x deletes x-1 and x+1: after bucketing values it is house robber.
Jump Game II looks like 1D / Fibonacci-style, but it’s Greedy
O(n2) DP works but the greedy BFS over reach windows is O(n).
Used together
1D / Fibonacci-style + Monotonic Deque
When: jump at most k steps; subsequence with gaps at most k. Transition dp[i] = f(i) + max(dp[i-k..i-1]) is O(nk) naively.
Topological Sort + 1D / Fibonacci-style
When: longest path / number of paths in a DAG; longest increasing path in a grid. DP needs an acyclic evaluation order.
Strongly Connected Components & Condensation + Topological Sort + 1D / Fibonacci-style
When: maximum total collected on a walk in a directed graph with cycles. Cycles let you collect everything in an SCC; across SCCs it is a DAG DP.
Dijkstra (Weighted Shortest Path) + 1D / Fibonacci-style
When: number of shortest paths; min/max edges among shortest paths. Counting shortest paths needs an order where all shortest predecessors are final.
1D / Fibonacci-style
- Climbing StairsEasy
- Min Cost Climbing StairsEasy
0/1 Knapsack
- Book ShopMedium
- Partition Equal Subset SumMedium
Unbounded Knapsack
- Coin ChangeMedium
- Minimizing CoinsEasy
LCS / Two-Sequence
- Longest Common SubsequenceMedium
- Delete Operation for Two StringsMedium
Longest Increasing Subsequence
- Longest Increasing SubsequenceMedium
- Increasing SubsequenceMedium
Palindromic Substrings
- Palindromic SubstringsMedium
- Longest Palindromic SubstringMedium
Grid / Matrix DP
- Unique PathsMedium
- Unique Paths IIMedium
Interval DP
- Stone GameMedium
- Removal GameMedium
State Machine DP (Stocks)
- Best Time to Buy and Sell StockEasy
- Best Time to Buy and Sell Stock IIMedium
Bitmask DP
- Can I WinMedium
- Partition to K Equal Sum SubsetsMedium
Digit DP
- Count Numbers with Unique DigitsMedium
- Numbers At Most N Given Digit SetHard
Further reading
- DP lecture notesErrichto
Lecture series from Fibonacci to hard problems; how to define states.
- AtCoder Educational DP ContestAtCoder
26 pure DP problems covering knapsack, interval, bitmask, digit DP.
- Introduction to DPUSACO Guide
Knapsack, LIS, paths on grids with graded problems.
- Dynamic Programming PatternsLeetCode discuss
Groups LeetCode DP problems into reusable patterns.
- Dynamic Programming playlistAditya Verma
Pattern-wise DP (knapsack, LCS, MCM) from recursion to tabulation.
- Bitmask DPUSACO Guide
Subset states and TSP-style DP.
- Digit DPCodeforces
Standard digit DP template with worked problems.