Introduction
In our last lesson, we mastered the unbounded choice DP pattern, where you could use items an infinite number of times. You saw how its recurrence relation, which depends on the current row's calculations, naturally leads to a space-optimized solution with a forward (left-to-right) inner loop.
Today, we address the other fundamental DP pattern: 0/1 Knapsack. The learning outcome is to solve 0/1 knapsack problems and its variations, such as Subset Sum and Partition Equal Subset Sum. The core constraint here is that each item can be chosen at most once. This seemingly small change fundamentally alters the DP recurrence and, crucially, the strategy for space optimization.
Mastering the distinction between these two patterns is critical for Staff-level interviews, as it demonstrates a deep, first-principles understanding of dynamic programming, moving beyond simple formula memorization.
1. The 0/1 Knapsack Problem
The 0/1 Knapsack problem is a classic optimization problem. Its structure forms the basis for many other DP problems you'll encounter.
Problem Definition: You are given items, each with a weight and a value . You have a knapsack with a maximum weight capacity . Your goal is to choose a subset of items to include in the knapsack such that the total value is maximized, and the total weight does not exceed . Each item can either be included (1) or not included (0).
To build our DP solution, let's first think recursively. At each item i, we have two choices:
- Don't take item
i: We move on to the next item (i-1) with the same knapsack capacity. The value is whatever we can get from the remaining items. - Take item
i: We add its value,v_i, to our total. We then solve the subproblem for the remaining items (i-1) with a reduced knapsack capacity ofW - w_i. This choice is only possible ifw_i <= W.
We want the maximum value from these two choices. This "take" or "not take" branching logic is the heart of the 0/1 pattern.
To see this logic developed from scratch, from the recursive formula all the way to a space-optimized solution, the following video is an excellent guide.
DP 19. 0/1 Knapsack | Recursion to Single Array Space Optimised Approach | DP on Subsequences
This video from 'take U forward' thoroughly explains the 0/1 Knapsack problem. It starts with the basic recursive idea and progressively builds up to the most optimized solution.
Please watch from the beginning to 17:37. This covers: The problem statement and why a greedy approach fails (00:59 - 07:58). The derivation of the recursive solution, defining the state and the 'pick' vs 'not pick' logic (07:58 - 17:37).\nFocus on understanding the recurrence relation f(index, W). This is the foundation for everything that follows.
2. From Recursion to a Space-Optimized Solution
The recursive solution has overlapping subproblems, which makes it a perfect candidate for dynamic programming.
Top-Down (Memoization) and Bottom-Up (Tabulation)
As the video shows, we can optimize the recursion by storing the results of subproblems in a 2D array, dp[i][w], where i is the item index and w is the capacity.
The state transition for the bottom-up (tabulation) approach is:
Notice the key difference from unbounded knapsack: the "take" case dp[**i-1**][w - w_{i-1}] depends only on the results from the previous row (i-1).

Space Optimization: The Right-to-Left Traversal
Since each cell dp[i][w] only depends on the previous row dp[i-1], we can optimize the space from to just by using a single 1D array.
However, this is where the contrast with the last lesson is most important.
- In Unbounded Knapsack, we iterated the inner capacity loop from left-to-right because we wanted to use an item multiple times.
dp[c-w]would refer to an already-updated value in the current pass. - In 0/1 Knapsack, we must iterate the inner capacity loop from right-to-left. This ensures that when we calculate
dp[w], the valuedp[w - w_{i-1}]we use still holds the result from the previous pass (the previous row in the 2D table). If we went left-to-right, we might use the same item multiple times within the same pass, incorrectly solving it as an unbounded knapsack problem.
This distinction is a crucial, Staff-level detail. Now, let's see the definitive explanation of this optimization.
DP 19. 0/1 Knapsack | Recursion to Single Array Space Optimised Approach | DP on Subsequences
Let's continue with the 'take U forward' video. The final part explains the single-array space optimization and the critical importance of the right-to-left loop.
Please watch from 34:15 to 41:09. This section is the most important part of the lesson. It explains why a single array is sufficient and why the inner loop must run backward. Understanding this 'why' is key.
The final, space-optimized Go code looks like this:
func knapsack01(weights []int, values []int, capacity int) int {
n := len(weights)
dp := make([]int, capacity+1)
// Iterate through each item
for i := 0; i < n; i++ {
// Iterate backward through capacities
for w := capacity; w >= weights[i]; w-- {
// dp[w] currently holds the value from the previous item's pass
// dp[w-weights[i]] also holds a value from the previous pass
// because we are iterating from right to left.
dp[w] = max(dp[w], values[i] + dp[w-weights[i]])
}
}
return dp[capacity]
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
3. Variation 1: Subset Sum Problem
Now let's apply this pattern. A very common interview problem is Subset Sum, which is a disguised 0/1 Knapsack problem.
Problem: Given a set of non-negative integers and a target sum, determine if a subset of the integers adds up to the target.
Reduction to 0/1 Knapsack:
- Items: The numbers in the input array.
- "Weight" of an item: The number itself.
- "Value" of an item: Not relevant in the standard sense. We only care if the sum is achievable.
- Knapsack "Capacity": The target sum.
- Goal: Determine if the knapsack can be filled exactly to its capacity.
The DP state dp[s] will be a boolean: true if sum s is achievable, false otherwise.
The recurrence for the space-optimized solution is:dp[s] = dp[s] || dp[s - num]
We'll use a textual resource this time that provides clean, idiomatic Go code for this problem.
This article from 'reintech.io' provides a concise explanation of the Subset Sum problem and its DP solutions in Go.
First, read the 'Dynamic Programming Solution' section to understand the 2D DP table approach. Then, read the 'Space-Optimized Dynamic Programming' section. Notice how its Go code is almost identical in structure to our optimized 0/1 Knapsack solution, including the backward inner loop.
4. Variation 2: Partition Equal Subset Sum
This is another classic problem (LeetCode 416) that builds directly on Subset Sum.
Problem: Given an array of positive integers nums, can it be partitioned into two subsets with equal sums?
The crucial insight is to reduce this to a Subset Sum problem.
- Calculate the total sum of all numbers in the array,
totalSum. - If
totalSumis odd, it's impossible to partition it into two equal integer sums. Returnfalseimmediately. - If
totalSumis even, the target sum for each subset must betarget = totalSum / 2. - The problem now becomes: "Is there a subset of
numsthat sums up totarget?" This is exactly the Subset Sum problem we just solved.
This resource provides an excellent summary and the optimal Go solution.
416. Partition Equal Subset Sum - Solution & Explanation
This NeetCode solution page for 'Partition Equal Subset Sum' clearly explains the reduction to Subset Sum and provides the most optimal 1D DP implementation.
Please read these three sections: 'Prerequisites' and 'Intuition': Confirms the link to the 0/1 Knapsack and Subset Sum patterns. 'Dynamic Programming (Optimal)': Study the algorithm and the Go code. You'll see it's the exact same logic as the space-optimized Subset Sum solution. 'Common Pitfalls': This is a great section for Staff-level thinking. It highlights key mistakes like forgetting the odd sum check or using the wrong loop direction.
The Go solution from the resource elegantly combines these steps:
func canPartition(nums []int) bool {
total := 0
for _, num := range nums {
total += num
}
if total%2 != 0 {
return false
}
target := total / 2
dp := make([]bool, target+1)
dp[0] = true
for _, num := range nums {
for j := target; j >= num; j-- {
dp[j] = dp[j] || dp[j-num]
}
}
return dp[target]
}
This clean, efficient solution is exactly what an interviewer is looking for.
Conclusion
In this lesson, you explored the 0/1 Knapsack pattern and its common variations. The main goal was to solidify the underlying mechanics and contrast them with the unbounded choice pattern from the previous lesson.
Key Takeaways:
- Pattern Recognition: The 0/1 Knapsack pattern applies when you must make a "take it or leave it" decision for a collection of unique items to optimize a goal within a certain capacity.
- Recurrence and Dependency: The core recurrence
dp[i][w] = op(dp[i-1][w], ... + dp[i-1][w-w_i])shows that solutions for itemidepend only on solutions from itemi-1. - Space Optimization: This dependency mandates a right-to-left (backward) inner loop when using a 1D DP array. This prevents an item from being used multiple times in a single pass.
- Problem Reduction: Many problems, like Subset Sum and Partition Equal Subset Sum, are direct applications of the 0/1 Knapsack pattern. The key skill is identifying the "items," "weights," and "capacity" in the context of the new problem.
Preview of the Next Lesson:
We will move on to another fundamental 2D DP pattern: sequence comparison. You will learn to solve problems like Longest Common Subsequence and Edit Distance. This pattern involves comparing two inputs (e.g., strings) and building a 2D DP table where dp[i][j] represents a solution involving the first i elements of the first input and the first j elements of the second.