0/1 knapsack
medium 22 minPack items with weights and values into a bag of capacity W to get the most value, each item taken whole or not at all.
See it run
Each item is packed once or not at all: watch the take-or-skip tree collapse into an (items × capacity) table, read the chosen items back out of it, and squeeze it into one row swept right to left.
Operations
Take or skip: brute recursion
f(i, cap) is the most value from the first i items with cap units of room. It tries both choices for item i: leave it, f(i - 1, cap), or pack it, value + f(i - 1, cap - weight), when it fits. Three day-hike items and a capacity of 4 already repeat a subtree.
Step 1 of 9
The question: f(3, 4)
items (w, v): (1, 2) (2, 5) (2, 4) · W = 4
Items: snacks (weight 1, value 2), first aid (2, 5), camera (2, 4). Room: 4. f(3, 4) asks for the best value using all three items with 4 units of room. Base case: f(0, cap) = 0, no items, no value.
Step 1: The question: f(3, 4)
def best(i, cap): """Most value from the first i items with room cap.""" if i == 0: return 0 # no items left wt, val = weights[i - 1], values[i - 1] skip = best(i - 1, cap) # leave item i if wt > cap: return skip # it does not fit: one branch only take = val + best(i - 1, cap - wt) # pack it and lose wt of room return max(skip, take)- Time
- O(2ⁿ)
- Space
- O(n) call stack
- 3 items here
- 14 calls, 11 distinct
- 30 items
- up to about 2 billion calls
Name the state before you code it: (items still in play, room left). Two numbers fully describe the subproblem, and that pair is exactly what the memo and the table are indexed by.
In the real world
The same 0/1 knapsack doing real jobs. Pick one and step through it.
The old app's light trip: snacks (1, 2), first aid (2, 5), camera (2, 4), binoculars (3, 3), and a 5 kg pack.
Step 1 of 3
First two rows
| 0 | 1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|---|
| 0 none | 0 | 0 | 0 | 0 | 0 | 0 |
| 1 snacks | 0 | 2 | 2 | 2 | 2 | 2 |
| 2 first aid | 0 | 2 | 5 | 7 | 7 | 7 |
| 3 camera | · | · | · | · | · | · |
| 4 binocs | · | · | · | · | · | · |
Snacks fill row 1 with 2. First aid: dp[2][2] = 5, dp[2][3] = 5 + dp[1][1] = 7 (first aid and snacks), and 7 to the end.
Step 1: First two rows
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Sweeping capacity left to right in the one-row version
criticalA forward loop reads dp[w - wt] after it was already updated for this item, so the item can be packed again and again. That solves the unbounded knapsack. On the camping trip the bottle alone fills all 7 units.
Wrongfor wt, val in zip(weights, values): for w in range(wt, W + 1): # left to right dp[w] = max(dp[w], val + dp[w - wt]) # reuses this itemRightfor wt, val in zip(weights, values): for w in range(W, wt - 1, -1): # right to left dp[w] = max(dp[w], val + dp[w - wt]) # reads the old rowReading the current row in the 2D take option
criticalThe take option must look at row i - 1: the best without item i. Reading dpi[w - wt] allows item i to be taken again, which is unbounded knapsack again.
Wrongtake = val + dp[i][w - wt] # item i can repeatRighttake = val + dp[i - 1][w - wt] # item i used at most onceSkipping the fit check (Python's negative index)
criticalWithout if wt <= w, dp[i - 1][w - wt] gets a negative index. Python does not crash: it reads from the end of the row, a large capacity, and silently returns a too-big answer.
Wrongfor w in range(W + 1): dp[i][w] = max(dp[i - 1][w], val + dp[i - 1][w - wt]) # w - wt < 0 wrapsRightfor w in range(W + 1): dp[i][w] = dp[i - 1][w] if wt <= w: dp[i][w] = max(dp[i][w], val + dp[i - 1][w - wt])Greedy by value per weight
majorPacking the best ratios first is right for fractional knapsack and wrong for 0/1: on the camping trip it packs the stove and the bottle for 8, while the bag and the tent give 9.
Wrongitems.sort(key=lambda it: it[1] / it[0], reverse=True)for wt, val in items: if wt <= room: room -= wt; total += val # 8 on the camping tripRightdp = [0] * (W + 1)for wt, val in items: for w in range(W, wt - 1, -1): dp[w] = max(dp[w], val + dp[w - wt]) # 9Memo keyed on the item index only
majorThe answer depends on both the item index and the room left. A memo keyed on i returns the answer for whatever capacity reached i first, which is wrong for every other capacity.
Wrongif i in memo: return memo[i] # ignores capRightif (i, cap) in memo: return memo[(i, cap)] # both parts of the stateBacktracking without reducing w
minorAfter deciding item i was packed you must move to column w - weight; staying in the same column compares the wrong cells and reports items that were never in the load.
Wrongif dp[i][w] != dp[i - 1][w]: picked.append(i - 1) # w never changesRightif dp[i][w] != dp[i - 1][w]: picked.append(i - 1) w -= weights[i - 1]
Interview tips
How to explain it
- State: dp[i][w] is the best value from the first i items with room w.
- Leave item i: dp[i - 1][w]. Take it if it fits: value + dp[i - 1][w - weight]. Keep the max.
- Row 0 and column 0 are zeros; the answer is dp[n][W]; O(n·W) time.
- Then: one row of W + 1 cells, swept right to left, for O(W) space.
Spot it in problems
- Choose a subset under a budget (weight, cost, time) to maximise a total.
- Each item usable at most once; a yes or no decision per item.
- Subset sum, partition equal subset sum, target sum, last stone weight II.
- Two budgets (ones and zeroes): the same idea with a 2D capacity.
Memory tricks
- TLC: Take, Leave, Choose the max.
- 0/1 sweeps backward, unbounded sweeps forward.
- Camping trip to know cold: capacity 7, answer 9 (sleeping bag and tent).
Watch out
- Always check wt <= w before reading w - wt.
- Greedy by ratio only works when items can be cut.
- W is a number: a huge capacity makes the table impossible.
- Keep the 2D table if you must list the items.