Pattern 17 of 22

Dynamic Programming Pattern: Template + 481 LeetCode Problems

Define a state, write the transition, and stop recomputing the same subproblem.

Easy
12
Medium
243
Hard
226

What the dynamic programming pattern is

Dynamic programming applies when a problem has optimal substructure — the best answer is built from the best answers to smaller versions — and overlapping subproblems, meaning the naive recursion asks the same question many times. The work is entirely in the first line: choosing a state, the smallest set of numbers that fully describes a subproblem. Everything else follows, because the transition is just the answer to "what were the last choices that could have led here?" and the base case is the state small enough to answer without recursing. Write it as recursion with a cache first; that version is easier to get right because the transition reads like the problem statement. Convert to a bottom-up table only once it works, and only for the two things a table buys: no recursion limit, and the chance to notice that row i depends only on row i-1, which is what collapses an O(n·m) table into O(m) space.

When to use it

  • The problem asks for a count, a maximum, a minimum, or whether something is possible — not for the arrangement itself.
  • A greedy choice is provably wrong because a locally worse choice can lead to a better total.
  • The naive recursion is exponential and its calls repeat with identical arguments.
  • The input has an obvious ordering — a prefix, an index range, a remaining capacity — to index the state by.

The dynamic programming template in Python

The shape, not a solution to any one problem. Adapt the condition and the summary being maintained; the skeleton stays the same across the 481 problems listed below.

PythonDynamic Programming template
def rob(nums):
    """The canonical 1-D shape: dp[i] is the answer for the prefix nums[:i]."""
    if not nums:
        return 0

    dp = [0] * (len(nums) + 1)
    dp[1] = nums[0]                                   # base case

    for i in range(2, len(nums) + 1):                 # transition
        dp[i] = max(dp[i - 1],                        # skip nums[i - 1]
                    dp[i - 2] + nums[i - 1])          # take it, so skip its neighbour

    return dp[len(nums)]

Complexity characteristics

Time
O(states × transitions)
Auxiliary space
O(states), frequently reducible

The running time is the number of distinct states multiplied by the work done at each one, which is why choosing the state is the whole problem: a one-dimensional state over a prefix gives O(n), a two-dimensional state over two strings gives O(n·m), and a bitmask state over n items gives O(2ⁿ·n). Memoised recursion and a bottom-up table share the same complexity and differ only in constant factors and stack depth. The space often collapses — when row i depends only on row i−1, an O(n·m) table becomes O(m).

Eyes only

Meet the dynamic programming problem you did not practise.

In the live round, Stealth Interview reads the problem off your screen, returns a working solution with a step-by-step explanation and its time and space complexity, and transcribes what the interviewer says. It's a desktop app for macOS and Windows, invisible to screen sharing.

All 481 dynamic programming LeetCode problems

Every problem in the library the dynamic programming pattern applies to, grouped by LeetCode's own difficulty rating. 416 of the 481 carry a complete Python solution with a worked example and complexity analysis; the rest are listed for completeness, with the LeetCode Premium ones marked.

Easy (12)

Easy problems
No.Problem
0070Climbing Stairs
0118Pascal's Triangle
0119Pascal's Triangle II
0121Best Time to Buy and Sell Stock
0338Counting Bits
0392Is Subsequence
0509Fibonacci Number
0746Min Cost Climbing Stairs
1137N-th Tribonacci Number
1025Divisor Game
1668Maximum Repeating Substring
2900Longest Unequal Adjacent Groups Subsequence I

Medium (243)

Medium problems
No.Problem
0005Longest Palindromic Substring
0022Generate Parentheses
0045Jump Game II
0053Maximum Subarray
0055Jump Game
0062Unique Paths
0063Unique Paths II
0064Minimum Path Sum
0072Edit Distance
0091Decode Ways
0095Unique Binary Search Trees II
0096Unique Binary Search Trees
0097Interleaving String
0120Triangle
0122Best Time to Buy and Sell Stock II
0131Palindrome Partitioning
0139Word Break
0152Maximum Product Subarray
0198House Robber
0213House Robber II
0221Maximal Square
0241Different Ways to Add Parentheses
0264Ugly Number II
0279Perfect Squares
0300Longest Increasing Subsequence
0309Best Time to Buy and Sell Stock with Cooldown
0313Super Ugly Number
0322Coin Change
0337House Robber III
0343Integer Break
0357Count Numbers with Unique Digits
0368Largest Divisible Subset
0375Guess Number Higher or Lower II
0376Wiggle Subsequence
0377Combination Sum IV
0396Rotate Function
0397Integer Replacement
0413Arithmetic Slices
0416Partition Equal Subset Sum
0435Non-overlapping Intervals
0464Can I Win
0467Unique Substrings in Wraparound String
0473Matchsticks to Square
0474Ones and Zeroes
0486Predict the Winner
0494Target Sum
0516Longest Palindromic Subsequence
0518Coin Change II
0526Beautiful Arrangement
054201 Matrix
0553Optimal Division
0576Out of Boundary Paths
0583Delete Operation for Two Strings
0638Shopping Offers
0646Maximum Length of Pair Chain
0647Palindromic Substrings
06502 Keys Keyboard
0673Number of Longest Increasing Subsequence
0678Valid Parenthesis String
0688Knight Probability in Chessboard
0698Partition to K Equal Sum Subsets
0712Minimum ASCII Delete Sum for Two Strings
0714Best Time to Buy and Sell Stock with Transaction Fee
0718Maximum Length of Repeated Subarray
0740Delete and Earn
0787Cheapest Flights Within K Stops
0790Domino and Tromino Tiling
0918Maximum Sum Circular Subarray
1143Longest Common Subsequence
1372Longest ZigZag Path in a Binary Tree
1493Longest Subarray of 1's After Deleting One Element
0256Paint HousePremium
0276Paint FencePremium
0294Flip Game IIPremium
0333Largest BST SubtreePremium
0351Android Unlock PatternsPremium
0361Bomb EnemyPremium
0418Sentence Screen FittingPremium
0487Max Consecutive Ones IIPremium
0562Longest Line of Consecutive One in MatrixPremium
0634Find the Derangement of An ArrayPremium
06514 Keys KeyboardPremium
0750Number Of Corner RectanglesPremium
0764Largest Plus Sign
0788Rotated Digits
0792Number of Matching Subsequences
0799Champagne Tower
0808Soup Servings
0813Largest Sum of Averages
0823Binary Trees With Factors
0837New 21 Game
0838Push Dominoes
0845Longest Mountain in Array
0873Length of Longest Fibonacci Subsequence
0877Stone Game
0894All Possible Full Binary Trees
0898Bitwise ORs of Subarrays
0907Sum of Subarray Minimums
0926Flip String to Monotone Increasing
0931Minimum Falling Path Sum
0935Knight Dialer
0978Longest Turbulent Subarray
0983Minimum Cost For Tickets
1014Best Sightseeing Pair
1024Video Stitching
1027Longest Arithmetic Subsequence
1031Maximum Sum of Two Non-Overlapping Subarrays
1035Uncrossed Lines
1039Minimum Score Triangulation of Polygon
1043Partition Array for Maximum Sum
1048Longest String Chain
1049Last Stone Weight II
1062Longest Repeating SubstringPremium
1066Campus Bikes IIPremium
1105Filling Bookcase Shelves
1130Minimum Cost Tree From Leaf Values
1139Largest 1-Bordered Square
1140Stone Game II
1155Number of Dice Rolls With Target Sum
1162As Far from Land as Possible
1182Shortest Distance to Target ColorPremium
1186Maximum Subarray Sum with One Deletion
1191K-Concatenation Maximum Sum
1218Longest Arithmetic Subsequence of Given Difference
1227Airplane Seat Assignment Probability
1230Toss Strange CoinsPremium
1262Greatest Sum Divisible by Three
1277Count Square Submatrices with All Ones
1334Find the City With the Smallest Number of Neighbors at a Threshold Distance
1387Sort Integers by The Power Value
1395Count Number of Teams
1477Find Two Non-overlapping Sub-arrays Each With Target Sum
1504Count Submatrices With All Ones
1524Number of Sub-arrays With Odd Sum
1525Number of Good Ways to Split a String
1567Maximum Length of Subarray With Positive Product
1578Minimum Time to Make Rope Colorful
1594Maximum Non Negative Product in a Matrix
1621Number of Sets of K Non-Overlapping Line Segments
1626Best Team With No Conflicts
1638Count Substrings That Differ by One Character
1641Count Sorted Vowel Strings
1653Minimum Deletions to Make String Balanced
1654Minimum Jumps to Reach Home
1682Longest Palindromic Subsequence IIPremium
1690Stone Game VII
1696Jump Game VI
1746Maximum Subarray Sum After One OperationPremium
1749Maximum Absolute Sum of Any Subarray
1774Closest Dessert Cost
1786Number of Restricted Paths From First to Last Node
1824Minimum Sideway Jumps
1871Jump Game VII
1884Egg Drop With 2 Eggs and N Floors
1888Minimum Number of Flips to Make the Binary String Alternating
1908Game of NimPremium
1911Maximum Alternating Subsequence Sum
1937Maximum Number of Points with Cost
1947Maximum Compatibility Score Sum
1959Minimum Total Space Wasted With K Resizing Operations
1976Number of Ways to Arrive at Destination
1981Minimize the Difference Between Target and Chosen Elements
1986Minimum Number of Work Sessions to Finish the Tasks
1997First Day Where You Have Been in All the Rooms
2002Maximum Product of the Length of Two Palindromic Subsequences
2008Maximum Earnings From Taxi
2036Maximum Alternating Subarray SumPremium
2052Minimum Cost to Separate Sentence Into RowsPremium
2054Two Best Non-Overlapping Events
2063Vowels of All Substrings
2086Minimum Number of Food Buckets to Feed the Hamsters
2100Find Good Days to Rob the Bank
2110Number of Smooth Descent Periods of a Stock
2140Solving Questions With Brainpower
2152Minimum Number of Lines to Cover PointsPremium
2184Number of Ways to Build Sturdy Brick WallPremium
2189Number of Ways to Build House of CardsPremium
2222Number of Ways to Select Buildings
2266Count Number of Texts
2291Maximum Profit From Trading StocksPremium
2297Jump Game VIIIPremium
2304Minimum Path Cost in a Grid
2305Fair Distribution of Cookies
2310Sum of Numbers With Units Digit K
2311Longest Binary Subsequence Less Than or Equal to K
2320Count Number of Ways to Place Houses
2327Number of People Aware of a Secret
2369Check if There is a Valid Partition For The Array
2370Longest Ideal Subsequence
2378Choose Edges to Maximize Score in a TreePremium
2380Time Needed to Rearrange a Binary String
2393Count Strictly Increasing SubarraysPremium
2400Number of Ways to Reach a Position After Exactly k Steps
2420Find All Good Indices
2431Maximize Total Tastiness of Purchased FruitsPremium
2436Minimum Split Into Subarrays With GCD Greater Than OnePremium
2439Minimize Maximum of Array
2464Minimum Subarrays in a Valid SplitPremium
2466Count Ways To Build Good Strings
2495Number of Subarrays Having Even ProductPremium
2501Longest Square Streak in an Array
2510Check if There is a Path With Equal Number of 0's And 1'sPremium
2522Partition String Into Substrings With Values at Most K
2533Number of Good Binary StringsPremium
2556Disconnect Path in a Binary Matrix by at Most One Flip
2560House Robber IV
2571Minimum Operations to Reduce an Integer to 0
2572Count the Number of Square-Free Subsets
2597The Number of Beautiful Subsets
2606Find the Substring With Maximum Cost
2616Minimize the Maximum Difference of Pairs
2638Count the Number of K-Free SubsetsPremium
2645Minimum Additions to Make Valid String
2673Make Costs of Paths Equal in a Binary Tree
2684Maximum Number of Moves in a Grid
2707Extra Characters in a String
2708Maximum Strength of a Group
2712Minimum Cost to Make All Characters Equal
2741Special Permutations
2745Construct the Longest New String
2746Decremental String Concatenation
2750Ways to Split Array Into Good Subarrays
2767Partition String Into Minimum Beautiful Substrings
2770Maximum Number of Jumps to Reach the Last Index
2771Longest Non-decreasing Subarray From Two Arrays
2786Visit Array Positions to Maximize Score
2787Ways to Express an Integer as Sum of Powers
2811Check if it is Possible to Split Array
2826Sorting Three Groups
2830Maximize the Profit as the Salesman
2850Minimum Moves to Spread Stones Over Grid
2892Minimizing Array After Replacing Pairs With Their ProductPremium
2896Apply Operations to Make Two Strings Equal
2901Longest Unequal Adjacent Groups Subsequence II
2915Length of the Longest Subsequence That Sums to Target
2919Minimum Increment Operations to Make Array Beautiful
2925Maximum Score After Applying Operations on a Tree
2930Number of Strings Which Can Be Rearranged to Contain Substring
2944Minimum Number of Coins for Fruits
2957Remove Adjacent Almost-Equal Characters
2979Most Expensive Item That Can Not Be BoughtPremium
2992Number of Self-Divisible PermutationsPremium
2998Minimum Number of Operations to Make X and Y Equal

Hard (226)

Hard problems
No.Problem
0010Regular Expression Matching
0032Longest Valid Parentheses
0042Trapping Rain Water
0044Wildcard Matching
0085Maximal Rectangle
0087Scramble String
0115Distinct Subsequences
0123Best Time to Buy and Sell Stock III
0124Binary Tree Maximum Path Sum
0132Palindrome Partitioning II
0140Word Break II
0174Dungeon Game
0188Best Time to Buy and Sell Stock IV
0233Number of Digit One
0312Burst Balloons
0329Longest Increasing Path in a Matrix
0354Russian Doll Envelopes
0403Frog Jump
0410Split Array Largest Sum
0446Arithmetic Slices II - Subsequence
0458Poor Pigs
0466Count The Repetitions
0472Concatenated Words
0488Zuma Game
0514Freedom Trail
0546Remove Boxes
0552Student Attendance Record II
0600Non-negative Integers without Consecutive Ones
0629K Inverse Pairs Array
0639Decode Ways II
0664Strange Printer
0689Maximum Sum of 3 Non-Overlapping Subarrays
0691Stickers to Spell Word
0730Count Different Palindromic Subsequences
0741Cherry Pickup
1235Maximum Profit in Job Scheduling
0265Paint House IIPremium
0465Optimal Account BalancingPremium
0471Encode String with Shortest LengthPremium
0568Maximum Vacation DaysPremium
0656Coin PathPremium
0727Minimum Window SubsequencePremium
0773Sliding Puzzle
0801Minimum Swaps To Make Sequences Increasing
0805Split Array With Same Average
0818Race Car
0828Count Unique Characters of All Substrings of a Given String
0834Sum of Distances in Tree
0847Shortest Path Visiting All Nodes
0871Minimum Number of Refueling Stops
0879Profitable Schemes
0887Super Egg Drop
0902Numbers At Most N Given Digit Set
0903Valid Permutations for DI Sequence
0913Cat and Mouse
0920Number of Music Playlists
0940Distinct Subsequences II
0943Find the Shortest Superstring
0956Tallest Billboard
0960Delete Columns to Make Sorted III
0964Least Operators to Express Number
0968Binary Tree Cameras
0975Odd Even Jump
0996Number of Squareful Arrays
1000Minimum Cost to Merge Stones
1012Numbers With Repeated Digits
1067Digit Count in RangePremium
1092Shortest Common Supersequence
1125Smallest Sufficient Team
1147Longest Chunked Palindrome Decomposition
1187Make Array Strictly Increasing
1216Valid Palindrome IIIPremium
1220Count Vowels Permutation
1223Dice Roll Simulation
1246Palindrome RemovalPremium
1255Maximum Score Words Formed by Letters
1259Handshakes That Don't CrossPremium
1269Number of Ways to Stay in the Same Place After Some Steps
1278Palindrome Partitioning III
1289Minimum Falling Path Sum II
1301Number of Paths with Max Score
1312Minimum Insertion Steps to Make a String Palindrome
1320Minimum Distance to Type a Word Using Two Fingers
1326Minimum Number of Taps to Open to Water a Garden
1335Minimum Difficulty of a Job Schedule
1340Jump Game V
1349Maximum Students Taking Exam
1359Count All Valid Pickup and Delivery Options
1363Largest Multiple of Three
1373Maximum Sum BST in Binary Tree
1388Pizza With 3n Slices
1397Find All Good Strings
1402Reducing Dishes
1406Stone Game III
1411Number of Ways to Paint N × 3 Grid
1416Restore The Array
1420Build Array Where You Can Find The Maximum Exactly K Comparisons
1425Constrained Subsequence Sum
1434Number of Ways to Wear Different Hats to Each Other
1444Number of Ways of Cutting a Pizza
1449Form Largest Integer With Digits That Add up to Target
1458Max Dot Product of Two Subsequences
1463Cherry Pickup II
1467Probability of a Two Boxes Having The Same Number of Distinct Balls
1473Paint House III
1478Allocate Mailboxes
1483Kth Ancestor of a Tree Node
1494Parallel Courses II
1510Stone Game IV
1526Minimum Number of Increments on Subarrays to Form a Target Array
1531String Compression II
1537Get the Maximum Score
1547Minimum Cost to Cut a Stick
1548The Most Similar Path in a GraphPremium
1553Minimum Number of Days to Eat N Oranges
1563Stone Game V
1569Number of Ways to Reorder Array to Get Same BST
1575Count All Possible Routes
1595Minimum Cost to Connect Two Groups of Points
1611Minimum One Bit Operations to Make Integers Zero
1617Count Subtrees With Max Distance Between Cities
1639Number of Ways to Form a Target String Given a Dictionary
1643Kth Smallest Instructions
1655Distribute Repeating Integers
1659Maximize Grid Happiness
1671Minimum Number of Removals to Make Mountain Array
1681Minimum Incompatibility
1687Delivering Boxes from Storage to Ports
1691Maximum Height by Stacking Cuboids
1692Count Ways to Distribute CandiesPremium
1714Sum Of Special Evenly-Spaced Elements In ArrayPremium
1723Find Minimum Time to Finish All Jobs
1728Cat and Mouse II
1735Count Ways to Make Array With Product
1745Palindrome Partitioning IV
1751Maximum Number of Events That Can Be Attended II
1755Closest Subsequence Sum
1770Maximum Score from Performing Multiplication Operations
1771Maximize Palindrome Length From Subsequences
1787Make the XOR of All Segments Equal to Zero
1799Maximize Score After N Operations
1815Maximum Number of Groups Getting Fresh Donuts
1857Largest Color Value in a Directed Graph
1866Number of Ways to Rearrange Sticks With K Sticks Visible
1872Stone Game VIII
1879Minimum XOR Sum of Two Arrays
1883Minimum Skips to Arrive at Meeting On Time
1896Minimum Cost to Change the Final Value of Expression
1900The Earliest and Latest Rounds Where Players Compete
1916Count Ways to Build Rooms in an Ant Colony
1928Minimum Cost to Reach Destination in Time
1931Painting a Grid With Three Different Colors
1955Count Number of Special Subsequences
1977Number of Ways to Separate Numbers
1987Number of Unique Good Subsequences
1994The Number of Good Subsets
2003Smallest Missing Genetic Value in Each Subtree
2005Subtree Removal Game with Fibonacci TreePremium
2019The Score of Students Solving Math Expression
2035Partition Array Into Two Arrays to Minimize Sum Difference
2050Parallel Courses III
2060Check if an Original String Exists Given Two Encoded Strings
2088Count Fertile Pyramids in a Land
2143Choose Numbers From Two Arrays in RangePremium
2147Number of Ways to Divide a Long Corridor
2163Minimum Difference in Sums After Removal of Elements
2167Minimum Time to Remove All Cars Containing Illegal Goods
2172Maximum AND Sum of Array
2188Minimum Time to Finish the Race
2209Minimum White Tiles After Covering With Carpets
2218Maximum Value of K Coins From Piles
2247Maximum Cost of Trip With K HighwaysPremium
2262Total Appeal of A String
2263Make Array Non-decreasing or Non-increasingPremium
2267Check if There Is a Valid Parentheses String Path
2272Substring With Largest Variance
2312Selling Pieces of Wood
2313Minimum Flips in Binary Tree to Get ResultPremium
2318Number of Distinct Roll Sequences
2321Maximum Score Of Spliced Array
2328Number of Increasing Paths in a Grid
2338Count the Number of Ideal Arrays
2355Maximum Number of Books You Can TakePremium
2361Minimum Costs Using the Train LinePremium
2376Count Special Integers
2403Minimum Time to Kill All MonstersPremium
2407Longest Increasing Subsequence II
2430Maximum Deletions on a String
2435Paths in Matrix Whose Sum Is Divisible by K
2463Minimum Total Distance Traveled
2472Maximum Number of Non-overlapping Palindrome Substrings
2478Number of Beautiful Partitions
2484Count Palindromic Subsequences
2518Number of Great Partitions
2538Difference Between Maximum and Minimum Price Sum
2547Minimum Cost to Split an Array
2552Count Increasing Quadruplets
2573Find the String with LCP
2581Count Number of Possible Root Nodes
2585Number of Ways to Earn Points
2617Minimum Number of Visited Cells in a Grid
2646Minimize the Total Price of the Trips
2681Power of Heroes
2713Maximum Strictly Increasing Cells in a Matrix
2719Count of Integers
2742Painting the Walls
2791Count Paths That Can Form a Palindrome in a Tree
2801Count Stepping Numbers in Range
2809Minimum Time to Make Array Sum At Most x
2827Number of Beautiful Integers in the Range
2836Maximize Value of Function in a Ball Passing Game
2851String Transformation
2858Minimum Edge Reversals So Every Node Is Reachable
2867Count Valid Paths in a Tree
2876Count Visited Nodes in a Directed Graph
2902Count of Sub-Multisets With Bounded Sum
2911Minimum Changes to Make K Semi-palindromes
2912Number of Ways to Reach Destination in the GridPremium
2916Subarrays Distinct Element Sum of Squares II
2920Maximum Points After Collecting Coins From All Nodes
2926Maximum Balanced Subsequence Sum
2945Find Maximum Non-decreasing Array Length
2969Minimum Number of Coins for Fruits IIPremium
2973Find Number of Coins to Place in Tree Nodes
2977Minimum Cost to Convert String II
2999Count the Number of Powerful Integers

Dynamic Programming pattern FAQ

What is the dynamic programming pattern?

Dynamic programming applies when a problem has optimal substructure — the best answer is built from the best answers to smaller versions — and overlapping subproblems, meaning the naive recursion asks the same question many times.

How many LeetCode problems use the dynamic programming pattern?

This page lists 481 LeetCode problems that the dynamic programming pattern applies to: 12 Easy, 243 Medium and 226 Hard. 416 of them carry a complete Python solution with complexity analysis.

What is the time complexity of the dynamic programming pattern?

O(states × transitions) time and O(states), frequently reducible space. The running time is the number of distinct states multiplied by the work done at each one, which is why choosing the state is the whole problem: a one-dimensional state over a prefix gives O(n), a two-dimensional state over two strings gives O(n·m), and a bitmask state over n items gives O(2ⁿ·n). Memoised recursion and a bottom-up table share the same complexity and differ only in constant factors and stack depth. The space often collapses — when row i depends only on row i−1, an O(n·m) table becomes O(m).

When should I use the dynamic programming pattern in an interview?

The problem asks for a count, a maximum, a minimum, or whether something is possible — not for the arrangement itself. A greedy choice is provably wrong because a locally worse choice can lead to a better total.

Which dynamic programming problem should I start with?

LeetCode 70. Climbing Stairs is the lowest-numbered Easy problem on this page, which makes it the usual starting point: the technique is visible without the problem's own complications getting in the way.

What patterns are related to dynamic programming?

Backtracking, Greedy, Prefix Sum, Bit Manipulation. Problems frequently sit in more than one of these, and the overlap is where the interesting follow-up questions come from.

More ways in: all 22 patterns, the curated study lists, or the full problem list.