0/1 Knapsack: Space-Efficient DP with Item Recovery
Dynamic ProgrammingModel answerLast updated
Implement a weight-capacity optimizer returning max value and an exact item set, using O(W) space DP, then extend to unbounded and bounded variants.
Weight-Limited Value Maximizer
You have n items. Each item has a positive integer weight and a non-negative integer value. You also have a bag with a maximum weight capacity W.
Your goal is to select a subset of items — using each item at most once — so that the total weight does not exceed W and the total value is as high as possible.
What to implement
-
Core solver. Write a function that takes the weight list, value list, and capacity
W, and returns:- the maximum achievable total value, and
- one list of item indices (0-based) that achieves it.
-
Complexity target. Your solution must run in O(n·W) time and use O(W) working space (excluding the output list). Explain clearly how you reconstruct the chosen items from a space-compressed state — this is the hardest part of the problem.
-
Variant discussion. After presenting your core solution, explain in words (and optionally code) how you would adapt it to:
- Unbounded knapsack — each item may be picked any number of times.
- Bounded knapsack — item
imay be picked at mostk_itimes.
Give the time and space complexity for each variant.
Constraints
1 ≤ n ≤ 1 0001 ≤ W ≤ 10 0001 ≤ weight[i] ≤ W0 ≤ value[i] ≤ 10 000- Any valid optimal subset is acceptable when there are ties.
- Assume all values are non-negative (confirm with the interviewer in practice).
Example
weights = [1, 3, 4, 5]
values = [1, 4, 5, 7]
W = 7
Output: max_value = 9, items = [1, 2]
Items 1 and 2 have combined weight 3 + 4 = 7 and combined value 4 + 5 = 9.
Hints
Hint 1
For the value DP, think about what happens if you iterate capacity upward versus downward when processing each item — the direction enforces whether an item can be reused.
Hint 2
A 1-D array overwrites earlier states as you go, so you can't simply backtrack to find which items were chosen. One practical workaround stores a single decision bit per (item, capacity) cell in O(n·W) bits total. A cleverer approach splits the item list in half, runs DP on each half separately, then finds the optimal split point and recurses — this reuses the same O(W) arrays at every level.
Hint 3
For the bounded variant, think about how to convert 'at most k copies' into a form your 0/1 solver already handles. Powers of two let you represent any count from 0 to k as a subset sum of O(log k) bundles.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core 0/1 DP for Value
Define dp[c] as the best total value achievable using items seen so far with total weight at most c. For each item with weight w and value v, update:
for c from W down to w:
dp[c] = max(dp[c], dp[c - w] + v)
The downward iteration is the key invariant. When we read dp[c - w], it still reflects the state before this item was considered, so each item is counted at most once. Upward iteration would let the same item be counted repeatedly (which is the unbounded variant).
This gives O(n·W) time and O(W) space for the value alone.
Reconstructing the Item Set — the Hard Part
A 1-D array discards the per-item history. Two options:
Option 1 — Decision bitset. Store a bit keep[i][c] for every (item, capacity) pair during the forward pass, then trace back from c = W. This is simple and correct, but uses O(n·W) bits of memory — not O(W) working space. Acceptable for most practical sizes; be honest about the tradeoff.
Option 2 — Divide and conquer (true O(W) space). This is the approach that fully satisfies the stated bound:
- Split the items into a left half
[lo, mid]and right half[mid+1, hi]. - Run the 1-D DP on the left half to get array
f, and independently on the right half to get arrayg. Both use at-most-c semantics, so both are non-decreasing. - Find
c* = argmax_c f[c] + g[W - c]. This is the capacity budget optimally assigned to the left half. - Free
fandg, then recurse: left half with capacityc*, right half with capacityW - c*. - Base case: one item — take it if it fits and has positive value.
Why it's correct. Take any optimal set S. Its left items use some weight a and right items use weight b, with a + b ≤ W. Then f[a] ≥ val(S_left) and g[W - a] ≥ val(S_right) (the right DP has slack capacity available). So max_c f[c] + g[W-c] ≥ OPT. Every feasible split also yields a feasible whole, so the maximum equals OPT exactly. Recursion preserves this argument at every level.
Complexity. At depth k there are 2^k subproblems, each with about n/2^k items, and their capacities sum to at most W. Work per level is O(n/2^k · W) · 2^k = O(n·W). Summed over O(log n) levels: O(n·W) time. The f and g arrays are freed before recursing, so working space stays O(W) plus an O(log n) call stack.
Python Implementation
from typing import List, Tuple
def _dp_half(weights: List[int], values: List[int],
lo: int, hi: int, cap: int) -> List[int]:
"""1-D 0/1 DP over items[lo..hi] with capacity cap."""
dp = [0] * (cap + 1)
for i in range(lo, hi + 1):
w, v = weights[i], values[i]
if w > cap or v <= 0:
continue
for c in range(cap, w - 1, -1):
candidate = dp[c - w] + v
if candidate > dp[c]:
dp[c] = candidate
return dp
def knapsack_01(weights: List[int], values: List[int],
W: int) -> Tuple[int, List[int]]:
"""
Returns (max_value, sorted list of chosen item indices).
O(n*W) time, O(W) working space + O(log n) stack + output.
"""
n = len(weights)
if n == 0 or W == 0:
return 0, []
chosen: List[int] = []
def solve(lo: int, hi: int, cap: int) -> None:
if lo > hi or cap == 0:
return
if lo == hi:
if weights[lo] <= cap and values[lo] > 0:
chosen.append(lo)
return
mid = (lo + hi) // 2
f = _dp_half(weights, values, lo, mid, cap)
g = _dp_half(weights, values, mid + 1, hi, cap)
best_c, best_val = 0, -1
for c in range(cap + 1):
s = f[c] + g[cap - c]
if s > best_val:
best_val, best_c = s, c
del f, g # keep memory O(W)
solve(lo, mid, best_c)
solve(mid + 1, hi, cap - best_c)
total = _dp_half(weights, values, 0, n - 1, W)[W]
solve(0, n - 1, W)
chosen.sort()
return total, chosen
Sanity check: weights=[1,3,4,5], values=[1,4,5,7], W=7 → (9, [1, 2]).
Edge Cases
W = 0orn = 0: return 0 with an empty set.- Items heavier than
W: the inner loop range is empty — they're automatically skipped. - Zero-weight items with positive value:
dp[c] = max(dp[c], dp[c] + v)reads before it writes; the item is added once, which is correct. - Zero-value items: the DP skips them since
v <= 0; the returned set stays minimal. - Negative values: the problem assumes non-negative; verify with the interviewer before coding.
Variant 1: Unbounded Knapsack
Each item can be chosen any number of times. Flip the loop direction to upward:
dp = [0] * (W + 1)
choice = [-1] * (W + 1)
for c in range(1, W + 1):
for i, (w, v) in enumerate(zip(weights, values)):
if w <= c and dp[c - w] + v > dp[c]:
dp[c] = dp[c - w] + v
choice[c] = i
When c - w is read after the current item has been processed for smaller capacities, it can already include that item — giving unlimited reuse. Reconstruction traces choice[c] back from W in O(W) time and O(W) space. Watch out for zero-weight positive-value items: the answer becomes unbounded.
Complexity: O(n·W) time, O(W) space.
Variant 2: Bounded Knapsack (item i usable at most k_i times)
Binary splitting (simple). Decompose k_i copies of item i into virtual items of 1, 2, 4, …, 2^(p−1), and one remainder bundle. Any count 0 to k_i is representable as a subset of these O(log k_i) bundles. Run the standard 0/1 solver on all bundles. Time: O(W · Σ log k_i). Space: O(W). Reconstruction: tag each bundle with its source item and count, sum up.
Monotone-queue DP (optimal). For item (w, v, k), group capacity indices by residue r = c mod w. Along residue class r, the DP becomes a sliding-window maximum over a window of size k, solvable with a deque. This achieves O(n·W) time and O(W) space — same asymptotic cost as the unbounded case. Reconstruction can reuse the divide-and-conquer split from the 0/1 solver, since each half still requires only a single O(W) pass.
Common Mistakes
- Iterating upward in 0/1: the most frequent error. Upward iteration silently converts 0/1 into unbounded. Always double-check the loop direction against the variant you're implementing.
- Claiming O(W) space while storing
keep[i][c]: O(n·W) bits is not O(W). Be precise; interviewers notice. - Missing the pseudo-polynomial caveat: O(n·W) is polynomial in the numeric value of W, not its bit length. For inputs where W is exponentially large but item values are small, flip the DP to
minWeight[total_value], costing O(n · ΣV). - Forgetting non-decreasing semantics in the split step: the correctness of the divide-and-conquer split relies on
gbeing non-decreasing in capacity. This holds because more capacity never hurts — confirm it when explaining the proof.