DEV Community

sarah
sarah

Posted on

Dynamic Programming Without the Panic

Dynamic Programming Without the Panic
DP is recursion plus memory.

Ask a room of candidates what they dread most and dynamic programming usually wins. The name sounds grand, the solutions look like magic, and the fear is that you either remember the trick or you do not. That fear makes people freeze, which is a much bigger problem than the material itself.

Here is the calmer view: dynamic programming is recursion with memory. If you can write a plain recursive solution, you are already most of the way there. This post shows a sequence of small steps, from brute force to cache to table, plus a way to recognize the classic families so that new problems feel familiar.

Try Deep Think →
Begin with the slow recursive answer
Forget tables for now. Write the most natural recursive solution, even if it is exponential. For climbing a staircase where you can take one or two steps, the number of ways to reach step n is the ways to reach n minus one plus the ways to reach n minus two. Base cases are one way for step zero and one way for step one.

Running this by hand for n equal to five shows the same calls repeating: step three is computed several times. That repetition is the signal. You say to the interviewer, subproblems overlap, so caching should help, and you have already demonstrated the core insight.

Do not rush to optimize. A correct brute force on the page is worth more than a half remembered table. It also gives you a reference you can use to test the faster version on small inputs.

Add a cache and you are done
Create a dictionary or array keyed by the arguments of the recursive function. At the start of the function, return the stored value if it exists. Before returning a computed value, store it. That is memoization, and for many interviews it is a complete answer.

State the complexity clearly: each distinct state is computed once, and each computation does a small amount of work, so total time is the number of states times the work per state. For the staircase that is linear time and linear space, down from exponential time.

Key the cache on every argument that changes
Check the cache first, store before returning
Count states times work per state for complexity
Define the state in one sentence
Before writing code, finish this sentence: dp of i and j means the best result when I have considered the first i items and have j left. If you cannot finish it, you are not ready to code. A vague state is the root cause of most wrong DP answers.

For coin change, a good sentence is: dp of amount is the fewest coins needed to make that amount. The transition follows naturally, because you try each coin and take the minimum of one plus dp of amount minus coin. Writing the sentence also gives you the base case, which is dp of zero equals zero.

Some people write the state sentence as a comment above the function. That one line keeps you honest when you are under time pressure, and it gives the interviewer a clear view of your thinking.

Convert to a table only when it helps
A bottom up table avoids recursion depth limits and can shrink memory. Fill states in an order where dependencies are already known. For coin change, loop amounts from one up to the target and look back at smaller amounts.

Often the table can be trimmed. If each row depends only on the previous row, keep two rows instead of all of them. Mention this as an optimization after your correct solution, not before. Interviewers value a correct memoized answer over a half finished clever table.

Study hard problems, then solve them yourself
When a problem is beyond your current level, use it as a case study. Phantom Code AI offers a Deep Think mode built for harder algorithm problems, so you can look at how a tough DP breaks into state, transition, and base case, then close the explanation and re-solve it from scratch. The desktop app runs on macOS and Windows and has a free trial.

The re-solve step matters most. Reading a solution creates a false sense of understanding. Keep it as a study and practice aid, and respect the rules of your employer and any test provider during real assessments. Afterward, add the problem to a family list so you can spot its relatives.

A walkthrough: climbing to coin change
Take amounts of 11 with coins 1, 2, and 5. The recursive idea is that the fewest coins for 11 is one plus the minimum of the fewest for 10, 9, and 6. Many of those smaller amounts appear more than once, such as 6 and 5, so a cache pays off right away.

Bottom up, fill an array from 0 to 11. Position 0 is 0. Position 1 is 1, position 2 is 1, position 3 is 2, and so on until position 11 comes out to 3, using 5, 5, and 1. Mark unreachable amounts with a large sentinel and return negative one if the target stays unreachable.

This pattern, an array indexed by a quantity and a loop over choices, shows up in dozens of problems. Once you have written it by hand, you can adapt it to counting ways, or to fewest steps.

Define the array meaning in a comment
Choose a sentinel for impossible states
Fill in an order that respects dependencies
Return the right cell, and handle unreachable cases
Frequently asked questions
How do I know a problem needs DP?
Look for optimization or counting over choices where the same smaller situation recurs. Phrases like number of ways, minimum cost, longest, and can you reach are common hints, especially when a greedy choice fails on a small example.

Top down or bottom up in an interview?
Start top down because it mirrors your reasoning and is quicker to get right. Move to bottom up if the interviewer asks about recursion depth or space.

Which problem families should I memorize?
Know knapsack, longest common subsequence, edit distance, and coin change well. Most other questions are disguised versions of these four shapes.

Final thoughts
Dynamic programming is a three step habit: write the recursion, notice the repeats, add memory. The panic fades once you stop hunting for a trick and start with the plain version every time.

Keep a short list of families you have solved, with the state sentence for each. Review it weekly and add one new problem at a time. In a few weeks, most questions will look like old friends in new clothes.

Try Deep Think →

Learn more at Phantom Code AI.[https://phantomcode.co/]

Use any interview tool in line with your employer's and test provider's rules.

Top comments (0)