Classic DP Patterns
๐ At a Glance
| Aspect | Details |
|---|---|
| Time to Read | 40 minutes |
| Prerequisites | Part 16 (DP Foundations) |
| Key Concepts | Knapsack, LCS, LIS, Edit Distance, Matrix Chain |
| Difficulty | โญโญโญ (Intermediate) |
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ CLASSIC DP PATTERNS โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค โ โ โ KNAPSACK FAMILY SEQUENCE PROBLEMS โ โ โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ โ โ โ 0/1 Knapsack โ โ LCS โ โ โ โ โโโโโโโโโโโโโโโ โ โ โโโโโโโโโโโโโโโ โ โ โ โ Take or leave โ โ Match chars โ โ โ โ each item โ โ in both strings โ โ โ โ โ โ โ โ โ โ Unbounded โ โ LIS โ โ โ โ โโโโโโโโโโโโโโโ โ โ โโโโโโโโโโโโโโโ โ โ โ โ Unlimited copiesโ โ Increasing โ โ โ โ of each item โ โ subsequence โ โ โ โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ โ โ โ โ STRING OPERATIONS OPTIMIZATION โ โ โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ โ โ โ Edit Distance โ โ Matrix Chain โ โ โ โ โโโโโโโโโโโโโโโ โ โ โโโโโโโโโโโโโโโ โ โ โ โ Insert, Delete โ โ Optimal โ โ โ โ Replace โ โ parenthesizationโ โ โ โ โ โ โ โ โ โ Used in: diff, โ โ Used in: โ โ โ โ spell check, โ โ query planning, โ โ โ โ DNA alignment โ โ expression eval โ โ โ โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ฏ What You'll Learn
After completing this article, you will be able to:
- Solve knapsack variants: 0/1, unbounded, bounded, subset sum
- Find LCS: Longest common subsequence between strings
- Compute LIS: Longest increasing subsequence in O(n log n)
- Calculate edit distance: Transform one string to another
- Optimize matrix chains: Find optimal multiplication order
๐ฅ Production Story: The Code Review Diff Engine
A code review platform needed to show differences between file versions. Their naive diff algorithm was timing out on large files.
The Problem
JAVA(14 lines)CodeLoading syntax highlighter...
Files with 10,000 lines were timing out after 30 seconds.
The Solution: LCS-Based Diff
JAVA(53 lines)CodeLoading syntax highlighter...
The Impact
| File Size | Before | After |
|---|---|---|
| 100 lines | 50ms | 2ms |
| 1,000 lines | 5s | 20ms |
| 10,000 lines | Timeout | 200ms |
| 100,000 lines | Impossible | 2s |
๐ฌ Deep Dive: 0/1 Knapsack
The Problem
Given items with weights and values, maximize value within weight capacity.
๐ฎ Try It Yourself
Watch how the DP table fills up step by step:
Loading visualizer...
Visual Representation
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ 0/1 KNAPSACK โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค โ โ โ Items: [๐ฑ, ๐ป, ๐ท, ๐ง] โ โ Weights: [1, 4, 3, 2] โ โ Values: [15, 30, 20, 10] โ โ Capacity: 5 โ โ โ โ State: dp[i][w] = max value using items 0..i-1 with capacity w โ โ โ โ Transition: โ โ dp[i][w] = max( โ โ dp[i-1][w], // Don't take item i โ โ dp[i-1][w-wt[i]] + val[i] // Take item i (if fits) โ โ ) โ โ โ โ Answer: dp[n][W] = 35 (take ๐ฑ and ๐ป: weights 1+4=5) โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Implementation
JAVA(65 lines)CodeLoading syntax highlighter...
Knapsack Variants
JAVA(52 lines)CodeLoading syntax highlighter...
๐ฌ Deep Dive: Longest Common Subsequence (LCS)
The Problem
Find the longest sequence present in both strings (not necessarily contiguous).
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ LCS VISUALIZATION โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค โ โ โ String A: A B C D G H โ โ String B: A E D F H R โ โ โ โ LCS: A D H (length = 3) โ โ โ โ โ โ โ โ โ State: dp[i][j] = LCS length for A[0..i-1] and B[0..j-1] โ โ โ โ Transition: โ โ if A[i-1] == B[j-1]: โ โ dp[i][j] = dp[i-1][j-1] + 1 // Match! Extend LCS โ โ else: โ โ dp[i][j] = max(dp[i-1][j], dp[i][j-1]) // Skip one char โ โ โ โ "" A E D F H R โ โ "" 0 0 0 0 0 0 0 โ โ A 0 1 1 1 1 1 1 โ โ B 0 1 1 1 1 1 1 โ โ C 0 1 1 1 1 1 1 โ โ D 0 1 1 2 2 2 2 โ โ G 0 1 1 2 2 2 2 โ โ H 0 1 1 2 2 3 3 โ Answer โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Implementation
JAVA(78 lines)CodeLoading syntax highlighter...
LCS Variants
JAVA(34 lines)CodeLoading syntax highlighter...
๐ฌ Deep Dive: Longest Increasing Subsequence (LIS)
The Problem
Find the longest strictly increasing subsequence.
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ LIS EXAMPLE โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค โ โ โ Array: [10, 9, 2, 5, 3, 7, 101, 18] โ โ โ โ LIS: [ 2, 3, 7, 18] (length = 4) โ โ or: [ 2, 5, 7, 18] (also length 4) โ โ โ โ O(nยฒ) DP State: โ โ dp[i] = LIS length ending at index i โ โ โ โ Transition: โ โ dp[i] = 1 + max(dp[j]) for all j < i where arr[j] < arr[i] โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
O(nยฒ) Implementation
JAVA(21 lines)CodeLoading syntax highlighter...
O(n log n) Binary Search Solution
JAVA(70 lines)CodeLoading syntax highlighter...
LIS Variants
JAVA(93 lines)CodeLoading syntax highlighter...
๐ฌ Deep Dive: Edit Distance (Levenshtein)
The Problem
Minimum operations to transform one string to another.
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ EDIT DISTANCE โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค โ โ โ Transform "horse" โ "ros" โ โ โ โ Operations: โ โ horse โ rorse (replace 'h' with 'r') โ โ rorse โ rose (delete 'r') โ โ rose โ ros (delete 'e') โ โ โ โ Edit distance = 3 โ โ โ โ State: dp[i][j] = edit distance for s1[0..i-1] and s2[0..j-1] โ โ โ โ Transition: โ โ if s1[i-1] == s2[j-1]: โ โ dp[i][j] = dp[i-1][j-1] // No operation needed โ โ else: โ โ dp[i][j] = 1 + min( โ โ dp[i-1][j-1], // Replace โ โ dp[i-1][j], // Delete from s1 โ โ dp[i][j-1] // Insert into s1 โ โ ) โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Implementation
JAVA(97 lines)CodeLoading syntax highlighter...
Edit Distance Variants
JAVA(57 lines)CodeLoading syntax highlighter...
๐ฌ Deep Dive: Matrix Chain Multiplication
The Problem
Find the optimal way to parenthesize matrix multiplication to minimize operations.
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ MATRIX CHAIN MULTIPLICATION โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค โ โ โ Matrices: A(10ร30) ร B(30ร5) ร C(5ร60) โ โ โ โ Option 1: (A ร B) ร C โ โ A ร B = 10ร30ร5 = 1500 ops โ result 10ร5 โ โ (AB) ร C = 10ร5ร60 = 3000 ops โ โ Total: 4500 ops โ โ โ โ Option 2: A ร (B ร C) โ โ B ร C = 30ร5ร60 = 9000 ops โ result 30ร60 โ โ A ร (BC) = 10ร30ร60 = 18000 ops โ โ Total: 27000 ops โ โ โ โ Optimal: Option 1 (6ร faster!) โ โ โ โ State: dp[i][j] = min cost to multiply matrices i to j โ โ โ โ Transition: โ โ dp[i][j] = min over k of: โ โ dp[i][k] + dp[k+1][j] + dims[i-1] ร dims[k] ร dims[j] โ โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Implementation
JAVA(59 lines)CodeLoading syntax highlighter...
โ ๏ธ Common Mistakes
Mistake 1: Knapsack Wrong Direction
JAVA(13 lines)CodeLoading syntax highlighter...
Mistake 2: LCS Off-by-One
JAVA(9 lines)CodeLoading syntax highlighter...
Mistake 3: Edit Distance Missing Base Cases
JAVA(7 lines)CodeLoading syntax highlighter...
๐ Debug This: LIS Binary Search Bug
This O(n log n) LIS implementation has a bug. Can you find it?
JAVA(22 lines)CodeLoading syntax highlighter...
๐ Click to reveal the bug
<= instead of < in comparison.JAVA(5 lines)CodeLoading syntax highlighter...
<=, equal elements are placed after existing elements, allowing duplicates in the subsequence. For strictly increasing LIS, we need <.Input: [1, 3, 3, 5] Bug answer: 4 (allows [1, 3, 3, 5]) Correct: 3 ([1, 3, 5])
๐ป Exercises
Exercise 1: Target Sum โญโญ
Given array and target, assign + or - to each element to reach target. Count ways.
JAVA(3 lines)CodeLoading syntax highlighter...
Exercise 2: Longest Palindromic Substring โญโญ
Find the longest palindromic substring (contiguous).
JAVA(3 lines)CodeLoading syntax highlighter...
Exercise 3: Distinct Subsequences โญโญโญ
Count distinct subsequences of s that equal t.
JAVA(3 lines)CodeLoading syntax highlighter...
Exercise 4: Interleaving String โญโญโญ
Check if s3 is formed by interleaving s1 and s2.
JAVA(3 lines)CodeLoading syntax highlighter...
Exercise 5: Burst Balloons โญโญโญโญ
Burst balloons to maximize coins (similar to matrix chain).
JAVA(4 lines)CodeLoading syntax highlighter...
๐ค Interview Questions
Q1: "Explain the difference between LCS and LIS."
| Aspect | LCS | LIS |
|---|---|---|
| Input | Two sequences | One sequence |
| Goal | Longest common to both | Longest increasing |
| State | dp[i][j] - 2D | dp[i] - 1D |
| Time | O(nm) | O(nยฒ) or O(n log n) |
| Application | Diff, DNA alignment | Patience sorting |
Q2: "How would you optimize 0/1 Knapsack for very large capacity?"
-
Meet in the middle (if n โค 40):
- Split items into two halves
- Enumerate all 2^(n/2) combinations for each
- Use binary search to find best complement
- O(2^(n/2) ร n) instead of O(nW)
-
If values are small (sum of values โค V):
- dp[v] = minimum weight to achieve value v
- O(nV) instead of O(nW)
-
Sparse DP (if few distinct weights):
- Use HashMap instead of array
- Only store reachable states
Q3: "When would edit distance give wrong results for spell checking?"
-
Doesn't consider keyboard layout:
- "teh" โ "the" (2 edits)
- But they're adjacent keys - should be weighted lower
-
Ignores phonetics:
- "knight" vs "nite" (4 edits)
- But they sound the same
-
Equal cost for all operations:
- Transposition ("hte" โ "the") costs 2 but is a common typo
- Damerau-Levenshtein (adds transposition)
- Weighted edit distance (keyboard-aware)
- Soundex/Metaphone (phonetic matching)
Q4: "How is LIS related to patience sorting?"
Patience sorting: - Deal cards into piles - Each pile is descending - Place card on leftmost pile where it fits - Number of piles = LIS length LIS algorithm: - tails[i] = smallest ending element of LIS length i+1 - Binary search to find where new element goes - Same as finding which pile to place card This connection shows: 1. LIS can be found in O(n log n) 2. Patience sorting produces an optimal LIS 3. The algorithm is actually a greedy approach
Q5: "How would you find all LCS strings, not just length?"
JAVA(41 lines)CodeLoading syntax highlighter...
๐ Quick Reference
Pattern Recognition
| Problem Type | State | Transition |
|---|---|---|
| 0/1 Knapsack | dp[i][w] | max(skip, take) |
| Unbounded Knapsack | dp[w] | max over all items |
| LCS | dp[i][j] | match or max(skip) |
| LIS | dp[i] | max(dp[j]+1) for j<i, a[j]<a[i] |
| Edit Distance | dp[i][j] | match or 1+min(ops) |
| Matrix Chain | dp[i][j] | min over split point |
Complexity Summary
| Algorithm | Time | Space (Optimized) |
|---|---|---|
| 0/1 Knapsack | O(nW) | O(W) |
| LCS | O(nm) | O(min(n,m)) |
| LIS | O(n log n) | O(n) |
| Edit Distance | O(nm) | O(min(n,m)) |
| Matrix Chain | O(nยณ) | O(nยฒ) |
Key Code Patterns
JAVA(11 lines)CodeLoading syntax highlighter...
๐ What's Next?
- DP on trees
- Bitmask DP
- Digit DP
- Convex hull trick
- Space optimization techniques
๐ Review Schedule
| Day | Focus | Time |
|---|---|---|
| 0 | Full read + Knapsack exercise | 90 min |
| 1 | Quick Reference | 10 min |
| 3 | Implement LCS from memory | 20 min |
| 7 | LIS + Edit Distance exercises | 30 min |
| 14 | Debug exercise + Matrix Chain | 20 min |
| 30 | All interview questions | 15 min |