r/leetcode • u/Ok_Designer_4455 • 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
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.
3
u/dvn7035 17h ago
https://www.reddit.com/r/leetcode/comments/14o10jd/the_ultimate_dynamic_programming_roadmap/
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
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:
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
Phase 2: Apply intuition
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.
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/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:
- 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