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:

  1. knapsack_01(weights, values, capacity) -> Tuple[int, List[int]] Each item may be chosen at most once (0 or 1 time). Return (best_value, chosen), where chosen is one optimal list of distinct item indices in strictly increasing order whose combined weight is at most capacity and whose values sum to best_value (omit zero-value items that add nothing to best_value). Your implementation must run in O(n * capacity) time using O(capacity) dynamic-programming working memory, reconstructing chosen without storing an O(n * capacity) state table.

  2. 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 every weights[i] must be at least 1. Return (best_value, counts), where counts has length n and counts[i] gives how many copies of item i are taken.

  3. bounded_knapsack(weights, values, limits, capacity) -> Tuple[int, List[int]] Item i may be chosen at most limits[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 (and len(limits) == len(weights) for bounded_knapsack)
  • 0 <= capacity <= 10^4
  • 0 <= weights[i], values[i], limits[i] <= 10^4 (and weights[i] >= 1 for unbounded_knapsack)
  • Invalid inputs must raise ValueError.
  • knapsack_01 must run in O(n * capacity) time (plus O(n log n) divide-and-conquer overhead when capacity == 0) with O(capacity) DP working space (O(capacity + n) total including call stack and output indices).

Step-by-step walkthrough

  1. Restate the problem and input/output contract

    Given n items with non-negative integer weights and values plus an integer limit capacity (W ≥ 0), we want to solve 0/1 Knapsack — selecting each item at most once so total weight stays ≤ W and total value is maximized — returning both the optimal value and one optimal list of sorted item indices in O(nW) time and O(W) working DP memory. We then extend the solver to unbounded knapsack (unlimited copies per item) and bounded knapsack (at most limits[i] copies of item i).

    Notice on Example 1 (weights = [2, 4, 5, 6], values = [5, 8, 9, 10], W = 9) why sorting items greedily by value / weight fails 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 17
    

    We 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] (weights 4 + 5 = 9, value 8 + 9 = 17).

  2. Compress the 2D DP table into one O(W) row

    Trying all 2ⁿ subsets is already > 10¹² checks at n = 40. Dynamic programming (DP) instead builds a table dp[i][cap] = maximum value achievable using a subset of the first i items within weight limit cap:

    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 at n = 1,000 and W = 1,000,000 that is 10⁹ integers — gigabytes of RAM. Because row i only ever reads row i − 1, we can overwrite a single 1D list best_for_cap of length W + 1 in place, as long as we scan cap from 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_cap
    

    Row 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 = 17
    
  3. Why 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 item 0, the naive check falsely concludes item 0 was skipped and returns [] even though the optimal value is 5.

    Storing a boolean took[n][W + 1] table fixes walk-back, and shrinks memory by ~64× if bit-packed, but n × (W + 1) bits is still O(nW) space, violating the strict O(W) space requirement. To reconstruct in true O(W) working memory, we recompute smartly instead of storing n rows.

  4. 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-1 at midpoint mid = (lo + hi) // 2 into a left half [lo, mid) and a right half [mid, hi).

    Any optimal subset S naturally partitions into left-half items S_left and right-half items S_right whose weights sum to at most W. If the left half gets left_cap units of capacity, the right half gets W − left_cap units. 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_cap from 0 to W to maximize left_best[left_cap] + right_best[W − left_cap] tells us the exact capacity budget best_left_cap that 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_cap inside its own helper function so Python frees left_best and right_best before any recursive call starts. If you kept both arrays alive inside the recursive function across log₂ n stack frames, memory would balloon to O(W log n) instead of O(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_cap
    
  5. Recurse down to single items and trace Example 1

    Once hi - lo == 1, only one item lo remains with budget capacity: we pick lo if and only if weights[lo] <= capacity and values[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, chosen
    

    Trace 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 = 17
    

    Why is total time still O(nW)? At depth 0, we do ~nW inner-loop work. At depth 1, the two children have n/2 items each, and their capacities sum to left_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 + ... < 2nW
    

    Even adding O(n) outer-loop overhead per level across log₂ n levels gives O(nW + n log n) time — at most ~2× the work of value-only DP while keeping DP memory at O(W)!

  6. 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 want best_for_cap[cap - item_weight] to already contain copies of item_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_idx at capacity cap, the remaining problem at cap - item_weight still has access to the exact same unlimited item pool. Recording last_item_at_cap[cap] = item_idx whenever item_idx improves best_for_cap[cap] lets us peel off chosen items one by one from capacity down until last_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], counts
    

    On Example 2 (weights = [2, 3, 5], values = [5, 8, 12], W = 8): best_for_cap[8] = 21 with last_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), and last_item_at_cap[0] = -1 (stop) — returning (21, [1, 2, 0]) in O(nW) time and O(W + n) space.

  7. Adapt to bounded knapsack: binary bundle splitting

    In bounded knapsack, item i can be picked at most k = limits[i] times. Turning item i into k separate 0/1 copies works, but takes O(W · Σ k_i) time — terrible if k = 10,000.

    Instead, group the k copies into bundles of sizes 1, 2, 4, 8, ... plus one final remainder bundle so the bundle sizes sum to k! Take k = 10: peeling off 1, 2, 4 leaves 10 − 7 = 3 < 8, so the bundles are [1, 2, 4, 3]. Notice that 0/1 subsets of {1, 2, 4} already form every integer 0..7, and adding the remainder bundle 3 shifts 0..7 to 3..10 — covering every count from 0 to 10 without ever exceeding 10:

    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⌋ + 1 synthetic 0/1 bundles, which we feed straight into knapsack_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 item 0, [1] for item 1, and [1, 1] for item 2, selecting item 1 (w=3, v=8) and one copy of item 2 (w=5, v=12) for (20, [0, 1, 1]). With P = Σ (⌊log₂ k_i⌋ + 1) total bundles, runtime drops to O(P · W) = O(W · Σ log k_i) with O(W + P) memory.

  8. 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):

  1. Split into left items {0, 1} and right items {2, 3}. Right-to-left 1D DP produces left_best = [0, 0, 5, 5, 8, 8, 13, 13, 13, 13] and right_best = [0, 0, 0, 0, 0, 9, 10, 10, 10, 10].
  2. Check every budget split c from 0 to 9: left_best[4] + right_best[9 − 4] = 8 + 9 = 17 wins, so left_cap = 4 and right_cap = 5. Both arrays are freed immediately.
  3. Recursing on {0, 1} with capacity 4 selects item 1 (w=4, v=8), and recursing on {2, 3} with capacity 5 selects item 2 (w=5, v=9), returning (17, [1, 2]) in O(nW) time and O(W) DP space.

Complexity

  • Value-only 1D 0/1 DP (_dp_1d_range) — O(nW) time, O(W) space: We loop over the n items once and update at most W + 1 entries in a single list of length W + 1.
  • knapsack_01 with Hirschberg reconstruction — O(nW + n log n) time (which is O(nW) whenever W ≥ log n), O(W) DP working space (O(W + n) total with output): At recursion depth d, the subproblems have n / 2^d items each and their capacities sum to W, so DP cell updates across depth d total (n / 2^d) × W = nW / 2^d. Summing nW + nW/2 + nW/4 + ... across all ⌈log₂ n⌉ levels is strictly less than 2nW, plus O(n) outer-loop work per level (n log₂ n). Because _find_best_capacity_split returns before recursion starts, only two arrays of length ≤ W + 1 exist at any moment (O(W) DP memory), alongside O(log n) call-stack frames and up to O(n) output indices.
  • unbounded_knapsack — O(nW) time, O(W + n) space: Each of the n items scans capacities w..W left-to-right in O(W) steps, maintaining best_for_cap and last_item_at_cap of length W + 1. Walking last_item_at_cap backward subtracts ≥ 1 from rem_cap at each step, taking at most W steps, plus O(n) for counts.
  • bounded_knapsack via binary splitting — O(W · Σ log k_i) time, O(W + Σ log k_i) space: Decomposing each limit k_i into powers of two plus a remainder creates P = Σ (⌊log₂ k_i⌋ + 1) synthetic 0/1 bundles, then runs knapsack_01 on those P bundles instead of Σ k_i naive 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 write W (≈ log₂ W bits), which is why O(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 when W = 0 and an item in 0/1 or bounded knapsack has weight = 0 and value > 0, which legitimately fits in capacity 0 and is selected.
  • Zero-weight items in unbounded_knapsack: Rejected with ValueError, because an item with weight = 0 and value > 0 could be taken infinitely many times.
  • Items heavier than capacity: range(capacity, item_weight - 1, -1) (and range(item_weight, capacity + 1)) is empty whenever item_weight > capacity, so oversized items are safely skipped.
  • Zero-value items (value == 0): The base case if weights[lo] <= capacity and values[lo] > 0 skips 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) in bounded_knapsack: The while remaining_copies > 0 loop generates zero bundles for item i, leaving counts[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] + v on the final 1D row fails whenever best[cap - w] already used that item (for example weights=[2], values=[5], W=4 yields [0, 0, 5, 5, 5], falsely skipping item 0).
  • Claiming a took[n][W] boolean matrix is O(W) space: Packing 64 booleans into an integer cuts constant memory usage by 64×, which is practical in production, but asymptotically n × W / 64 is still O(nW), not O(W).
  • Keeping left_best and right_best in scope across recursive calls: Allocating both rows directly inside _collect_optimal_items holds 2 rows at depth 0, plus 1 row at depth 1, etc., inflating space to O(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 = 10 into [1, 2, 4, 8] allows picking all four bundles (15 > 10 copies!); the last bundle must be min(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×) whenever n × W fits comfortably in memory (e.g., n × W ≤ 10⁷).
  • Value-indexed DP (O(n · V) time, where V = Σ values): Flip the state to min_weight[val] = minimum weight needed to achieve exact value val. Ideal when W is huge (say 10⁹) while item values are small (V ≤ 10⁵).
  • Meet-in-the-middle (O(2^(n/2) · n) time): When n ≤ 40 and both weights and values are huge (10¹²), enumerate all 2^(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 residue cap mod w turns 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 the log k_i factor.

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 W takes only B ≈ log₂ W bits to write down in binary, W ≈ 2^B, so O(nW) = O(n · 2^B) actually grows exponentially in the number of input bits B (adding one bit to W doubles 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 W is 10⁹, a capacity-indexed array of length W + 1 is impossible, but the maximum possible total value is at most V = 100 × 100 = 10,000. Define min_weight[v] as the minimum weight required to achieve exact total value v (initialized to 0 at v = 0 and ∞ elsewhere), update v right-to-left from V down to values[i], and return the largest v with min_weight[v] ≤ W in O(nV) ≈ 10⁶ operations.
  • Under what problem rules does sorting items greedily by value-to-weight ratio guarantee an optimal result? Greedy by value / weight is optimal for Fractional Knapsack, where you are allowed to take any continuous fraction 0 ≤ f_i ≤ 1 of 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 in O(n log n) sorting time.

Follow-up questions

Similar questions

More BitGo interview questions

All 2 BitGo questions →