In Part 10 you learned what dynamic programming is: solve each smaller problem once and write it down. The hard part in interviews is knowing what to write down. Good news: most DP questions belong to just four families. Spot the family and the solution shape comes with it.
The 12 interview patterns: you are here
- 1Two Pointerssorted + pair
- 2Sliding Windowcontiguous subarray
- 3Prefix Sum + Hash Maprange sums, sum = K
- 4Binary Search on Answersmallest value that works
- 5Fast & Slow Pointerscycle, middle
- 6Merge Intervalsoverlapping ranges
- 7Monotonic Stacknext greater element
- 8Heap / Top-Ktop K, Kth largest
- 9Tree Patternsdepth, paths, levels
- 10Grid BFS & Topological Sortislands, dependencies
- 11Backtrackingall combinations
- 12DP Patternscount ways, min cost
The four families
1️⃣ 1D sequence
best[i] from best[i−1] and best[i−2]
Climbing stairs, house robber, decode ways
🎒 Knapsack
take it or skip it, within a limit
0/1 knapsack, coin change, subset sum
📈 LIS
longest chain ending at each index
Longest increasing subsequence, Russian dolls
🔲 2D table
answer from top, left and diagonal
LCS, edit distance, unique paths
The trek bag story (knapsack)
You're packing for a trek and your bag holds 7 kg. Each item has a weight and a usefulness value. Try every combo and you'll be there all night. DP builds a table instead: “best value with just these items and this much room”, one small question at a time. Fill it yourself:
🎒 Pack the trek bag (max 7 kg): fill the DP table
| items ↓ / room → | 0kg | 1kg | 2kg | 3kg | 4kg | 5kg | 6kg | 7kg |
|---|---|---|---|---|---|---|---|---|
| none | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 🍫 Snacks 1kg · 1 | · | · | · | · | · | · | · | · |
| 💧 Water 3kg · 4 | · | · | · | · | · | · | · | · |
| 🧥 Jacket 4kg · 5 | · | · | · | · | · | · | · | · |
| 📷 Camera 5kg · 7 | · | · | · | · | · | · | · | · |
Each row adds one more item to choose from. Press Next to fill cells left to right.
Each cell answers a smaller question: “best value using only these items, with this much room”. Every cell is just max(skip it, take it), using answers from the row above. The last cell is the answer: 9 (water + jacket).
🔍 Use dynamic programming when you see
- ✓Count the ways, minimum, maximum, or “is it possible?”
- ✓Choices at each step that affect later steps
- ✓The same smaller question keeps coming back
- ✓Two strings compared, or paths across a grid
🚫 Don't use it when
- ✗List every answer (backtracking)
- ✗A greedy choice is provably always right
- ✗A single pass with a window or two pointers is enough
The template (for any family)
1. State: dp[i] (or dp[i][j]) = "the best answer for ..."
2. Choice: what options lead into this state? (take / skip, match / drop)
3. Base: the smallest answers you know (dp[0] = 0, empty string = 0)
4. Order: fill so every answer you need is already filled
knapsack: best[c] = max(best[c], best[c - w] + v) # loop c backwards
LIS: chain[i] = 1 + max(chain[j]) for j < i with nums[j] < nums[i]
LCS: match → t[i-1][j-1] + 1, else max(t[i-1][j], t[i][j-1])⚡ Memory tricks
- 1
“Name the family, say the state”
Finish “dp[i] = the best for…” out loud before coding.
- 2
“Skip it or take it”
The heart of every knapsack problem.
- 3
“Backwards for once, forwards for many”
0/1 knapsack loops capacity backwards; unbounded (coin change) loops forwards.
- 4
“Match goes diagonal”
In LCS and edit distance, a match moves up-left in the table.
Code: knapsack, LIS and LCS
Three families, three short functions. Outputs in the comments come from running the code.
def knapsack(weights, values, capacity):
"""0/1 knapsack: best value with each item taken at most once."""
best = [0] * (capacity + 1) # best[c] = best value with capacity c
for w, v in zip(weights, values):
for c in range(capacity, w - 1, -1): # go backwards so each item is used once
best[c] = max(best[c], best[c - w] + v) # skip it, or take it
return best[capacity]
def lis(nums):
"""Longest increasing subsequence: longest chain ending at each index."""
chain = [1] * len(nums)
for i in range(len(nums)):
for j in range(i):
if nums[j] < nums[i]:
chain[i] = max(chain[i], chain[j] + 1)
return max(chain)
def lcs(a, b):
"""Longest common subsequence: a 2D table of prefixes."""
t = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
if a[i - 1] == b[j - 1]:
t[i][j] = t[i - 1][j - 1] + 1 # letters match: extend
else:
t[i][j] = max(t[i - 1][j], t[i][j - 1]) # drop a letter from one side
return t[len(a)][len(b)]
print(knapsack([1, 3, 4, 5], [1, 4, 5, 7], 7)) # 9 (items of weight 3 + 4)
print(lis([10, 9, 2, 5, 3, 7, 101, 18])) # 4 (2, 3, 7, 18)
print(lcs("abcde", "ace")) # 3 ("ace")One pattern, many problems
| Famous problem | How the pattern solves it | Level |
|---|---|---|
| House Robber | 1D: best[i] = max(best[i−1], best[i−2] + nums[i]) | Medium |
| Coin Change | Unbounded knapsack: fewest coins for each amount | Medium |
| Partition Equal Subset Sum | 0/1 knapsack to total / 2 | Medium |
| Longest Increasing Subsequence | chain[i] from smaller earlier values | Medium |
| Longest Common Subsequence | 2D table, match goes diagonal | Medium |
| Unique Paths | Grid: from above + from the left | Medium |
| Edit Distance | 2D: insert, delete or replace | Hard |
🎯 Spot the pattern: is it dynamic programming?
In an interview nobody tells you the pattern. Read each problem and decide. Look for the signal words.
1. Find the length of the longest strictly increasing subsequence.
2. Minimum edits (insert, delete, replace) to turn one word into another.
3. Return every subset of [1, 2, 3].
4. Can the array be split into two parts with equal sums?
5. Count the unique paths from the top-left to the bottom-right of a grid (only right or down).
🧠 PATH memory card
Remember DP patterns for good
Picture it · Anchor it · Trace it · Hit-recall it. Four quick steps that turn “I read it once” into “I can explain it in an exam”.
- P
Picture it
Your brain remembers scenes far better than definitions.
← swipe to see the whole picture →
Packing a 7 kg trek bag: for each item, skip it or take it. Water plus jacket gives the best value, 9.
- A
Anchor it
A silly sentence you can't forget, where every word maps to the concept.
“Trek bag: name the family, say the state, skip it or take it”
- Name the family→1D, knapsack, LIS or 2D table
- Say the state→dp[i] = the best answer for…
- Skip it or take it→The choice that builds each answer
- Fill the table→Smaller answers first, so each is ready when needed
- T
Trace it
Run it by hand on a tiny example once. Doing beats reading.
Items (1 kg, 1), (3 kg, 4), (4 kg, 5), (5 kg, 7), bag 7 kg. Best for 7 kg after all items: max(skip camera = 9, take camera = 7 + best for 2 kg = 7 + 1 = 8) = 9, from water + jacket. - H
Hit-recall it
Test yourself now, then again on the day each card comes back.
Card 1 / 6 · new0 mastered · 0 practisedSay the answer out loud first, then flip and be honest.
Common mistakes
- Coding before stating dp[i]. If you can't finish the sentence, the recurrence will be wrong.
- Forward loop in 0/1 knapsack. It silently reuses items; loop capacity backwards.
- Off-by-one in 2D tables. Use an extra row and column of zeros for the empty prefix.
Where to go next
That's all 12 interview patterns. The final part puts them together the way interviews do: a problem with no label, and you decide which pattern fits: the “Which pattern?” challenge.
Key takeaways
- ✓Most DP problems belong to four families: 1D, knapsack, LIS, 2D tables.
- ✓Say the state first: “dp[i] = the best answer for…”.
- ✓Knapsack: skip it or take it; loop backwards for 0/1, forwards for unbounded.
- ✓LIS: longest chain ending at each index; LCS: a match goes diagonal.
- ✓Count / min / max → DP; list every answer → backtracking.
Frequently asked questions
What are the main dynamic programming patterns?
Four families cover most interview problems. 1D sequence DP (climbing stairs, house robber), where each answer comes from the previous one or two. Knapsack (take it or skip it within a limit: coin change, subset sum). Longest increasing subsequence (longest chain ending at each index). 2D tables over two strings or a grid (LCS, edit distance, unique paths).
How do I know a problem needs dynamic programming?
Look for a count of ways, a minimum or maximum, or 'is it possible', where the same smaller question gets asked again and again (overlapping subproblems) and the best answer is built from best answers to smaller parts (optimal substructure). If it asks you to LIST every answer, use backtracking instead.
What is the 0/1 knapsack problem?
You have items with weights and values and a bag with a weight limit. Each item can be taken at most once. The best value for capacity c with the first i items is the better of skipping item i or taking it (its value plus the best for c − its weight). With a 1D array, loop capacity backwards so each item is used once.
What's the difference between LIS and LCS?
LIS (longest increasing subsequence) works on one list: for each index, the longest increasing chain ending there. LCS (longest common subsequence) compares two strings with a 2D table: if letters match, extend the diagonal; otherwise take the best of dropping a letter from either string.
How do I write the DP state?
Finish the sentence “dp[i] (or dp[i][j]) = the best answer for…”. For example: best[c] = the best value with capacity c; chain[i] = the longest increasing chain ending at index i; t[i][j] = the LCS of the first i letters of a and first j letters of b. Once the sentence is clear, the recurrence usually follows.
🧠 Quick check: DP patterns
1. Coin change: fewest coins to make 11 from [1, 2, 5]. Which DP family?
2. In 0/1 knapsack with a 1D array, why loop capacity backwards?
3. LCS: the letters a[i] and b[j] match. What's t[i][j]?
4. “List all ways to make change for 11.” Which pattern?
Checking your access…