r/leetcode • • 18h ago

Question How do I actually get good at Dynamic Programming (DP)? I struggle to come up with solutions

I'm good at other DSA topics like Graphs, Two Pointers, Sliding Window, etc., but DP just doesn't click for me.

Even after understanding solutions, I struggle to come up with the approach myself.

What resources, problem lists, or strategies helped you develop DP intuition? Any advice would be appreciated!

I want to learn how to think in DP, not just memorize patterns.

41 Upvotes

20 comments sorted by

14

u/elfleur 18h ago

+1 here. I think I understand DP as a concept, but the application is tricky. DP tells you that you use subproblems to build up to the solution, but often I find it difficult to identify the subproblem that builds up to the problem.

5

u/Remarkable_Mistake77 18h ago

Instead of trying to see the full DP solution, start by writing the brute-force recursion and then ask what the minimum state is that makes each call unique; that state becomes your table index. Write the recurrence in plain words first ("best answer at i = best of choice A or choice B"), then code it. Memoize the recursion before converting to a bottom-up table, and trace a tiny input by hand to check the base cases. Ten problems of one pattern teach more than one problem from each category.

3

u/hucchnanmaga 17h ago

First step- get good at recursion and backtracking. And then most DP problems flow naturally as top-down recursion problems with memoization including multi-dimensional DP. If the interviewer insists on using bottom-up DP, thank him for his time and ask him to politely fuck off.

5

u/Vivid-Zombie-477 18h ago

as u/elfleur mentioned you can't just become good at DP since the solution differs based on the subproblem, not just a general copy-paste technique.

If you don't understand the concept, I recommend this g4g article that uses fibonacci to dimonstrate how to write it using different DP approaches and how it can be sometimes optimized https://www.geeksforgeeks.org/dsa/introduction-to-dynamic-programming-data-structures-and-algorithm-tutorials/

Other than that... just practice. Everything in leetcode comes down to practice and how many problems you've seen before

2

u/Putrid-Leader724 11h ago

i understand that BUT i’m tired of reading the same fibonacci article a million times. it just doesn’t click for me and i believe i’m lacking in volume of DP problems. i really hope to get better at them since it gate keeps a lot of job interviews for me

5

u/BerserkkD 18h ago

two words - aditya verma

2

u/TopTutor6926 18h ago

get good at recursion.

2

u/dol1_ 16h ago edited 16h ago

I do believe it's an intuition thing.

I have solved more than 600 leetcode questions, and even though I can easily solve easy or medium difficulty ones, I struggle a lot when it comes to DP. It's like a gift to be able to solve them on the spot

1

u/AppropriateEmotion22 17h ago

I think I have a good enough flow of solving DP. First you have to get good at recursion and bactracking. Then for most of the common dp questions, write out the brute force recursive solution. When it is done, you can just slot in the memo into it. Declare the memo at the top, in the function, add if xyz in memo: return memo[xyz], then at the last, whatever you are getting in res, attribute it to memo[xyz] = res and return mamo[xyz] and change the dfs(i, j+1) or whatever it is to memo[i][j+1]. Then for tabulation, just observe what is the is the flow of the recursion, if it is moving forward, then make the nested loop move backward, that it. Here is the solution to leetcode 714 that i have done, you can clearly see the pattern from above in solving the problem:

class Solution:
    def maxProfit(self, prices: list[int], fee: int) -> int:
        # Brute force
        # n = len(prices)


        # def dfs(i, holding):
        #     if i==n:
        #         return 0


        #     if holding:
        #         skip = dfs(i+1, 1)
        #         sell = prices[i] - fee + dfs(i+1, 0)
        #         return max(skip, sell)
        #     else:
        #         skip = dfs(i+1, 0)
        #         buy =  -prices[i] + dfs(i+1, 1)
        #         return max(skip, buy)


        
        # return dfs(0, 0)


        # Memo
        # n = len(prices)
        # memo = [[-1] * 2 for _ in range(n)]


        # def dfs(i, holding):
        #     if i==n:
        #         return 0
        #     if memo[i][holding] != -1:
        #         return memo[i][holding]
        #     if holding:
        #         skip = dfs(i+1, 1)
        #         sell = prices[i] - fee + dfs(i+1, 0)
        #         memo[i][holding] = max(skip, sell)
        #         return memo[i][holding]
        #     else:
        #         skip = dfs(i+1, 0)
        #         buy =  -prices[i] + dfs(i+1, 1)
        #         memo[i][holding] = max(skip, buy)
        #         return memo[i][holding]

        # return dfs(0, 0)


        # Tabulation


        n = len(prices)
        dp = [[0] * 2 for _ in range(n + 1)]


        for i in range(n - 1, -1, -1):
            dp[i][0] = max(dp[i + 1][0],                 # skip
                           -prices[i] + dp[i + 1][1])    # buy


            dp[i][1] = max(dp[i + 1][1],                 # skip
                           prices[i] - fee + dp[i + 1][0])  # sell


        return dp[0][0] 

1

u/jackgoldberg123 14h ago

the thing you're describing is really common, since the hard part of dp is spotting the state, not writing the recurrence once you have it. it also helps to see it as a recursion that keeps recomputing the same calls, so you're mostly hunting for what repeats rather than trying to invent a table.

1

u/eulerianReflections IC6 - obsessed with learning and love to teach 11h ago edited 10h ago

I think the key here is developing the mental models and associations that allow you to intuitively recognise when and how to apply the DP principles you've learnt.

I'd treat patterns as something you want your brain to arrive at through experience, rather than something you memorise and then try to apply.

I've tried to use this simplified diagram below to illustrate how different problem-solving experiences can collectively shape your intuition and influence how you approach unfamiliar problems.

Phase 1: Develop intuition

Solve problems A, B and C
↓
Brain processes experiences
↓
Detects underlying similarities
↓
Forms generalisations (patterns)
↓
Builds mental models and associations

Phase 2: Apply intuition

Encounter an unfamiliar problem
↓
Brain detects familiar cues
↓
Draws on previous experiences
↓
Relevant knowledge comes to mind
↓
Potential solution approach

The interesting thing about the human brain is that it can recognise similarities and form associations without you necessarily being consciously aware of them. Those patterns which are expressed in human language (words), don't capture everything your brain would on its own.

You might catch yourself solving an unfamiliar problem and feeling that a particular approach could work, before being able to articulate exactly why. This relates to the concept of expert intuition that Daniel Kahneman discusses in his book Thinking, Fast and Slow.

By simply memorising patterns, you're potentially missing out on many of the mental connections your brain would have developed through the experiences leading up to those patterns. (I believe this is what you are missing)

I recommend this guide, which explains how to structure your DP learning around this. The same principles apply to other DSA topics too.

1

u/tangertale 10h ago

For what it’s worth I’ve interviewed with dozens of companies over the last 7 years and never encountered a DP problem

1

u/jason_graph 10h ago edited 9h ago

For me, my intuitive process is

0. If the problem is an optimization problem, make a quick guess as to whether it makes sense that the optimal solutions solution would be composed of the solution of smaller subproblems, even if you arent 100% clear what those subproblems would be.

  1. Define what universe of things the problem is asking about. Subarrays, subsequences, subsets, etc. Don't just limit your consideration to optimal things. Don't only consider things that correspond to the final subproblem that the question asks about (e.g. for Climbing Stairs, consider all sequences of 1 and 2 steps, not just those that sum to n).
  2. Consider how you can construct these things from other things and what base cases there are. This might be appending an element to the front/back of a subarray, concatenating two subarrays to form a largee subarray, etc.

3a.Try to partition all these things into groups based on similar qualities. These groups will eventually become the dp states but dont think of them as the solutions to various subproblems but rather a collection of things that have similar properties. You might group things by the "size" of the subproblem they correspond to and/or other relevant properties the question asks for.

3b. It is also very important that elements within the same group can be modified in the same way to form new elements. Take for example a problem about making sequences of 0, 1, and 2s such that no pair of adjacent elements are the same and you want to know how many valid sequences of length n. You could try forming groups for sequences of each length but then you run into an issue where if you take all the sequences of length I, you can only append a 0 to some of them. To fix this, split your groups also based on any criteria that affects how you can/cant modify it to make future things. In this case, groups based on the length of each sequence and what the final element is.

4. Try to make a reccurence relation. If you run into issues you may have to review a previous step.

4a. One issue that can happen is you arent able to construct everything easily. Take for example a problem asking about subsequences of an integer array whose sum must be a multiple of k. If you only consider such subsequences you will have a hard time constructing them. Instead what you need to do is expand your universe to include subsequences with other sums and make your groups based also on what their sum is mod k.

5a. To improve the time complexity of a solution, your recurrence relation might refer to multiple subproblems. There might be a way to query this information more efficiently. Perhaps by binary searching something or keeping track of.something.

5b. To improve time complexity, sometimes a recurrence relation can be further optimized by modifying small things about how you define the groups. Take for example house robber. You could split your groups based on all valid subsequences of the first i houses that must use the i'th house or all valid subsequences of the first i houses without that additional criterion. In the first scenario, the recurrence relation would involve checking all other states in O(n) time while the latter of requires you to check one subproblem. Some examples of these variations might be if you are/arent required to use a final element like in this example, if you use all or at most of a certain constraint (like in knapsack dp), if dp[ i ] measures things corresponding to exactly the ith subproblem or if dp[ i ] measures things <= the ith subproblem.

As you solve more dp problems you will get better at realizing how to group things and make states. Be sure to reflect on how the problems you encounter construct objects from other objects and how they split objects into groups.

1

u/jason_graph 9h ago edited 9h ago

As for some general tips for learning DP.

  1. Be very comfortable with DFS + tree/binary tree problems as they are very similar to dp but the subproblems are quite literally each subtree. These problems are good at being able to not just implement recursive solutions but practice thinking recursively and thinking of how the solution of subproblems can be combined.
  2. Be aware of one of the main differences between DP and backtracking. They both involve thinking about some sort of object that can be seen as made of a sequence of choices. With backtracking though you need to store your past choices because your future choices depend on them. With DP, there are ways you can summarize the result of your past choices and discard exactly how you got there in order to determine what future choices you can make. This is very powerful as it lets you treat multiple distinct objects as behaving similarly and put them into groups as I describe above.
  3. When solving dp problems, I like to always write a comment describing in a lot of detail what dp[ state ] or dpFunc( state ) returns. For example // houseRobber[ i=0,1,..,n] = the maximum sum of a valid subset of the first I houses.

I try to avoid using the word "optimal" and be very careful with phrasing it in a way that avoids any off by one errors In interpretation. For example "dp[ i ] = the optimal solution of the ith subproblem" might mean the subproblem using the first i elements of an array or the subproblem using elements up to and including index i. Whar "optimal" means could be less apparent for harder problems.

If you are reading another person's solution make sure you know exactly what their dp[ state ] is measuring as there could also be subtle differences like dp[ i ] = the subproblems of size i vs dp[ I ] = the subproblems of size <= i.

4. This is just personal preference but I like to always have the base case have a small index like dp[ 0 ] and the final solution be dp[ n ]. This makes it so it is very clear that lower indices/arguments to a dp function correspond to smaller problems at a glance for 99% of the time. This also has implications on how I "name" the axis of my dp table/an argument of my dp function. When doing knapsack dp, I could choose to measure the sum of the space of the items I've chosen or I could measure the remaining space. In the first, a 0 corresponds to a base case of an empty selection and a large value corresponds to a more filled knapsack that is a "bigger" subproblem. If you do it the other way you have it the opposite way.

This way of thinking also imposes the "durection" that when making a reccurence relation and thinking of how to construct objects I kind of have to think a bit of what prior step got me to the current state rather than thinking what next step could I do from my current state. For this reason some people may prefer doing the opposite ( dpfunc(0)=solution, dpfunc(n)=base case) ), especially if they solve the problem top down. Either way I suppose having a consistent way of going about it is useful rather than if being 50/50 if a closer to base case subproblem corresponds to.a bigger or smaller index.

1

u/AndyKJMehta 10h ago

DP is named incorrectly by someone very enthusiastic about simple stuff. Forget about the name. Solve the problem. Iteratively, then recursively, and then add caching of intermediate results. Viola. That’s DP!

1

u/BackgroundBreak6485 9h ago

Since you're already fine with graphs, here's the reframe that made DP click for me: DP is just recursion on a graph of states, where you cache results because the same state gets reached more than once. You already know how to think in states from BFS and DFS. DP uses that same skill.

What worked for me, in order:

  1. Always write the brute-force recursion first. Don't try to come up with the table. Ask: "If I'm standing at position i (or i, j, or i, remaining_capacity), what choices do I have, and what does each choice leave me with?" Write that as a recursive function. It'll be exponential. That's fine.
  2. Name the state out loud. Ask yourself: "What is the smallest amount of information I need to finish solving the problem from here?" That's your function signature. Most of the difficulty in DP is this one step. If you have to pass along a whole list or path, your state is too big. Shrink it.
  3. Add a cache. Put u/lru_cache (or a memo dict) on the recursion. You now have a correct DP solution. Seriously, stop here in an interview unless they ask for more.
  4. Only then convert to bottom-up, if you need to. The table is just the cache, filled in an order where every state's dependencies are already computed. Memory optimization (keeping only the last row, and so on) comes after that.
  5. Learn the handful of state shapes, not 200 problems:

- 1D prefix: dp[i] = best answer using the first i items (house robber, climbing stairs, decode ways)

- Two sequences: dp[i][j] over prefixes of both (LCS, edit distance)

- Knapsack: dp[i][capacity] (subset sum, coin change)

- Intervals: dp[l][r] (burst balloons, palindrome partitioning)

- Grid paths: dp[r][c]

- Bitmask: dp[mask] for small n (TSP-style)

Do 3 to 5 problems per shape, and for each one, write down the state definition in plain English before you code. That habit is what builds the intuition.

6. When reading a solution, reverse-engineer it. Don't justat is dp[i][j] in words, and why is that enoughinformation?" If you can't answer that, you don't understand it yet.

Resources: the Aditya Verma DP playlist (knapsack and LCS families) and the DP section of NeetCode 150 are both solid. Errichto's DP lectures on YouTube are great for the "why".

One practical note: if this is for job interviews, check hoanies actually ask. Many of the practical-style rounds nowlean on stateful design, parsing, BFS, and hash maps far more than hard DP. I put together some free examples of that style here: https://aceoffer.app/learn/practice. Worth balancing your tof it.

1

u/Leather_Grand2896 7h ago

What made DP click for me:

- Write the brute force recursion first. DP is that recursion plus memoization

- Define the state in one sentence before coding, e.g. "dp[i] = best answer using the first i items"

- Ask what the last decision is (take/skip, where to split, which character) and build the transition from that

- Learn it by sub-pattern instead of randomly: 1D, grid, knapsack, two sequences, intervals

We group DP problems by those sub-patterns here: https://algo.monster/problems/dynamic_programming_intro (disclosure: I work on AlgoMonster)

1

u/Amazon_Trickery_326 36m ago

DP, Graphs, Trie, Recursion and Back Tracking, never understood these