0/1 Knapsack and Unbounded Knapsack
Interview guide for 0/1 Knapsack and Unbounded Knapsack with intuition, dry run, C++ code, complexity, and practice problems
This article covers the intuition, workflow, dry run, C++ implementation, complexity, and interview usage for 0/1 Knapsack and Unbounded Knapsack.
1. Intuition
Knapsack asks how to maximize value under a capacity constraint.
- 0/1 knapsack: take each item at most once
- unbounded knapsack: reuse items unlimited times
2. How It Works
For 0/1 knapsack:
dp[i][w]= best value using firstiitems and capacityw- Either skip the item or take it once
For unbounded knapsack:
- Similar state
- When taking the item, stay on the same row or iterate capacity forward
3. Pattern Recognition
Think knapsack when you see:
- capacity or budget
- choose items for best score
- subset under weight constraint
4. Dry Run Example
Input:
weights = [1, 3, 4], values = [15, 20, 30], capacity = 4Step-by-step execution:
- Best with capacity
4is taking weight4value30 - Or weight
1 + 3gives35
Final Output:
355. Code (C++)
int knapsack01(const vector<int>& weight, const vector<int>& value, int cap) {
vector<int> dp(cap + 1, 0);
for (int i = 0; i < static_cast<int>(weight.size()); i++) {
for (int w = cap; w >= weight[i]; w--) {
dp[w] = max(dp[w], value[i] + dp[w - weight[i]]);
}
}
return dp[cap];
}6. Complexity Analysis
- Time Complexity:
O(n * capacity) - Space Complexity:
O(capacity)
7. When to Use
- capacity optimization
- subset-choice scoring
- coin change style problems
8. Common Mistakes
- iterating capacity in the wrong direction
- confusing 0/1 with unbounded transitions
9. Variations / Extensions
- coin change
- target sum
- partition equal subset sum
10. LeetCode Practice Problems
Medium
- https://magicsheet.dev/questions/partition-equal-subset-sum/
- https://magicsheet.dev/questions/coin-change/
Hard
11. Key Takeaways
- Loop direction often reveals whether reuse is allowed
- Knapsack is one of the most reusable DP patterns