KatInterview

0/1 Knapsack: Space-Efficient DP with Item Recovery

Dynamic ProgrammingModel answer
MediumModel answerDynamic Programmingdynamic-programmingknapsackreconstruction

Last 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

  1. 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.
  2. 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.

  3. 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 i may be picked at most k_i times.

    Give the time and space complexity for each variant.

Constraints

  • 1 ≤ n ≤ 1 000
  • 1 ≤ W ≤ 10 000
  • 1 ≤ weight[i] ≤ W
  • 0 ≤ 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.