Space-Optimized Knapsack and Multi-Copy Variants
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Given n candidate items — where item i has an integer weight weights[i] and an integer value values[i] — along with an integer weight limit capacity, implement three related knapsack solvers that return both the optimal total value and a valid selection achieving that value:
-
knapsack_01(weights, values, capacity) -> Tuple[int, List[int]]Each item may be chosen at most once (0or1time). Return(best_value, chosen), wherechosenis one optimal list of distinct item indices in strictly increasing order whose combined weight is at mostcapacityand whose values sum tobest_value(omit zero-value items that add nothing tobest_value). Your implementation must run inO(n * capacity)time usingO(capacity)dynamic-programming working memory, reconstructingchosenwithout storing anO(n * capacity)state table. -
unbounded_knapsack(weights, values, capacity) -> Tuple[int, List[int]]Each item may be chosen any non-negative integer number of times (0, 1, 2, ...), and everyweights[i]must be at least1. Return(best_value, counts), wherecountshas lengthnandcounts[i]gives how many copies of itemiare taken. -
bounded_knapsack(weights, values, limits, capacity) -> Tuple[int, List[int]]Itemimay be chosen at mostlimits[i]times (0 <= counts[i] <= limits[i]). Return(best_value, counts).
Raise ValueError whenever input lengths do not match (len(weights) != len(values), or len(limits) != len(weights) in bounded_knapsack), whenever capacity or any weight, value, or limit is negative, or whenever any item passed to unbounded_knapsack has weight == 0.
Examples
Example 1
Input: knapsack_01(weights=[2, 4, 5, 6], values=[5, 8, 9, 10], capacity=9)
Output: (17, [1, 2])
Selecting greedily by value-per-weight ratio (2.50, 2.00, 1.80, 1.67) picks items 0 and 1 for weight 2 + 4 = 6 and value 5 + 8 = 13, stranding 3 units of unused capacity. Picking items 1 and 2 uses exact weight 4 + 5 = 9 and achieves the maximum possible total value 8 + 9 = 17.
Example 2
Input: unbounded_knapsack(weights=[2, 3, 5], values=[5, 8, 12], capacity=8)
Output: (21, [1, 2, 0])
Four copies of item 0 yield 4 * 5 = 20, and one copy each of items 1 and 2 yields 8 + 12 = 20. Taking 1 copy of item 0 (weight = 2, value = 5) plus 2 copies of item 1 (weight = 6, value = 16) fills capacity 8 and reaches optimal value 21.
Example 3
Input: bounded_knapsack(weights=[2, 3, 5], values=[5, 8, 12], limits=[3, 1, 2], capacity=8)
Output: (20, [0, 1, 1])
Because limits[1] == 1 forbids taking two copies of item 1 and limits[0] == 3 forbids taking four copies of item 0, the best valid multiset takes 0 copies of item 0, 1 copy of item 1 (weight = 3, value = 8), and 1 copy of item 2 (weight = 5, value = 12) for total weight 8 and value 20.
Constraints
0 <= len(weights) == len(values) <= 200(andlen(limits) == len(weights)forbounded_knapsack)0 <= capacity <= 10^40 <= weights[i], values[i], limits[i] <= 10^4(andweights[i] >= 1forunbounded_knapsack)- Invalid inputs must raise
ValueError. knapsack_01must run inO(n * capacity)time (plusO(n log n)divide-and-conquer overhead whencapacity == 0) withO(capacity)DP working space (O(capacity + n)total including call stack and output indices).
Step-by-step walkthrough
Restate the problem and input/output contract
Given
nitems with non-negative integerweightsandvaluesplus an integer limitcapacity(W ≥ 0), we want to solve 0/1 Knapsack — selecting each item at most once so total weight stays≤ Wand total value is maximized — returning both the optimal value and one optimal list of sorted item indices inO(nW)time andO(W)working DP memory. We then extend the solver to unbounded knapsack (unlimited copies per item) and bounded knapsack (at mostlimits[i]copies of itemi).Notice on Example 1 (
weights = [2, 4, 5, 6],values = [5, 8, 9, 10],W = 9) why sorting items greedily byvalue / weightfails for 0/1 items:capacity W = 9 item 0: weight 2, value 5 (ratio 2.50) item 1: weight 4, value 8 (ratio 2.00) item 2: weight 5, value 9 (ratio 1.80) item 3: weight 6, value 10 (ratio 1.67) Greedy takes item 0 + item 1 -> weight 6, value 13 (3 capacity wasted, items 2 and 3 cannot fit!) Optimal takes item 1 + item 2 -> weight 9, value 17We implement all three variants cleanly behind a shared input validator:
from typing import List, Tuple def _validate_inputs(weights: List[int], values: List[int], capacity: int) -> None: """Ensure weights, values, and capacity satisfy basic non-negativity and length rules.""" if len(weights) != len(values): raise ValueError("weights and values must have the same length") if capacity < 0: raise ValueError("capacity must be >= 0") for idx in range(len(weights)): if weights[idx] < 0 or values[idx] < 0: raise ValueError("weights and values must be >= 0")Throughout the 0/1 walkthrough we trace
weights = [2, 4, 5, 6],values = [5, 8, 9, 10],W = 9, whose optimal subset is[1, 2](weights4 + 5 = 9, value8 + 9 = 17).Compress the 2D DP table into one O(W) row
Trying all
2ⁿsubsets is already> 10¹²checks atn = 40. Dynamic programming (DP) instead builds a tabledp[i][cap]= maximum value achievable using a subset of the firstiitems within weight limitcap:dp[0][cap] = 0 dp[i][cap] = max( dp[i - 1][cap], # skip item i-1 dp[i - 1][cap - w] + v # take item i-1 once (only when w <= cap) )Storing the full
(n + 1) × (W + 1)table makes reconstruction easy, but atn = 1,000andW = 1,000,000that is10⁹integers — gigabytes of RAM. Because rowionly ever reads rowi − 1, we can overwrite a single 1D listbest_for_capof lengthW + 1in place, as long as we scancapfrom right (W) down to left (w):Right-to-left scan for item with w = 4, v = 8: cap = 8 reads best_for_cap[4] BEFORE best_for_cap[4] is updated -> item used at most once! Left-to-right scan (WRONG for 0/1): cap = 4 updates best_for_cap[4] = 8 first, then cap = 8 reads best_for_cap[4] = 8 and writes 16 -> item used TWICE!We write this 1D pass over an arbitrary slice of items
[lo, hi)so we can reuse it on sub-ranges in the next step:from typing import List def _dp_1d_range( weights: List[int], values: List[int], lo: int, hi: int, capacity: int ) -> List[int]: """Compute 1D 0/1 knapsack DP over items in slice [lo, hi) up to capacity.""" # best_for_cap: length (capacity + 1) list; best_for_cap[cap] = max value using subset of items lo..hi-1 with weight <= cap best_for_cap = [0] * (capacity + 1) for item_idx in range(lo, hi): item_weight = weights[item_idx] item_value = values[item_idx] # Iterate capacity right-to-left so best_for_cap[cap - item_weight] still holds # the value from BEFORE item_idx was considered, preventing using item_idx twice. for cap in range(capacity, item_weight - 1, -1): candidate_value = best_for_cap[cap - item_weight] + item_value if candidate_value > best_for_cap[cap]: best_for_cap[cap] = candidate_value return best_for_capRow evolution on Example 1 (
weights = [2, 4, 5, 6],values = [5, 8, 9, 10],W = 9):cap: 0 1 2 3 4 5 6 7 8 9 start 0 0 0 0 0 0 0 0 0 0 + item 0 (w2, v5) 0 0 5 5 5 5 5 5 5 5 + item 1 (w4, v8) 0 0 5 5 8 8 13 13 13 13 + item 2 (w5, v9) 0 0 5 5 8 9 13 14 14 17 + item 3 (w6, v10) 0 0 5 5 8 9 13 14 15 17 -> max value = 17Why you cannot just walk backward on a single 1D row
Beginners often try to reconstruct the chosen 0/1 items directly from the final 1D array by checking whether
best_for_cap[cap] == best_for_cap[cap - w] + v. That breaks! Once earlier rows are overwritten,best_for_cap[cap - w]may already include the very item you are testing.Here is a minimal counterexample (
weights = [2],values = [5],W = 4):cap: 0 1 2 3 4 start 0 0 0 0 0 + item 0 (2,5) 0 0 5 5 5 <- final 1D array Naive check at cap = 4: does best[4] == best[4 - 2] + 5? 5 == 5 + 5 -> 5 == 10 (FALSE!)Because
best[2]already counted item0, the naive check falsely concludes item0was skipped and returns[]even though the optimal value is5.Storing a boolean
took[n][W + 1]table fixes walk-back, and shrinks memory by ~64× if bit-packed, butn × (W + 1)bits is stillO(nW)space, violating the strictO(W)space requirement. To reconstruct in trueO(W)working memory, we recompute smartly instead of storingnrows.Reconstruct in O(W) space by splitting items and capacity
Use Hirschberg's divide-and-conquer idea (originally invented to align DNA strings in linear memory). Split the items
lo..hi-1at midpointmid = (lo + hi) // 2into a left half[lo, mid)and a right half[mid, hi).Any optimal subset
Snaturally partitions into left-half itemsS_leftand right-half itemsS_rightwhose weights sum to at mostW. If the left half getsleft_capunits of capacity, the right half getsW − left_capunits. So if we compute two 1D DP rows:left_best = _dp_1d_range(weights, values, lo, mid, W)right_best = _dp_1d_range(weights, values, mid, hi, W)
then scanning
left_capfrom0toWto maximizeleft_best[left_cap] + right_best[W − left_cap]tells us the exact capacity budgetbest_left_capthat some optimal solution spends on the left half!items [lo .. mid-1] gets best_left_cap --> solve smaller subproblem! items [mid .. hi-1] gets W - best_left_cap --> solve smaller subproblem!Crucial memory detail: compute
best_left_capinside its own helper function so Python freesleft_bestandright_bestbefore any recursive call starts. If you kept both arrays alive inside the recursive function acrosslog₂ nstack frames, memory would balloon toO(W log n)instead ofO(W):from typing import List def _find_best_capacity_split( weights: List[int], values: List[int], lo: int, mid: int, hi: int, capacity: int ) -> int: """Return how much capacity the left half [lo, mid) receives in an optimal split.""" left_best = _dp_1d_range(weights, values, lo, mid, capacity) right_best = _dp_1d_range(weights, values, mid, hi, capacity) best_left_cap = 0 best_combined = left_best[0] + right_best[capacity] for left_cap in range(1, capacity + 1): combined = left_best[left_cap] + right_best[capacity - left_cap] if combined > best_combined: best_combined = combined best_left_cap = left_cap # left_best and right_best are garbage-collected as soon as we return best_left_cap! return best_left_capRecurse down to single items and trace Example 1
Once
hi - lo == 1, only one itemloremains with budgetcapacity: we pickloif and only ifweights[lo] <= capacityandvalues[lo] > 0(ignoring zero-value items keeps the output minimal). Visiting the left half before the right half appends chosen indices in strictly increasing order:from typing import List, Tuple def _collect_optimal_items( weights: List[int], values: List[int], lo: int, hi: int, capacity: int, chosen: List[int], ) -> None: """Divide-and-conquer (Hirschberg's trick) to append optimal item indices from [lo, hi) in order.""" if hi - lo == 1: if weights[lo] <= capacity and values[lo] > 0: chosen.append(lo) return mid = (lo + hi) // 2 left_cap = _find_best_capacity_split(weights, values, lo, mid, hi, capacity) right_cap = capacity - left_cap _collect_optimal_items(weights, values, lo, mid, left_cap, chosen) _collect_optimal_items(weights, values, mid, hi, right_cap, chosen) def knapsack_01( weights: List[int], values: List[int], capacity: int ) -> Tuple[int, List[int]]: """0/1 knapsack: return (best_value, chosen item indices in increasing order).""" _validate_inputs(weights, values, capacity) chosen: List[int] = [] if len(weights) > 0: _collect_optimal_items(weights, values, 0, len(weights), capacity, chosen) total_value = 0 for item_idx in chosen: total_value += values[item_idx] return total_value, chosenTrace on Example 1 (
weights = [2, 4, 5, 6],values = [5, 8, 9, 10],W = 9):Root: items [0..4), capacity = 9 left_best (items 0,1): [0, 0, 5, 5, 8, 8, 13, 13, 13, 13] right_best (items 2,3): [0, 0, 0, 0, 0, 9, 10, 10, 10, 10] left_cap: 0 1 2 3 4 5 6 7 8 9 left[c] + right[9 - c]: 10 10 15 15 17 8 13 13 13 13 -> best_left_cap = 4! ├── Left child: items [0..2), capacity = 4 │ left_best (item 0): [0, 0, 5, 5, 5], right_best (item 1): [0, 0, 0, 0, 8] │ c = 0 gives 0 + 8 = 8 -> best_left_cap = 0 │ ├── item 0 with cap 0 -> w=2 > 0 -> skip │ └── item 1 with cap 4 -> w=4 <= 4, v=8 > 0 -> APPEND 1 └── Right child: items [2..4), capacity = 9 - 4 = 5 left_best (item 2): [0, 0, 0, 0, 0, 9], right_best (item 3): [0, 0, 0, 0, 0, 0] c = 5 gives 9 + 0 = 9 -> best_left_cap = 5 ├── item 2 with cap 5 -> w=5 <= 5, v=9 > 0 -> APPEND 2 └── item 3 with cap 0 -> w=6 > 0 -> skip Result: chosen = [1, 2], total_value = 8 + 9 = 17Why is total time still
O(nW)? At depth0, we do~nWinner-loop work. At depth1, the two children haven/2items each, and their capacities sum toleft_cap + (W − left_cap) = W, so their combined DP work is(n/2) × left_cap + (n/2) × (W − left_cap) = nW / 2! Across all depths, the work forms a geometric series:nW + nW/2 + nW/4 + nW/8 + ... < 2nWEven adding
O(n)outer-loop overhead per level acrosslog₂ nlevels givesO(nW + n log n)time — at most ~2× the work of value-only DP while keeping DP memory atO(W)!Adapt to unbounded knapsack: loop left-to-right with one parent array
In unbounded knapsack, every item can be taken
0, 1, 2, ...times (so every weight must be≥ 1, otherwise a weight-0 item with positive value could be taken infinitely). Now we wantbest_for_cap[cap - item_weight]to already contain copies ofitem_idx— which is achieved simply by flipping the inner capacity loop to left-to-right (range(item_weight, capacity + 1)).Unlike 0/1 knapsack, 1D walk-back works directly here! Why? Because after taking one copy of
item_idxat capacitycap, the remaining problem atcap - item_weightstill has access to the exact same unlimited item pool. Recordinglast_item_at_cap[cap] = item_idxwheneveritem_idximprovesbest_for_cap[cap]lets us peel off chosen items one by one fromcapacitydown untillast_item_at_cap[rem_cap] == -1:from typing import List, Tuple def unbounded_knapsack( weights: List[int], values: List[int], capacity: int ) -> Tuple[int, List[int]]: """Unbounded knapsack: return (best_value, counts) where each item may be used arbitrarily many times.""" _validate_inputs(weights, values, capacity) for item_weight in weights: if item_weight == 0: raise ValueError("unbounded knapsack needs every weight >= 1") best_for_cap = [0] * (capacity + 1) last_item_at_cap = [-1] * (capacity + 1) for item_idx in range(len(weights)): item_weight = weights[item_idx] item_value = values[item_idx] # Left-to-right allows reusing item_idx arbitrarily many times. for cap in range(item_weight, capacity + 1): candidate_value = best_for_cap[cap - item_weight] + item_value if candidate_value > best_for_cap[cap]: best_for_cap[cap] = candidate_value last_item_at_cap[cap] = item_idx counts = [0] * len(weights) rem_cap = capacity while last_item_at_cap[rem_cap] != -1: item_idx = last_item_at_cap[rem_cap] counts[item_idx] += 1 rem_cap -= weights[item_idx] return best_for_cap[capacity], countsOn Example 2 (
weights = [2, 3, 5],values = [5, 8, 12],W = 8):best_for_cap[8] = 21withlast_item_at_cap[8] = 1(rem_cap: 8 -> 5),last_item_at_cap[5] = 1(5 -> 2),last_item_at_cap[2] = 0(2 -> 0), andlast_item_at_cap[0] = -1(stop) — returning(21, [1, 2, 0])inO(nW)time andO(W + n)space.Adapt to bounded knapsack: binary bundle splitting
In bounded knapsack, item
ican be picked at mostk = limits[i]times. Turning itemiintokseparate 0/1 copies works, but takesO(W · Σ k_i)time — terrible ifk = 10,000.Instead, group the
kcopies into bundles of sizes1, 2, 4, 8, ...plus one final remainder bundle so the bundle sizes sum tok! Takek = 10: peeling off1, 2, 4leaves10 − 7 = 3 < 8, so the bundles are[1, 2, 4, 3]. Notice that 0/1 subsets of{1, 2, 4}already form every integer0..7, and adding the remainder bundle3shifts0..7to3..10— covering every count from0to10without ever exceeding10:bundles for limit = 10: [1, 2, 4, 3] (sum = 10, only 4 bundles instead of 10!) counts 0..7 : pick subsets of {1, 2, 4} (e.g. 5 = 1 + 4) counts 8..10: pick 3 + subset of {1, 2, 4} (e.g. 9 = 3 + 2 + 4, max = 1 + 2 + 4 + 3 = 10)Each item becomes
⌊log₂ k_i⌋ + 1synthetic 0/1 bundles, which we feed straight intoknapsack_01! On Example 3 (weights = [2, 3, 5],values = [5, 8, 12],limits = [3, 1, 2],W = 8), bundle copy counts are[1, 2]for item0,[1]for item1, and[1, 1]for item2, selecting item1(w=3, v=8) and one copy of item2(w=5, v=12) for(20, [0, 1, 1]). WithP = Σ (⌊log₂ k_i⌋ + 1)total bundles, runtime drops toO(P · W) = O(W · Σ log k_i)withO(W + P)memory.Complete Python solution
from typing import List, Tuple def _validate_inputs(weights: List[int], values: List[int], capacity: int) -> None: """Ensure weights, values, and capacity satisfy basic non-negativity and length rules.""" if len(weights) != len(values): raise ValueError("weights and values must have the same length") if capacity < 0: raise ValueError("capacity must be >= 0") for idx in range(len(weights)): if weights[idx] < 0 or values[idx] < 0: raise ValueError("weights and values must be >= 0") def _dp_1d_range( weights: List[int], values: List[int], lo: int, hi: int, capacity: int ) -> List[int]: """Compute 1D 0/1 knapsack DP over items in slice [lo, hi) up to capacity.""" # best_for_cap: length (capacity + 1) list; best_for_cap[cap] = max value using subset of items lo..hi-1 with weight <= cap best_for_cap = [0] * (capacity + 1) for item_idx in range(lo, hi): item_weight = weights[item_idx] item_value = values[item_idx] # Iterate capacity right-to-left so best_for_cap[cap - item_weight] still holds # the value from BEFORE item_idx was considered, preventing using item_idx twice. for cap in range(capacity, item_weight - 1, -1): candidate_value = best_for_cap[cap - item_weight] + item_value if candidate_value > best_for_cap[cap]: best_for_cap[cap] = candidate_value return best_for_cap def _find_best_capacity_split( weights: List[int], values: List[int], lo: int, mid: int, hi: int, capacity: int ) -> int: """Return how much capacity the left half [lo, mid) receives in an optimal split.""" # Run O(W)-space 1D DP independently on the left half [lo, mid) and right half [mid, hi). left_best = _dp_1d_range(weights, values, lo, mid, capacity) right_best = _dp_1d_range(weights, values, mid, hi, capacity) # Scan every possible capacity allocation (left_cap, capacity - left_cap) to maximize combined value. best_left_cap = 0 best_combined = left_best[0] + right_best[capacity] for left_cap in range(1, capacity + 1): combined = left_best[left_cap] + right_best[capacity - left_cap] if combined > best_combined: best_combined = combined best_left_cap = left_cap # Returning from this helper frees left_best and right_best BEFORE the caller recurses, # keeping peak DP working memory strictly O(capacity) instead of O(capacity * log n). return best_left_cap def _collect_optimal_items( weights: List[int], values: List[int], lo: int, hi: int, capacity: int, chosen: List[int], ) -> None: """Divide-and-conquer (Hirschberg's trick) to append optimal item indices from [lo, hi) in order.""" # Base case: a single item is worth taking iff it fits in remaining capacity and adds positive value. if hi - lo == 1: if weights[lo] <= capacity and values[lo] > 0: chosen.append(lo) return # Split the item range in half, find the optimal capacity split, and recurse left then right # so chosen indices are naturally appended in strictly increasing order. mid = (lo + hi) // 2 left_cap = _find_best_capacity_split(weights, values, lo, mid, hi, capacity) right_cap = capacity - left_cap _collect_optimal_items(weights, values, lo, mid, left_cap, chosen) _collect_optimal_items(weights, values, mid, hi, right_cap, chosen) def knapsack_01( weights: List[int], values: List[int], capacity: int ) -> Tuple[int, List[int]]: """0/1 knapsack: return (best_value, chosen item indices in increasing order).""" _validate_inputs(weights, values, capacity) # chosen: increasing list of selected item indices, e.g. [1, 2] chosen: List[int] = [] if len(weights) > 0: _collect_optimal_items(weights, values, 0, len(weights), capacity, chosen) total_value = 0 for item_idx in chosen: total_value += values[item_idx] return total_value, chosen def unbounded_knapsack( weights: List[int], values: List[int], capacity: int ) -> Tuple[int, List[int]]: """Unbounded knapsack: return (best_value, counts) where each item may be used arbitrarily many times.""" _validate_inputs(weights, values, capacity) # Reject weight-0 items: a zero-weight positive-value item could be repeated infinitely. for item_weight in weights: if item_weight == 0: raise ValueError("unbounded knapsack needs every weight >= 1") # best_for_cap[cap] = max value for capacity cap; last_item_at_cap[cap] = item index added last (-1 if none) best_for_cap = [0] * (capacity + 1) last_item_at_cap = [-1] * (capacity + 1) for item_idx in range(len(weights)): item_weight = weights[item_idx] item_value = values[item_idx] # Iterate capacity left-to-right so best_for_cap[cap - item_weight] CAN already # include earlier copies of item_idx, allowing unlimited reuse. for cap in range(item_weight, capacity + 1): candidate_value = best_for_cap[cap - item_weight] + item_value if candidate_value > best_for_cap[cap]: best_for_cap[cap] = candidate_value last_item_at_cap[cap] = item_idx # Walk parent pointers backward from capacity: valid in 1D because every capacity subproblem # shares the exact same unlimited pool of items. counts = [0] * len(weights) rem_cap = capacity while last_item_at_cap[rem_cap] != -1: item_idx = last_item_at_cap[rem_cap] counts[item_idx] += 1 rem_cap -= weights[item_idx] return best_for_cap[capacity], counts def bounded_knapsack( weights: List[int], values: List[int], limits: List[int], capacity: int ) -> Tuple[int, List[int]]: """Bounded knapsack via binary bundle splitting into 0/1 items: return (best_value, counts).""" _validate_inputs(weights, values, capacity) if len(limits) != len(weights): raise ValueError("limits must have one entry per item") # Parallel lists describing synthetic 0/1 bundles: e.g. limit=10 splits into copy counts [1, 2, 4, 3]. bundle_weights: List[int] = [] bundle_values: List[int] = [] bundle_owner: List[int] = [] bundle_copies: List[int] = [] for item_idx in range(len(weights)): if limits[item_idx] < 0: raise ValueError("limits must be >= 0") remaining_copies = limits[item_idx] power_of_two = 1 # Peel off powers of two (1, 2, 4, ...) and finish with min(power_of_two, remaining_copies) # so 0/1 subsets of bundles can form every integer in 0..limits[item_idx] and never exceed it. while remaining_copies > 0: copies_in_bundle = min(power_of_two, remaining_copies) bundle_weights.append(copies_in_bundle * weights[item_idx]) bundle_values.append(copies_in_bundle * values[item_idx]) bundle_owner.append(item_idx) bundle_copies.append(copies_in_bundle) remaining_copies -= copies_in_bundle power_of_two *= 2 best_value, chosen_bundles = knapsack_01(bundle_weights, bundle_values, capacity) # Sum chosen bundles back into per-item copy counts. counts = [0] * len(weights) for bundle_idx in chosen_bundles: original_item = bundle_owner[bundle_idx] counts[original_item] += bundle_copies[bundle_idx] return best_value, counts✅ Submit now — all tests should pass.
Intuition & how it works
Imagine packing a hiking backpack with a strict weight limit W, where every piece of gear has an integer weight and a usefulness score. Dynamic programming (DP) — solving a complex optimization problem by caching optimal answers to smaller capacity subproblems — lets us compute the maximum score using just a single 1D scratchpad best_for_cap[0..W], scanned right-to-left so no item gets packed twice. To recover which items were packed without storing all n historical rows, we use Hirschberg's divide-and-conquer: like finding the best cross-country driving route by first figuring out the optimal halfway transfer city, we split the items into a left half and right half, run the cheap 1D DP on each half to find how much weight budget belongs to the left half (left_cap) versus the right half (W − left_cap), discard both 1D arrays, and recurse on the two smaller halves.
Naive approaches break down quickly. Checking all 2ⁿ subsets takes exponential time (> 10¹² subsets at n = 40), while sorting greedily by value-per-weight leaves awkward unused capacity because whole 0/1 items cannot be sawed into fractions. Storing a textbook (n + 1) × (W + 1) 2D table makes backtracking trivial, but allocates O(nW) memory (10⁹ integers when n = 1,000 and W = 1,000,000), and trying to walk backward on a single overwritten 1D row fails because earlier cells already contain the very item you are checking.
Trace Example 1 (weights = [2, 4, 5, 6], values = [5, 8, 9, 10], W = 9):
- Split into left items
{0, 1}and right items{2, 3}. Right-to-left 1D DP producesleft_best = [0, 0, 5, 5, 8, 8, 13, 13, 13, 13]andright_best = [0, 0, 0, 0, 0, 9, 10, 10, 10, 10]. - Check every budget split
cfrom0to9:left_best[4] + right_best[9 − 4] = 8 + 9 = 17wins, soleft_cap = 4andright_cap = 5. Both arrays are freed immediately. - Recursing on
{0, 1}with capacity4selects item1(w=4, v=8), and recursing on{2, 3}with capacity5selects item2(w=5, v=9), returning(17, [1, 2])inO(nW)time andO(W)DP space.
Complexity
- Value-only 1D 0/1 DP (
_dp_1d_range) —O(nW)time,O(W)space: We loop over thenitems once and update at mostW + 1entries in a single list of lengthW + 1. knapsack_01with Hirschberg reconstruction —O(nW + n log n)time (which isO(nW)wheneverW ≥ log n),O(W)DP working space (O(W + n)total with output): At recursion depthd, the subproblems haven / 2^ditems each and their capacities sum toW, so DP cell updates across depthdtotal(n / 2^d) × W = nW / 2^d. SummingnW + nW/2 + nW/4 + ...across all⌈log₂ n⌉levels is strictly less than2nW, plusO(n)outer-loop work per level (n log₂ n). Because_find_best_capacity_splitreturns before recursion starts, only two arrays of length≤ W + 1exist at any moment (O(W)DP memory), alongsideO(log n)call-stack frames and up toO(n)output indices.unbounded_knapsack—O(nW)time,O(W + n)space: Each of thenitems scans capacitiesw..Wleft-to-right inO(W)steps, maintainingbest_for_capandlast_item_at_capof lengthW + 1. Walkinglast_item_at_capbackward subtracts≥ 1fromrem_capat each step, taking at mostWsteps, plusO(n)forcounts.bounded_knapsackvia binary splitting —O(W · Σ log k_i)time,O(W + Σ log k_i)space: Decomposing each limitk_iinto powers of two plus a remainder createsP = Σ (⌊log₂ k_i⌋ + 1)synthetic 0/1 bundles, then runsknapsack_01on thosePbundles instead ofΣ k_inaive copies.- Note on pseudo-polynomial time: A pseudo-polynomial algorithm runs in time polynomial in the numeric value of an input (
W) rather than the number of bits needed to writeW(≈ log₂ Wbits), which is whyO(nW)does not contradict 0/1 Knapsack being NP-hard.
Edge cases
- Empty item list (
n = 0) or zero capacity (W = 0): Returns(0, [])(or(0, [0, ...])for counts), except whenW = 0and an item in 0/1 or bounded knapsack hasweight = 0andvalue > 0, which legitimately fits in capacity0and is selected. - Zero-weight items in
unbounded_knapsack: Rejected withValueError, because an item withweight = 0andvalue > 0could be taken infinitely many times. - Items heavier than
capacity:range(capacity, item_weight - 1, -1)(andrange(item_weight, capacity + 1)) is empty wheneveritem_weight > capacity, so oversized items are safely skipped. - Zero-value items (
value == 0): The base caseif weights[lo] <= capacity and values[lo] > 0skips zero-value items so they never bloat the chosen set without increasing total value. - Multiple tied optimal subsets: Several subsets can achieve the exact same best value; tests should validate subset feasibility, distinct sorted indices, and summed value rather than hardcoding one arbitrary tie-break.
- Zero copy limit (
limits[i] == 0) inbounded_knapsack: Thewhile remaining_copies > 0loop generates zero bundles for itemi, leavingcounts[i] == 0.
Common mistakes
- Scanning capacity left-to-right in 0/1 knapsack: Updating low capacities before high capacities lets
best_for_cap[cap - w]already include the current item, silently solving unbounded knapsack instead of 0/1 knapsack. - Trying to backtrack on a single overwritten 1D array in 0/1 knapsack: Testing
best[cap] == best[cap - w] + von the final 1D row fails wheneverbest[cap - w]already used that item (for exampleweights=[2], values=[5], W=4yields[0, 0, 5, 5, 5], falsely skipping item0). - Claiming a
took[n][W]boolean matrix isO(W)space: Packing 64 booleans into an integer cuts constant memory usage by 64×, which is practical in production, but asymptoticallyn × W / 64is stillO(nW), notO(W). - Keeping
left_bestandright_bestin scope across recursive calls: Allocating both rows directly inside_collect_optimal_itemsholds2rows at depth0, plus1row at depth1, etc., inflating space toO(W log n)instead of isolating them inside_find_best_capacity_split. - Splitting bounded limits into pure powers of two without a remainder: Splitting
limit = 10into[1, 2, 4, 8]allows picking all four bundles (15 > 10copies!); the last bundle must bemin(power_of_two, remaining_copies) = 3, giving[1, 2, 4, 3].
Alternative approaches
- Full 2D DP table or bit-packed
took[n][W]table (O(nW)time,O(nW)space): Easiest code to write and fastest constant factor (~1× pass instead of ~1.8×) whenevern × Wfits comfortably in memory (e.g.,n × W ≤ 10⁷). - Value-indexed DP (
O(n · V)time, whereV = Σ values): Flip the state tomin_weight[val]= minimum weight needed to achieve exact valueval. Ideal whenWis huge (say10⁹) while item values are small (V ≤ 10⁵). - Meet-in-the-middle (
O(2^(n/2) · n)time): Whenn ≤ 40and both weights and values are huge (10¹²), enumerate all2^(n/2)subsets of each half, filter the right half to its Pareto front (keeping only subsets where no lighter-or-equal subset achieves a higher-or-equal value), and binary-search the best partner for each left subset. - Monotonic-queue bounded knapsack (
O(nW)time,O(W)space): Grouping capacities by residuecap mod wturns each item's bounded transition into a fixed-width sliding-window maximum maintained with a monotonic queue (a double-ended queue kept in decreasing order of adjusted values), removing thelog k_ifactor.
Follow-up questions
- Since 0/1 Knapsack is NP-hard, why doesn't an O(n * capacity) dynamic programming algorithm imply P = NP? In complexity theory, "polynomial time" means polynomial in the bit length of the input. Because the integer
Wtakes onlyB ≈ log₂ Wbits to write down in binary,W ≈ 2^B, soO(nW) = O(n · 2^B)actually grows exponentially in the number of input bitsB(adding one bit toWdoubles the runtime). - How would you adapt 0/1 Knapsack when capacity is 10^9, n = 100, and every item value is at most 100? Because
Wis10⁹, a capacity-indexed array of lengthW + 1is impossible, but the maximum possible total value is at mostV = 100 × 100 = 10,000. Definemin_weight[v]as the minimum weight required to achieve exact total valuev(initialized to0atv = 0and∞elsewhere), updatevright-to-left fromVdown tovalues[i], and return the largestvwithmin_weight[v] ≤ WinO(nV) ≈ 10⁶operations. - Under what problem rules does sorting items greedily by value-to-weight ratio guarantee an optimal result? Greedy by
value / weightis optimal for Fractional Knapsack, where you are allowed to take any continuous fraction0 ≤ f_i ≤ 1of an item (like scooping gold dust and silver dust). If any solution included a lower-ratio powder while leaving a higher-ratio powder behind, swapping an equal weight of the higher-ratio powder in strictly increases total value — an exchange argument proving greedy runs optimally inO(n log n)sorting time.
Follow-up questions
- Since 0/1 Knapsack is NP-hard, why doesn't an O(n * capacity) dynamic programming algorithm imply P = NP?
- How would you adapt 0/1 Knapsack when capacity is 10^9, n = 100, and every item value is at most 100?
- Under what problem rules does sorting items greedily by value-to-weight ratio guarantee an optimal result?
Similar questions
- End-to-End Deep Dive on a High-Impact Engineering Project
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One