Skip to the solution
MediumDSA10 min read

How do you solve the 0/1 knapsack problem?

1.1k views

The problem

Question presented to candidate: "You have n items, each with a weight and a value, and a bag that holds at most W. Each item can be taken at most once. What is the largest total value you can carry? Walk me through your approach and code it in Python."

What a strong answer should cover:

  • Why greedy (best value per weight first) fails for 0/1 items, with a counter-example.
  • The state dp[i][c] = best value from the first i items with capacity c, and the take-or-skip transition max(dp[i-1][c], dp[i-1][c-w] + v).
  • O(nยทW) time, pseudo-polynomial, and O(W) space with one row looped backwards โ€” and why forwards would reuse items (unbounded knapsack).
  • Rebuilding the chosen items by walking back through the full table.
  • Python details: dp[c - w] with c < w silently reads from the end of the list (negative indexing), so the loop bounds must stop at w; and a list comprehension for the 2D table.

Clarifying questions expected:

  • Can an item be used more than once, or split?
  • How large are W and n?
  • Do you need the chosen items or only the best value?

Code / implementation expected: Yes โ€” the one-row DP with a backwards capacity loop in Python; the 2D table if the items must be listed.

  • dp
  • knapsack

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

Python2D knapsack table, best value and the chosen items
Python1D backwards vs forwards, greedy, and brute force

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 44 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you solve the course schedule (prerequisites) problem?

Continue