NUKOE

Dynamic programming: 5 families for coding interviews

• 9 min •
A young man wearing glasses is typing on a keyboard in front of two screens displaying code.

Dynamic programming is the subject that causes the biggest drop in performance in technical interviews. The concepts are rarely obscure, yet candidates break them down poorly. A candidate who encounters a "longest common subsequence" type problem can spend thirty minutes looking for an ad hoc solution. The one who recognizes the problem family writes the recurrence in five minutes and devotes the rest of the time to optimization.

Most candidates approach dynamic programming as a collection of isolated problems: they memorize solutions, then try to adapt them case by case. Successful candidates learn to classify problem statements into stable patterns. AlgoMaster points this out in its guide: dynamic programming is arguably the hardest topic in interviews, but the fastest way to master it is to extract recurring families from it. LeetCode Discuss agrees, offering thirteen patterns to structure preparation.

Why dynamic programming remains an obstacle

The difficulty of DP rarely comes from mathematics. It comes from the fact that the optimal solution to a problem depends on the optimal solutions of overlapping subproblems. A candidate with no reference pattern gets stuck on defining the state, the recurrence relation, or the choice between recursion and iteration.

Myths and realities

You often hear that dynamic programming requires a gift for mathematics, that you need to know hundreds of problems, or that the topic has become rare in interviews. The following table compares what candidates expect and what they actually experience.

| Myth | Reality |

|-------|---------|

| You have to be excellent at mathematics | Most patterns rely on simple choices and accessible recurrence formulas |

| You have to memorize hundreds of solutions | About ten families cover the bulk of questions asked in interviews |

| DP no longer comes up in interviews | Candidate feedback on LeetCode shows it remains frequent, especially for mid-level and senior positions |

| A recursive solution is always too slow | With memoization, recursion becomes competitive and often more readable than a bottom-up table |

Dynamic programming groups a family of strategies that apply to problems with two properties: optimal substructure and overlapping subproblems. The Udemy course Dynamic Programming Patterns for Coding Interviews stresses this point: successful candidates know which class the problem belongs to, instead of inventing recurrences on the fly.

The pattern families to master first

Available lists vary: AlgoMaster counts twenty, LeetCode Discuss keeps thirteen. Five families cover a large majority of the questions asked in interviews.

| Pattern | Clue in the statement | Representative problem |

|---------|----------------------|----------------------|

| 0/1 Knapsack | Choose a subset with a limited capacity, each item used at most once | 0/1 Knapsack, Partition Equal Subset Sum |

| Unbounded Knapsack | Choose items with possible repetition, capacity or amount to reach | Coin Change, Rod Cutting |

| Longest Common Subsequence | Compare two sequences, allow deletions or insertions | Longest Common Subsequence, Edit Distance |

| Longest Increasing Subsequence | Look for an increasing subsequence, often with pairs or dimensions | Longest Increasing Subsequence, Russian Doll Envelopes |

| DP on grids / paths | Move through a matrix with movement constraints | Unique Paths, Minimum Path Sum |

| Palindromic Subsequence | Work on intervals or palindromic substrings | Longest Palindromic Subsequence, Palindrome Partitioning |

The 0/1 Knapsack pattern is the most emblematic. Levelup Gitconnected describes it as choosing items that each have a value and a weight, under a capacity constraint. The question is to maximize value without exceeding capacity. Partitioning, target sum and resource allocation problems reuse the same structure.

1. 0/1 Knapsack

Typical signal: the problem statement mentions a capacity, a budget, a limited time, and each item can be chosen only once. The state is usually defined as dp[i][c], where i is the number of items considered and c the remaining capacity. The recurrence is:

dp[i][c] = max(dp[i-1][c], value[i] + dp[i-1][c-weight[i]])

if the weight of item i does not exceed c, otherwise dp[i][c] = dp[i-1][c]. This pattern is the basis of many target-sum and partitioning problems.

2. Unbounded Knapsack

Here, items can be chosen multiple times. The signal is the presence of unlimited repetition. The difference from 0/1 lies in the recurrence: when you include an item, you stay on the same row i instead of moving to i-1.

dp[i][c] = max(dp[i-1][c], value[i] + dp[i][c-weight[i]])

Coin Change problems or Rod Cutting fall into this category.

3. Longest Common Subsequence (LCS)

This pattern appears as soon as two sequences need to be compared. The state dp[i][j] is the length of the LCS between the first i characters of the first string and the first j of the second. The recurrence is:

if a[i-1] == b[j-1] : dp[i][j] = dp[i-1][j-1] + 1
otherwise : dp[i][j] = max(dp[i-1][j], dp[i][j-1])

Variants include edit distance, where each operation has a cost.

4. Longest Increasing Subsequence (LIS)

The signal is the search for an increasing subsequence, sometimes with additional dimensions. A classic approach uses a dp[i] array that stores the length of the LIS ending at index i. The complexity can be reduced to O(n log n) with binary search, but the O(n²) version remains acceptable in an interview to explain the reasoning.

5. Palindromic Subsequences

These problems work on intervals. The state is often dp[i][j] for the substring from i to j. The recurrence compares the endpoints and uses the inner substrings. Palindromic partitioning problems are one example.

6. Grid or Path DP

When the problem statement talks about moving through a grid, counting paths or minimizing a travel cost, the pattern is almost always DP. The state dp[i][j] represents the result for reaching cell (i,j). The transition comes from neighboring cells, often dp[i-1][j] and dp[i][j-1].

How to Tackle a DP Problem: A Five-Step Method

The five steps below give you a framework you can explain to the interviewer, and that explanation counts as much as the final code.

Programmer explaining a problem on a whiteboard during an interview.

Step 1: Spot the Signs of Optimal Substructure

A problem lends itself to DP when its optimal solution can be built from the optimal solutions of subproblems. Typical signs: the statement asks for a maximum, a minimum, a total number of ways, or an optimization under constraints. If the decision at a given moment leaves a subproblem of the same nature but smaller in size, that is a strong signal. For example, in the 0/1 knapsack, deciding to include or exclude an item leaves a subproblem with reduced capacity.

Step 2: Define the State Precisely

The state is the set of variables that fully describe the situation of a subproblem. It must be minimal but sufficient. For the 0/1 knapsack, the state is often defined by two indices: the number of items considered and the remaining capacity. For the longest common subsequence, the state dp[i][j] represents the length of the longest common subsequence between the first i characters of the first string and the first j of the second. Redundant information in the state, or a missing variable, breaks the recurrence.

Step 3: Write the Recurrence Relation

The recurrence describes how to move from subproblems to the current problem. For the 0/1 knapsack, if weight[i] and value[i] denote the weight and value of item i, the relation is written:

dp[i][c] = dp[i-1][c] if weight[i] > c
dp[i][c] = max(dp[i-1][c], value[i] + dp[i-1][c-weight[i]]) otherwise

This formula translates the choice: either you do not include the item, or you include it and add its value to the best solution for the remaining capacity. The base cases, typically dp[0][c] = 0 and dp[i][0] = 0, close the recursion.

Step 4: Move from recursion to memoization, then to the table

Always start with a recursive version that uses a cache. It is easier to explain and less prone to initialization errors. Once the recursion works, turn it into a bottom-up table if the interviewer asks for it or if the number of recursive calls becomes a problem. Memoization alone is often enough for an interview.

Step 5: Optimize space if needed

Many DP patterns depend only on the previous row of the table. In the 0/1 knapsack, you can reduce the capacity dimension by using a one-dimensional array and iterating the capacity from right to left. Interviewers ask for this reduction often enough that it is worth rehearsing beforehand.

Quick checklist after writing the recurrence

  • Is the state defined without ambiguity?
  • Does the recurrence relation cover every possible case?
  • Are the base cases initialized correctly?
  • Is the time and space complexity acceptable?
  • Can one dimension of the table be reduced?

Worked example: the 0/1 knapsack

Let's take a small knapsack problem. The capacity is 5 units. Three items are available: the first has a value of 60 and a weight of 2, the second a value of 100 and a weight of 3, the third a value of 120 and a weight of 4. The following table shows how the bottom-up DP fills in.

| Capacity | 0 | 1 | 2 | 3 | 4 | 5 |

|----------|---|---|---|---|---|---|

| No item | 0 | 0 | 0 | 0 | 0 | 0 |

| Item (value 60, weight 2) | 0 | 0 | 60 | 60 | 60 | 60 |

| Item (value 100, weight 3) | 0 | 0 | 60 | 100 | 100 | 160 |

| Item (value 120, weight 4) | 0 | 0 | 60 | 100 | 120 | 160 |

The final cell reads 160, which corresponds to taking the items of weight 2 and 3. Narrating the filling while you write the code keeps the interviewer following your reasoning.

Top-down or bottom-up: how to choose

The top-down version (recursive with memoization) stays closer to the natural definition of the recurrence. It is simpler to write and to debug, especially when the state has several dimensions. The bottom-up version (iterating over a table) avoids the overhead of recursive calls and makes some space optimizations easier.

| Criterion | Top-down (memoization) | Bottom-up (table) |

|---------|------------------------|---------------------|

| Ease of writing | High, follows the recurrence | Medium, requires defining the fill order |

| Risk of indexing errors | Low | Higher, especially with offset indices |

| Interview performance | Enough for most questions | Preferable if the interviewer asks for an optimization |

| Space optimization | Limited | Often possible with a rolling array |

Candidates who start top-down convert to bottom-up only if time allows.

Complexity: what the interviewer expects

For a typical two-dimensional pattern, the time complexity is O(n * m) where n and m are the dimensions of the state. The space complexity is the same, but can often be reduced to O(m) with a rolling array.

  • 0/1 knapsack: O(n * capacity) time, O(capacity) space once optimized.
  • LCS: O(n * m) time and space, reducible to O(min(n,m)).
  • LIS in O(n²): O(n) space.
  • Grid DP: O(rows * columns) time, often O(columns) space.

Four mistakes that cost dearly in an interview

Frustrated developer staring at code on a computer screen.
  1. Looking for the brute-force recursive solution without memoization. An exponential recursion may seem natural at first, but it leads to a failure on the test cases. Add a cache as soon as the recursion is written, before even testing with examples.
  1. Confusing the state and the result. The state must contain only the information needed to solve the subproblem. If you store the partial result in the state, you complicate the recurrence for no benefit.
  1. Neglecting the base cases. An indexing or initialization error makes the algorithm fail silently. Always check dp[0][] and dp[][0] on trivial examples.
  1. Wanting to write the iterative version straight away. Recursion with memoization is more natural for building the solution, especially under stress. Once it is validated, the conversion to a bottom-up table follows the recurrence line by line.

An analogy to anchor the reasoning

Comparing DP to a construction plan can help. A DP problem is a building whose foundations (the base cases) and assembly rules (the recurrence relation) are known. Without a plan, you can put together a small example, but the structure collapses as soon as the problem grows. Patterns work like pre-drawn blueprints you can pull off the shelf.

What the sources recommend

The experience report published by Code Grey on Medium about NeetCode 150 shows that dynamic programming is best worked on at the end of the journey, once data structures and graph traversals are mastered. DP problems frequently require recursion, array manipulation and an eye for complexity at the same time.

The Udemy course Dynamic Programming Patterns for Coding Interviews stresses recognizing known patterns rather than memorizing isolated solutions. AlgoMaster and LeetCode Discuss provide useful lists for organizing revision. Levelup Gitconnected places the 0/1 Knapsack pattern within a broader set of twenty interview patterns, alongside graph traversal and sliding window families.

Further reading

  • AlgoMaster Newsletter: a list of twenty DP problem families with application examples.
  • LeetCode Discuss: thirteen DP patterns to structure your preparation.
  • Levelup Gitconnected: the 0/1 knapsack pattern explained within the framework of the twenty interview patterns.
  • Udemy: a course dedicated to DP patterns for Java interviews.
  • Medium, Code Grey: an experience report on NeetCode 150 and where DP fits in a preparation plan.

Related articles