Dynamic Programming Pattern: Template + 481 LeetCode Problems

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

  • 12 Easy
  • 243 Medium
  • 226 Hard
  • O(states × transitions) time

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.

Dynamic Programming — Python 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).

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)

#ProblemDifficultyTopics
70Climbing StairsEasyMemoization, Math, Dynamic Programming
118Pascal's TriangleEasyArray, Dynamic Programming
119Pascal's Triangle IIEasyArray, Dynamic Programming
121Best Time to Buy and Sell StockEasyArray, Dynamic Programming
338Counting BitsEasyBit Manipulation, Dynamic Programming
392Is SubsequenceEasyTwo Pointers, String, Dynamic Programming
509Fibonacci NumberEasyRecursion, Memoization, Math +1
746Min Cost Climbing StairsEasyArray, Dynamic Programming
1137N-th Tribonacci NumberEasyMemoization, Math, Dynamic Programming
1025Divisor GameEasyBrainteaser, Math, Dynamic Programming +1
1668Maximum Repeating SubstringEasyString, Dynamic Programming, String Matching
2900Longest Unequal Adjacent Groups Subsequence IEasyGreedy, Array, String +1

Medium (243)

#ProblemDifficultyTopics
5Longest Palindromic SubstringMediumTwo Pointers, String, Dynamic Programming
22Generate ParenthesesMediumString, Dynamic Programming, Backtracking
45Jump Game IIMediumGreedy, Array, Dynamic Programming
53Maximum SubarrayMediumArray, Divide and Conquer, Dynamic Programming
55Jump GameMediumGreedy, Array, Dynamic Programming
62Unique PathsMediumMath, Dynamic Programming, Combinatorics
63Unique Paths IIMediumArray, Dynamic Programming, Matrix
64Minimum Path SumMediumArray, Dynamic Programming, Matrix
72Edit DistanceMediumString, Dynamic Programming
91Decode WaysMediumString, Dynamic Programming
95Unique Binary Search Trees IIMediumTree, Binary Search Tree, Dynamic Programming +2
96Unique Binary Search TreesMediumTree, Binary Search Tree, Math +2
97Interleaving StringMediumString, Dynamic Programming
120TriangleMediumArray, Dynamic Programming
122Best Time to Buy and Sell Stock IIMediumGreedy, Array, Dynamic Programming
131Palindrome PartitioningMediumString, Dynamic Programming, Backtracking
139Word BreakMediumTrie, Memoization, Array +3
152Maximum Product SubarrayMediumArray, Dynamic Programming
198House RobberMediumArray, Dynamic Programming
213House Robber IIMediumArray, Dynamic Programming
221Maximal SquareMediumArray, Dynamic Programming, Matrix
241Different Ways to Add ParenthesesMediumRecursion, Memoization, Math +2
264Ugly Number IIMediumHash Table, Math, Dynamic Programming +1
279Perfect SquaresMediumBreadth-First Search, Math, Dynamic Programming
300Longest Increasing SubsequenceMediumArray, Binary Search, Dynamic Programming
309Best Time to Buy and Sell Stock with CooldownMediumArray, Dynamic Programming
313Super Ugly NumberMediumArray, Math, Dynamic Programming
322Coin ChangeMediumBreadth-First Search, Array, Dynamic Programming
337House Robber IIIMediumTree, Depth-First Search, Dynamic Programming +1
343Integer BreakMediumMath, Dynamic Programming
357Count Numbers with Unique DigitsMediumMath, Dynamic Programming, Backtracking
368Largest Divisible SubsetMediumArray, Math, Dynamic Programming +1
375Guess Number Higher or Lower IIMediumMath, Dynamic Programming, Game Theory
376Wiggle SubsequenceMediumGreedy, Array, Dynamic Programming
377Combination Sum IVMediumArray, Dynamic Programming
396Rotate FunctionMediumArray, Math, Dynamic Programming
397Integer ReplacementMediumGreedy, Bit Manipulation, Memoization +1
413Arithmetic SlicesMediumArray, Dynamic Programming, Sliding Window
416Partition Equal Subset SumMediumArray, Dynamic Programming
435Non-overlapping IntervalsMediumGreedy, Array, Dynamic Programming +1
464Can I WinMediumBit Manipulation, Memoization, Math +3
467Unique Substrings in Wraparound StringMediumString, Dynamic Programming
473Matchsticks to SquareMediumBit Manipulation, Array, Dynamic Programming +2
474Ones and ZeroesMediumArray, String, Dynamic Programming
486Predict the WinnerMediumRecursion, Array, Math +2
494Target SumMediumArray, Dynamic Programming, Backtracking
516Longest Palindromic SubsequenceMediumString, Dynamic Programming
518Coin Change IIMediumArray, Dynamic Programming
526Beautiful ArrangementMediumBit Manipulation, Array, Dynamic Programming +2
54201 MatrixMediumBreadth-First Search, Array, Dynamic Programming +1
553Optimal DivisionMediumArray, Math, Dynamic Programming
576Out of Boundary PathsMediumDynamic Programming
583Delete Operation for Two StringsMediumString, Dynamic Programming
638Shopping OffersMediumBit Manipulation, Memoization, Array +3
646Maximum Length of Pair ChainMediumGreedy, Array, Dynamic Programming +1
647Palindromic SubstringsMediumTwo Pointers, String, Dynamic Programming
6502 Keys KeyboardMediumMath, Dynamic Programming
673Number of Longest Increasing SubsequenceMediumBinary Indexed Tree, Segment Tree, Array +1
678Valid Parenthesis StringMediumStack, Greedy, String +1
688Knight Probability in ChessboardMediumDynamic Programming
698Partition to K Equal Sum SubsetsMediumBit Manipulation, Memoization, Array +3
712Minimum ASCII Delete Sum for Two StringsMediumString, Dynamic Programming
714Best Time to Buy and Sell Stock with Transaction FeeMediumGreedy, Array, Dynamic Programming
718Maximum Length of Repeated SubarrayMediumArray, Binary Search, Dynamic Programming +3
740Delete and EarnMediumArray, Hash Table, Dynamic Programming
787Cheapest Flights Within K StopsMediumDepth-First Search, Breadth-First Search, Graph +3
790Domino and Tromino TilingMediumDynamic Programming
918Maximum Sum Circular SubarrayMediumQueue, Array, Divide and Conquer +2
1143Longest Common SubsequenceMediumString, Dynamic Programming
1372Longest ZigZag Path in a Binary TreeMediumTree, Depth-First Search, Dynamic Programming +1
1493Longest Subarray of 1's After Deleting One ElementMediumArray, Dynamic Programming, Sliding Window
256Paint HousePremiumMediumArray, Dynamic Programming
276Paint FencePremiumMediumDynamic Programming
294Flip Game IIPremiumMediumMemoization, Math, Dynamic Programming +2
333Largest BST SubtreePremiumMediumTree, Depth-First Search, Binary Search Tree +2
351Android Unlock PatternsPremiumMediumBit Manipulation, Dynamic Programming, Backtracking +1
361Bomb EnemyPremiumMediumArray, Dynamic Programming, Matrix
418Sentence Screen FittingPremiumMediumArray, String, Dynamic Programming
487Max Consecutive Ones IIPremiumMediumArray, Dynamic Programming, Sliding Window
562Longest Line of Consecutive One in MatrixPremiumMediumArray, Dynamic Programming, Matrix
634Find the Derangement of An ArrayPremiumMediumMath, Dynamic Programming, Combinatorics
6514 Keys KeyboardPremiumMediumMath, Dynamic Programming
750Number Of Corner RectanglesPremiumMediumArray, Math, Dynamic Programming +1
764Largest Plus SignMediumArray, Dynamic Programming
788Rotated DigitsMediumMath, Dynamic Programming
792Number of Matching SubsequencesMediumTrie, Array, Hash Table +4
799Champagne TowerMediumDynamic Programming
808Soup ServingsMediumMath, Dynamic Programming, Probability and Statistics
813Largest Sum of AveragesMediumArray, Dynamic Programming, Prefix Sum
823Binary Trees With FactorsMediumArray, Hash Table, Dynamic Programming +1
837New 21 GameMediumMath, Dynamic Programming, Sliding Window +1
838Push DominoesMediumTwo Pointers, String, Dynamic Programming
845Longest Mountain in ArrayMediumArray, Two Pointers, Dynamic Programming +1
873Length of Longest Fibonacci SubsequenceMediumArray, Hash Table, Dynamic Programming
877Stone GameMediumArray, Math, Dynamic Programming +1
894All Possible Full Binary TreesMediumTree, Recursion, Memoization +2
898Bitwise ORs of SubarraysMediumBit Manipulation, Array, Dynamic Programming
907Sum of Subarray MinimumsMediumStack, Array, Dynamic Programming +1
926Flip String to Monotone IncreasingMediumString, Dynamic Programming
931Minimum Falling Path SumMediumArray, Dynamic Programming, Matrix
935Knight DialerMediumDynamic Programming
978Longest Turbulent SubarrayMediumArray, Dynamic Programming, Sliding Window
983Minimum Cost For TicketsMediumArray, Dynamic Programming
1014Best Sightseeing PairMediumArray, Dynamic Programming
1024Video StitchingMediumGreedy, Array, Dynamic Programming
1027Longest Arithmetic SubsequenceMediumArray, Hash Table, Binary Search +1
1031Maximum Sum of Two Non-Overlapping SubarraysMediumArray, Dynamic Programming, Sliding Window
1035Uncrossed LinesMediumArray, Dynamic Programming
1039Minimum Score Triangulation of PolygonMediumArray, Dynamic Programming
1043Partition Array for Maximum SumMediumArray, Dynamic Programming
1048Longest String ChainMediumArray, Hash Table, Two Pointers +3
1049Last Stone Weight IIMediumArray, Dynamic Programming
1062Longest Repeating SubstringPremiumMediumString, Binary Search, Dynamic Programming +3
1066Campus Bikes IIPremiumMediumBit Manipulation, Array, Dynamic Programming +2
1105Filling Bookcase ShelvesMediumArray, Dynamic Programming
1130Minimum Cost Tree From Leaf ValuesMediumStack, Greedy, Array +2
1139Largest 1-Bordered SquareMediumArray, Dynamic Programming, Matrix
1140Stone Game IIMediumArray, Math, Dynamic Programming +2
1155Number of Dice Rolls With Target SumMediumDynamic Programming
1162As Far from Land as PossibleMediumBreadth-First Search, Array, Dynamic Programming +1
1182Shortest Distance to Target ColorPremiumMediumArray, Binary Search, Dynamic Programming
1186Maximum Subarray Sum with One DeletionMediumArray, Dynamic Programming
1191K-Concatenation Maximum SumMediumArray, Dynamic Programming
1218Longest Arithmetic Subsequence of Given DifferenceMediumArray, Hash Table, Dynamic Programming
1227Airplane Seat Assignment ProbabilityMediumBrainteaser, Math, Dynamic Programming +1
1230Toss Strange CoinsPremiumMediumArray, Math, Dynamic Programming +1
1262Greatest Sum Divisible by ThreeMediumGreedy, Array, Dynamic Programming +1
1277Count Square Submatrices with All OnesMediumArray, Dynamic Programming, Matrix
1334Find the City With the Smallest Number of Neighbors at a Threshold DistanceMediumGraph, Dynamic Programming, Shortest Path
1387Sort Integers by The Power ValueMediumMemoization, Dynamic Programming, Sorting
1395Count Number of TeamsMediumBinary Indexed Tree, Segment Tree, Array +1
1477Find Two Non-overlapping Sub-arrays Each With Target SumMediumArray, Hash Table, Binary Search +2
1504Count Submatrices With All OnesMediumStack, Array, Dynamic Programming +2
1524Number of Sub-arrays With Odd SumMediumArray, Math, Dynamic Programming +1
1525Number of Good Ways to Split a StringMediumBit Manipulation, Hash Table, String +1
1567Maximum Length of Subarray With Positive ProductMediumGreedy, Array, Dynamic Programming
1578Minimum Time to Make Rope ColorfulMediumGreedy, Array, String +1
1594Maximum Non Negative Product in a MatrixMediumArray, Dynamic Programming, Matrix
1621Number of Sets of K Non-Overlapping Line SegmentsMediumMath, Dynamic Programming, Combinatorics
1626Best Team With No ConflictsMediumArray, Dynamic Programming, Sorting
1638Count Substrings That Differ by One CharacterMediumHash Table, String, Dynamic Programming +1
1641Count Sorted Vowel StringsMediumMath, Dynamic Programming, Combinatorics
1653Minimum Deletions to Make String BalancedMediumStack, String, Dynamic Programming
1654Minimum Jumps to Reach HomeMediumBreadth-First Search, Array, Dynamic Programming
1682Longest Palindromic Subsequence IIPremiumMediumString, Dynamic Programming
1690Stone Game VIIMediumArray, Math, Dynamic Programming +1
1696Jump Game VIMediumQueue, Array, Dynamic Programming +2
1746Maximum Subarray Sum After One OperationPremiumMediumArray, Dynamic Programming
1749Maximum Absolute Sum of Any SubarrayMediumArray, Dynamic Programming
1774Closest Dessert CostMediumArray, Dynamic Programming, Backtracking
1786Number of Restricted Paths From First to Last NodeMediumGraph, Topological Sort, Dynamic Programming +2
1824Minimum Sideway JumpsMediumGreedy, Array, Dynamic Programming
1871Jump Game VIIMediumString, Dynamic Programming, Prefix Sum +1
1884Egg Drop With 2 Eggs and N FloorsMediumMath, Dynamic Programming
1888Minimum Number of Flips to Make the Binary String AlternatingMediumString, Dynamic Programming, Sliding Window
1908Game of NimPremiumMediumBit Manipulation, Brainteaser, Array +3
1911Maximum Alternating Subsequence SumMediumArray, Dynamic Programming
1937Maximum Number of Points with CostMediumArray, Dynamic Programming, Matrix
1947Maximum Compatibility Score SumMediumBit Manipulation, Array, Dynamic Programming +2
1959Minimum Total Space Wasted With K Resizing OperationsMediumArray, Dynamic Programming
1976Number of Ways to Arrive at DestinationMediumGraph, Topological Sort, Dynamic Programming +1
1981Minimize the Difference Between Target and Chosen ElementsMediumArray, Dynamic Programming, Matrix
1986Minimum Number of Work Sessions to Finish the TasksMediumBit Manipulation, Array, Dynamic Programming +2
1997First Day Where You Have Been in All the RoomsMediumArray, Dynamic Programming
2002Maximum Product of the Length of Two Palindromic SubsequencesMediumBit Manipulation, String, Dynamic Programming +2
2008Maximum Earnings From TaxiMediumArray, Hash Table, Binary Search +2
2036Maximum Alternating Subarray SumPremiumMediumArray, Dynamic Programming
2052Minimum Cost to Separate Sentence Into RowsPremiumMediumArray, Dynamic Programming
2054Two Best Non-Overlapping EventsMediumArray, Binary Search, Dynamic Programming +2
2063Vowels of All SubstringsMediumMath, String, Dynamic Programming +1
2086Minimum Number of Food Buckets to Feed the HamstersMediumGreedy, String, Dynamic Programming
2100Find Good Days to Rob the BankMediumArray, Dynamic Programming, Prefix Sum
2110Number of Smooth Descent Periods of a StockMediumArray, Math, Two Pointers +2
2140Solving Questions With BrainpowerMediumArray, Dynamic Programming
2152Minimum Number of Lines to Cover PointsPremiumMediumBit Manipulation, Geometry, Array +5
2184Number of Ways to Build Sturdy Brick WallPremiumMediumBit Manipulation, Array, Dynamic Programming +1
2189Number of Ways to Build House of CardsPremiumMediumMath, Dynamic Programming
2222Number of Ways to Select BuildingsMediumString, Dynamic Programming, Prefix Sum
2266Count Number of TextsMediumHash Table, Math, String +1
2291Maximum Profit From Trading StocksPremiumMediumArray, Dynamic Programming
2297Jump Game VIIIPremiumMediumStack, Graph, Array +3
2304Minimum Path Cost in a GridMediumArray, Dynamic Programming, Matrix
2305Fair Distribution of CookiesMediumBit Manipulation, Array, Dynamic Programming +2
2310Sum of Numbers With Units Digit KMediumGreedy, Math, Dynamic Programming +1
2311Longest Binary Subsequence Less Than or Equal to KMediumGreedy, Memoization, String +1
2320Count Number of Ways to Place HousesMediumDynamic Programming
2327Number of People Aware of a SecretMediumQueue, Dynamic Programming, Simulation
2369Check if There is a Valid Partition For The ArrayMediumArray, Dynamic Programming
2370Longest Ideal SubsequenceMediumHash Table, String, Dynamic Programming
2378Choose Edges to Maximize Score in a TreePremiumMediumTree, Depth-First Search, Dynamic Programming
2380Time Needed to Rearrange a Binary StringMediumString, Dynamic Programming, Simulation
2393Count Strictly Increasing SubarraysPremiumMediumArray, Math, Dynamic Programming
2400Number of Ways to Reach a Position After Exactly k StepsMediumMath, Dynamic Programming, Combinatorics
2420Find All Good IndicesMediumArray, Dynamic Programming, Prefix Sum
2431Maximize Total Tastiness of Purchased FruitsPremiumMediumArray, Dynamic Programming
2436Minimum Split Into Subarrays With GCD Greater Than OnePremiumMediumGreedy, Array, Math +2
2439Minimize Maximum of ArrayMediumGreedy, Array, Binary Search +2
2464Minimum Subarrays in a Valid SplitPremiumMediumArray, Math, Dynamic Programming +1
2466Count Ways To Build Good StringsMediumDynamic Programming
2495Number of Subarrays Having Even ProductPremiumMediumArray, Math, Dynamic Programming
2501Longest Square Streak in an ArrayMediumArray, Hash Table, Binary Search +2
2510Check if There is a Path With Equal Number of 0's And 1'sPremiumMediumArray, Dynamic Programming, Matrix
2522Partition String Into Substrings With Values at Most KMediumGreedy, String, Dynamic Programming
2533Number of Good Binary StringsPremiumMediumDynamic Programming
2556Disconnect Path in a Binary Matrix by at Most One FlipMediumDepth-First Search, Breadth-First Search, Array +2
2560House Robber IVMediumGreedy, Array, Binary Search +1
2571Minimum Operations to Reduce an Integer to 0MediumGreedy, Bit Manipulation, Dynamic Programming
2572Count the Number of Square-Free SubsetsMediumBit Manipulation, Array, Math +2
2597The Number of Beautiful SubsetsMediumArray, Hash Table, Math +4
2606Find the Substring With Maximum CostMediumArray, Hash Table, String +1
2616Minimize the Maximum Difference of PairsMediumGreedy, Array, Binary Search +2
2638Count the Number of K-Free SubsetsPremiumMediumArray, Math, Dynamic Programming +2
2645Minimum Additions to Make Valid StringMediumStack, Greedy, String +1
2673Make Costs of Paths Equal in a Binary TreeMediumGreedy, Tree, Array +2
2684Maximum Number of Moves in a GridMediumArray, Dynamic Programming, Matrix
2707Extra Characters in a StringMediumTrie, Array, Hash Table +2
2708Maximum Strength of a GroupMediumGreedy, Bit Manipulation, Array +4
2712Minimum Cost to Make All Characters EqualMediumGreedy, String, Dynamic Programming
2741Special PermutationsMediumBit Manipulation, Array, Dynamic Programming +1
2745Construct the Longest New StringMediumGreedy, Brainteaser, Math +1
2746Decremental String ConcatenationMediumArray, String, Dynamic Programming
2750Ways to Split Array Into Good SubarraysMediumArray, Math, Dynamic Programming
2767Partition String Into Minimum Beautiful SubstringsMediumHash Table, String, Dynamic Programming +1
2770Maximum Number of Jumps to Reach the Last IndexMediumArray, Dynamic Programming
2771Longest Non-decreasing Subarray From Two ArraysMediumArray, Dynamic Programming
2786Visit Array Positions to Maximize ScoreMediumArray, Dynamic Programming
2787Ways to Express an Integer as Sum of PowersMediumDynamic Programming
2811Check if it is Possible to Split ArrayMediumGreedy, Array, Dynamic Programming
2826Sorting Three GroupsMediumArray, Binary Search, Dynamic Programming
2830Maximize the Profit as the SalesmanMediumArray, Hash Table, Binary Search +2
2850Minimum Moves to Spread Stones Over GridMediumBreadth-First Search, Array, Dynamic Programming +1
2892Minimizing Array After Replacing Pairs With Their ProductPremiumMediumGreedy, Array, Dynamic Programming
2896Apply Operations to Make Two Strings EqualMediumString, Dynamic Programming
2901Longest Unequal Adjacent Groups Subsequence IIMediumArray, String, Dynamic Programming
2915Length of the Longest Subsequence That Sums to TargetMediumArray, Dynamic Programming
2919Minimum Increment Operations to Make Array BeautifulMediumArray, Dynamic Programming
2925Maximum Score After Applying Operations on a TreeMediumTree, Depth-First Search, Dynamic Programming
2930Number of Strings Which Can Be Rearranged to Contain SubstringMediumMath, Dynamic Programming, Combinatorics
2944Minimum Number of Coins for FruitsMediumQueue, Array, Dynamic Programming +2
2957Remove Adjacent Almost-Equal CharactersMediumGreedy, String, Dynamic Programming
2979Most Expensive Item That Can Not Be BoughtPremiumMediumMath, Dynamic Programming, Number Theory
2992Number of Self-Divisible PermutationsPremiumMediumBit Manipulation, Array, Math +4
2998Minimum Number of Operations to Make X and Y EqualMediumBreadth-First Search, Memoization, Dynamic Programming

Hard (226)

#ProblemDifficultyTopics
10Regular Expression MatchingHardRecursion, String, Dynamic Programming
32Longest Valid ParenthesesHardStack, String, Dynamic Programming
42Trapping Rain WaterHardStack, Array, Two Pointers +2
44Wildcard MatchingHardGreedy, Recursion, String +1
85Maximal RectangleHardStack, Array, Dynamic Programming +2
87Scramble StringHardString, Dynamic Programming
115Distinct SubsequencesHardString, Dynamic Programming
123Best Time to Buy and Sell Stock IIIHardArray, Dynamic Programming
124Binary Tree Maximum Path SumHardTree, Depth-First Search, Dynamic Programming +1
132Palindrome Partitioning IIHardString, Dynamic Programming
140Word Break IIHardTrie, Memoization, Array +4
174Dungeon GameHardArray, Dynamic Programming, Matrix
188Best Time to Buy and Sell Stock IVHardArray, Dynamic Programming
233Number of Digit OneHardRecursion, Math, Dynamic Programming
312Burst BalloonsHardArray, Dynamic Programming
329Longest Increasing Path in a MatrixHardDepth-First Search, Breadth-First Search, Graph +5
354Russian Doll EnvelopesHardArray, Binary Search, Dynamic Programming +1
403Frog JumpHardArray, Dynamic Programming
410Split Array Largest SumHardGreedy, Array, Binary Search +2
446Arithmetic Slices II - SubsequenceHardArray, Dynamic Programming
458Poor PigsHardMath, Dynamic Programming, Combinatorics
466Count The RepetitionsHardString, Dynamic Programming
472Concatenated WordsHardDepth-First Search, Trie, Array +3
488Zuma GameHardStack, Breadth-First Search, Memoization +2
514Freedom TrailHardDepth-First Search, Breadth-First Search, String +1
546Remove BoxesHardMemoization, Array, Dynamic Programming
552Student Attendance Record IIHardDynamic Programming
600Non-negative Integers without Consecutive OnesHardDynamic Programming
629K Inverse Pairs ArrayHardDynamic Programming
639Decode Ways IIHardString, Dynamic Programming
664Strange PrinterHardString, Dynamic Programming
689Maximum Sum of 3 Non-Overlapping SubarraysHardArray, Dynamic Programming, Prefix Sum +1
691Stickers to Spell WordHardBit Manipulation, Memoization, Array +5
730Count Different Palindromic SubsequencesHardString, Dynamic Programming
741Cherry PickupHardArray, Dynamic Programming, Matrix
1235Maximum Profit in Job SchedulingHardArray, Binary Search, Dynamic Programming +1
265Paint House IIPremiumHardArray, Dynamic Programming
465Optimal Account BalancingPremiumHardBit Manipulation, Array, Dynamic Programming +2
471Encode String with Shortest LengthPremiumHardString, Dynamic Programming
568Maximum Vacation DaysPremiumHardArray, Dynamic Programming, Matrix
656Coin PathPremiumHardArray, Dynamic Programming
727Minimum Window SubsequencePremiumHardString, Dynamic Programming, Sliding Window
773Sliding PuzzleHardBreadth-First Search, Memoization, Array +3
801Minimum Swaps To Make Sequences IncreasingHardArray, Dynamic Programming
805Split Array With Same AverageHardBit Manipulation, Array, Math +2
818Race CarHardDynamic Programming
828Count Unique Characters of All Substrings of a Given StringHardHash Table, String, Dynamic Programming
834Sum of Distances in TreeHardTree, Depth-First Search, Graph +1
847Shortest Path Visiting All NodesHardBit Manipulation, Breadth-First Search, Graph +2
871Minimum Number of Refueling StopsHardGreedy, Array, Dynamic Programming +1
879Profitable SchemesHardArray, Dynamic Programming
887Super Egg DropHardMath, Binary Search, Dynamic Programming
902Numbers At Most N Given Digit SetHardArray, Math, String +2
903Valid Permutations for DI SequenceHardString, Dynamic Programming, Prefix Sum
913Cat and MouseHardGraph, Topological Sort, Memoization +3
920Number of Music PlaylistsHardMath, Dynamic Programming, Combinatorics
940Distinct Subsequences IIHardString, Dynamic Programming
943Find the Shortest SuperstringHardBit Manipulation, Array, String +2
956Tallest BillboardHardArray, Dynamic Programming
960Delete Columns to Make Sorted IIIHardArray, String, Dynamic Programming
964Least Operators to Express NumberHardMemoization, Math, Dynamic Programming
968Binary Tree CamerasHardTree, Depth-First Search, Dynamic Programming +1
975Odd Even JumpHardStack, Array, Dynamic Programming +3
996Number of Squareful ArraysHardBit Manipulation, Array, Hash Table +4
1000Minimum Cost to Merge StonesHardArray, Dynamic Programming, Prefix Sum
1012Numbers With Repeated DigitsHardMath, Dynamic Programming
1067Digit Count in RangePremiumHardMath, Dynamic Programming
1092Shortest Common SupersequenceHardString, Dynamic Programming
1125Smallest Sufficient TeamHardBit Manipulation, Array, Dynamic Programming +1
1147Longest Chunked Palindrome DecompositionHardGreedy, Two Pointers, String +3
1187Make Array Strictly IncreasingHardArray, Binary Search, Dynamic Programming +1
1216Valid Palindrome IIIPremiumHardString, Dynamic Programming
1220Count Vowels PermutationHardDynamic Programming
1223Dice Roll SimulationHardArray, Dynamic Programming
1246Palindrome RemovalPremiumHardArray, Dynamic Programming
1255Maximum Score Words Formed by LettersHardBit Manipulation, Array, Hash Table +5
1259Handshakes That Don't CrossPremiumHardMath, Dynamic Programming
1269Number of Ways to Stay in the Same Place After Some StepsHardDynamic Programming
1278Palindrome Partitioning IIIHardString, Dynamic Programming
1289Minimum Falling Path Sum IIHardArray, Dynamic Programming, Matrix
1301Number of Paths with Max ScoreHardArray, Dynamic Programming, Matrix
1312Minimum Insertion Steps to Make a String PalindromeHardString, Dynamic Programming
1320Minimum Distance to Type a Word Using Two FingersHardString, Dynamic Programming
1326Minimum Number of Taps to Open to Water a GardenHardGreedy, Array, Dynamic Programming
1335Minimum Difficulty of a Job ScheduleHardArray, Dynamic Programming
1340Jump Game VHardArray, Dynamic Programming, Sorting
1349Maximum Students Taking ExamHardBit Manipulation, Array, Dynamic Programming +2
1359Count All Valid Pickup and Delivery OptionsHardMath, Dynamic Programming, Combinatorics
1363Largest Multiple of ThreeHardGreedy, Array, Math +2
1373Maximum Sum BST in Binary TreeHardTree, Depth-First Search, Binary Search Tree +2
1388Pizza With 3n SlicesHardGreedy, Array, Dynamic Programming +1
1397Find All Good StringsHardString, Dynamic Programming, String Matching
1402Reducing DishesHardGreedy, Array, Dynamic Programming +1
1406Stone Game IIIHardArray, Math, Dynamic Programming +1
1411Number of Ways to Paint N × 3 GridHardDynamic Programming
1416Restore The ArrayHardString, Dynamic Programming
1420Build Array Where You Can Find The Maximum Exactly K ComparisonsHardDynamic Programming, Prefix Sum
1425Constrained Subsequence SumHardQueue, Array, Dynamic Programming +3
1434Number of Ways to Wear Different Hats to Each OtherHardBit Manipulation, Array, Dynamic Programming +1
1444Number of Ways of Cutting a PizzaHardMemoization, Array, Dynamic Programming +2
1449Form Largest Integer With Digits That Add up to TargetHardArray, Dynamic Programming
1458Max Dot Product of Two SubsequencesHardArray, Dynamic Programming
1463Cherry Pickup IIHardArray, Dynamic Programming, Matrix
1467Probability of a Two Boxes Having The Same Number of Distinct BallsHardArray, Math, Dynamic Programming +3
1473Paint House IIIHardArray, Dynamic Programming
1478Allocate MailboxesHardArray, Math, Dynamic Programming +1
1483Kth Ancestor of a Tree NodeHardBit Manipulation, Tree, Depth-First Search +4
1494Parallel Courses IIHardBit Manipulation, Graph, Dynamic Programming +1
1510Stone Game IVHardMath, Dynamic Programming, Game Theory
1526Minimum Number of Increments on Subarrays to Form a Target ArrayHardStack, Greedy, Array +2
1531String Compression IIHardString, Dynamic Programming
1537Get the Maximum ScoreHardGreedy, Array, Two Pointers +1
1547Minimum Cost to Cut a StickHardArray, Dynamic Programming, Sorting
1548The Most Similar Path in a GraphPremiumHardGraph, Dynamic Programming
1553Minimum Number of Days to Eat N OrangesHardMemoization, Dynamic Programming
1563Stone Game VHardArray, Math, Dynamic Programming +1
1569Number of Ways to Reorder Array to Get Same BSTHardTree, Union Find, Binary Search Tree +7
1575Count All Possible RoutesHardMemoization, Array, Dynamic Programming
1595Minimum Cost to Connect Two Groups of PointsHardBit Manipulation, Array, Dynamic Programming +2
1611Minimum One Bit Operations to Make Integers ZeroHardBit Manipulation, Memoization, Dynamic Programming
1617Count Subtrees With Max Distance Between CitiesHardBit Manipulation, Tree, Dynamic Programming +2
1639Number of Ways to Form a Target String Given a DictionaryHardArray, String, Dynamic Programming
1643Kth Smallest InstructionsHardArray, Math, Dynamic Programming +1
1655Distribute Repeating IntegersHardBit Manipulation, Array, Dynamic Programming +2
1659Maximize Grid HappinessHardBit Manipulation, Memoization, Dynamic Programming +1
1671Minimum Number of Removals to Make Mountain ArrayHardGreedy, Array, Binary Search +1
1681Minimum IncompatibilityHardBit Manipulation, Array, Dynamic Programming +1
1687Delivering Boxes from Storage to PortsHardSegment Tree, Queue, Array +4
1691Maximum Height by Stacking CuboidsHardArray, Dynamic Programming, Sorting
1692Count Ways to Distribute CandiesPremiumHardDynamic Programming
1714Sum Of Special Evenly-Spaced Elements In ArrayPremiumHardArray, Dynamic Programming
1723Find Minimum Time to Finish All JobsHardBit Manipulation, Array, Dynamic Programming +2
1728Cat and Mouse IIHardGraph, Topological Sort, Memoization +5
1735Count Ways to Make Array With ProductHardArray, Math, Dynamic Programming +2
1745Palindrome Partitioning IVHardString, Dynamic Programming
1751Maximum Number of Events That Can Be Attended IIHardArray, Binary Search, Dynamic Programming +1
1755Closest Subsequence SumHardBit Manipulation, Array, Two Pointers +3
1770Maximum Score from Performing Multiplication OperationsHardArray, Dynamic Programming
1771Maximize Palindrome Length From SubsequencesHardString, Dynamic Programming
1787Make the XOR of All Segments Equal to ZeroHardBit Manipulation, Array, Dynamic Programming
1799Maximize Score After N OperationsHardBit Manipulation, Array, Math +4
1815Maximum Number of Groups Getting Fresh DonutsHardBit Manipulation, Memoization, Array +2
1857Largest Color Value in a Directed GraphHardGraph, Topological Sort, Memoization +3
1866Number of Ways to Rearrange Sticks With K Sticks VisibleHardMath, Dynamic Programming, Combinatorics
1872Stone Game VIIIHardArray, Math, Dynamic Programming +2
1879Minimum XOR Sum of Two ArraysHardBit Manipulation, Array, Dynamic Programming +1
1883Minimum Skips to Arrive at Meeting On TimeHardArray, Dynamic Programming
1896Minimum Cost to Change the Final Value of ExpressionHardStack, Math, String +1
1900The Earliest and Latest Rounds Where Players CompeteHardMemoization, Dynamic Programming
1916Count Ways to Build Rooms in an Ant ColonyHardTree, Graph, Topological Sort +3
1928Minimum Cost to Reach Destination in TimeHardGraph, Array, Dynamic Programming
1931Painting a Grid With Three Different ColorsHardDynamic Programming
1955Count Number of Special SubsequencesHardArray, Dynamic Programming
1977Number of Ways to Separate NumbersHardString, Dynamic Programming, Suffix Array
1987Number of Unique Good SubsequencesHardString, Dynamic Programming
1994The Number of Good SubsetsHardBit Manipulation, Array, Hash Table +5
2003Smallest Missing Genetic Value in Each SubtreeHardTree, Depth-First Search, Union Find +1
2005Subtree Removal Game with Fibonacci TreePremiumHardTree, Math, Dynamic Programming +2
2019The Score of Students Solving Math ExpressionHardStack, Memoization, Array +4
2035Partition Array Into Two Arrays to Minimize Sum DifferenceHardBit Manipulation, Array, Two Pointers +4
2050Parallel Courses IIIHardGraph, Topological Sort, Array +1
2060Check if an Original String Exists Given Two Encoded StringsHardString, Dynamic Programming
2088Count Fertile Pyramids in a LandHardArray, Dynamic Programming, Matrix
2143Choose Numbers From Two Arrays in RangePremiumHardArray, Dynamic Programming
2147Number of Ways to Divide a Long CorridorHardMath, String, Dynamic Programming
2163Minimum Difference in Sums After Removal of ElementsHardArray, Dynamic Programming, Heap (Priority Queue)
2167Minimum Time to Remove All Cars Containing Illegal GoodsHardString, Dynamic Programming
2172Maximum AND Sum of ArrayHardBit Manipulation, Array, Dynamic Programming +1
2188Minimum Time to Finish the RaceHardArray, Dynamic Programming
2209Minimum White Tiles After Covering With CarpetsHardString, Dynamic Programming, Prefix Sum
2218Maximum Value of K Coins From PilesHardArray, Dynamic Programming, Prefix Sum
2247Maximum Cost of Trip With K HighwaysPremiumHardBit Manipulation, Graph, Dynamic Programming +1
2262Total Appeal of A StringHardHash Table, String, Dynamic Programming
2263Make Array Non-decreasing or Non-increasingPremiumHardGreedy, Dynamic Programming
2267Check if There Is a Valid Parentheses String PathHardArray, Dynamic Programming, Matrix
2272Substring With Largest VarianceHardArray, Dynamic Programming
2312Selling Pieces of WoodHardMemoization, Array, Dynamic Programming
2313Minimum Flips in Binary Tree to Get ResultPremiumHardTree, Depth-First Search, Dynamic Programming +1
2318Number of Distinct Roll SequencesHardMemoization, Dynamic Programming
2321Maximum Score Of Spliced ArrayHardArray, Dynamic Programming
2328Number of Increasing Paths in a GridHardDepth-First Search, Breadth-First Search, Graph +5
2338Count the Number of Ideal ArraysHardMath, Dynamic Programming, Combinatorics +1
2355Maximum Number of Books You Can TakePremiumHardStack, Array, Dynamic Programming +1
2361Minimum Costs Using the Train LinePremiumHardArray, Dynamic Programming
2376Count Special IntegersHardMath, Dynamic Programming
2403Minimum Time to Kill All MonstersPremiumHardBit Manipulation, Array, Dynamic Programming +1
2407Longest Increasing Subsequence IIHardBinary Indexed Tree, Segment Tree, Queue +4
2430Maximum Deletions on a StringHardString, Dynamic Programming, String Matching +2
2435Paths in Matrix Whose Sum Is Divisible by KHardArray, Dynamic Programming, Matrix
2463Minimum Total Distance TraveledHardArray, Dynamic Programming, Sorting
2472Maximum Number of Non-overlapping Palindrome SubstringsHardGreedy, Two Pointers, String +1
2478Number of Beautiful PartitionsHardString, Dynamic Programming, Prefix Sum
2484Count Palindromic SubsequencesHardString, Dynamic Programming
2518Number of Great PartitionsHardArray, Dynamic Programming
2538Difference Between Maximum and Minimum Price SumHardTree, Depth-First Search, Array +1
2547Minimum Cost to Split an ArrayHardArray, Hash Table, Dynamic Programming +1
2552Count Increasing QuadrupletsHardBinary Indexed Tree, Array, Dynamic Programming +2
2573Find the String with LCPHardGreedy, Union Find, Array +3
2581Count Number of Possible Root NodesHardTree, Depth-First Search, Array +2
2585Number of Ways to Earn PointsHardArray, Dynamic Programming
2617Minimum Number of Visited Cells in a GridHardStack, Breadth-First Search, Union Find +5
2646Minimize the Total Price of the TripsHardTree, Depth-First Search, Graph +2
2681Power of HeroesHardArray, Math, Dynamic Programming +2
2713Maximum Strictly Increasing Cells in a MatrixHardMemoization, Array, Hash Table +5
2719Count of IntegersHardMath, String, Dynamic Programming
2742Painting the WallsHardArray, Dynamic Programming
2791Count Paths That Can Form a Palindrome in a TreeHardBit Manipulation, Tree, Depth-First Search +2
2801Count Stepping Numbers in RangeHardString, Dynamic Programming
2809Minimum Time to Make Array Sum At Most xHardArray, Dynamic Programming, Sorting
2827Number of Beautiful Integers in the RangeHardMath, Dynamic Programming
2836Maximize Value of Function in a Ball Passing GameHardBit Manipulation, Array, Dynamic Programming
2851String TransformationHardMath, String, Dynamic Programming +1
2858Minimum Edge Reversals So Every Node Is ReachableHardDepth-First Search, Breadth-First Search, Graph +1
2867Count Valid Paths in a TreeHardTree, Depth-First Search, Math +2
2876Count Visited Nodes in a Directed GraphHardGraph, Memoization, Dynamic Programming
2902Count of Sub-Multisets With Bounded SumHardArray, Hash Table, Dynamic Programming +1
2911Minimum Changes to Make K Semi-palindromesHardTwo Pointers, String, Dynamic Programming
2912Number of Ways to Reach Destination in the GridPremiumHardMath, Dynamic Programming, Combinatorics
2916Subarrays Distinct Element Sum of Squares IIHardBinary Indexed Tree, Segment Tree, Array +1
2920Maximum Points After Collecting Coins From All NodesHardBit Manipulation, Tree, Depth-First Search +3
2926Maximum Balanced Subsequence SumHardBinary Indexed Tree, Segment Tree, Array +2
2945Find Maximum Non-decreasing Array LengthHardStack, Queue, Array +4
2969Minimum Number of Coins for Fruits IIPremiumHardQueue, Array, Dynamic Programming +2
2973Find Number of Coins to Place in Tree NodesHardTree, Depth-First Search, Dynamic Programming +2
2977Minimum Cost to Convert String IIHardGraph, Trie, Array +3
2999Count the Number of Powerful IntegersHardMath, String, Dynamic Programming

Related patterns

Problems sit in more than one pattern more often than not, and the overlap is where the interesting follow-up questions live.

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.

Meet the dynamic programming problem you did not practise

Stealth Interview is a desktop app for macOS and Windows. It reads the coding 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 is saying — while staying invisible to screen sharing.