Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns

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

  1. 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.

    Learn 1D / Fibonacci-styleCheat sheet and practice
  2. 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

    Learn 0/1 KnapsackCheat sheet and practice
  3. 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

    Learn Unbounded KnapsackCheat sheet and practice
  4. 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

    Learn LCS / Two-SequenceCheat sheet and practice
  5. 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

    Learn Longest Increasing SubsequenceCheat sheet and practice
  6. 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

    Learn Palindromic SubstringsCheat sheet and practice
  7. 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

    Learn Grid / Matrix DPCheat sheet and practice
  8. 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

    Learn Interval DPCheat sheet and practice
  9. 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

    Learn State Machine DPCheat sheet and practice
  10. 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

    Learn Bitmask DPCheat sheet and practice
  11. 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

    Learn Digit DPCheat sheet and practice

Which one? Match the signal

If the problem saysReach for
Count ways / max value where state depends on the previous one or twoDP · 1D / FibonacciO(n)
Each item is take-or-skip under a capacity; subset hits a target; equal partitionDP · 0/1 KnapsackO(n·W)
Items reusable any number of times: coin change, perfect squares, rod cuttingDP · Unbounded KnapsackO(n·W)
Two strings/arrays compared: edit distance, longest common subsequence, alignDP · LCS familyO(n·m)
Longest increasing / chain subsequence in one ordered arrayDP · LISO(n log n)
Longest palindromic sub-string/-sequence, or fewest palindrome cutsDP · PalindromeO(n²)
2D grid, move right/down: count paths or min/max-cost pathDP · GridO(n·m)
Solve a range [i..j] by trying every split point k (burst balloons, matrix chain)DP · IntervalO(n³)
Buy/sell stock with states — cooldown, fees, or at-most-k transactionsDP · State MachineO(n·k)
Tiny n (≤ ~20) and you must "visit all" / assign everythingDP · BitmaskO(2ⁿ·n)
Count how many numbers in [L, R] satisfy a digit constraintDP · DigitO(digits)

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.

Where to start

then the The 128 and The 365 sheets

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

free, outside Lessgo
  • 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.

← GraphsAll 49 patternsStacks, Queues & Deques →
TodayReviewPatternsProblems