DSA
    advanced

    0/1 Knapsack Problem

    Software Engineer path · lesson 35 of 99
    time O(nW)
    space O(nW)

    Up to 5 items; weights 1–10, values 0–30. Greedy trap: best value-per-weight first loses.

    Try:
    Capacity W
    01234567—1: 1/12: 3/43: 4/54: 5/700000000
    FillingRead (skip / take)Item takenItem skipped

    Row 0: with no items, every capacity is worth 0.

    Code (running line highlighted)
    1. 1dp[0][c] = 0 for every capacity c
    2. 2for i in 1..n, for c in 0..W:
    3. 3 skip = dp[i-1][c]
    4. 4 take = dp[i-1][c - w_i] + v_i (only if w_i <= c)
    5. 5 dp[i][c] = max(skip, take)
    6. 6walk back from dp[n][W]: a changed row means item i was taken
    Cells filled
    0 / 32
    Take wins
    0 / 17
    Invariant: dp[i][c] = best value using the first i items with capacity c.

    Tap any element in the diagram to inspect its state at this step.

    1 / 38

    Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.

    Fill the knapsack table

    Sequence

    Order the steps of the 0/1 knapsack DP.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    5. 5Drop a step here
    5 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    What does dp[i][w] represent?

    The short version

    Think of a thief robbing a store with a small backpack. He can't take everything. He must choose a combination of items that fits in the bag but has the highest total resale value.

    In more depth

    The Choice Diagram

    The Knapsack problem represents the classic Constraint Optimization pattern. For every item, you have a choice:

    1.Include it: Add its value, subtract its weight from capacity.
    2.Exclude it: Skip it, keep capacity same.

    We take the maximum of these two choices.

    0/1 vs Unbounded:

    0/1: Can use each item only once.
    Unbounded: Can use each item infinite times (like Coin Change).

    When to reach for this

    • Maximize value given a capacity constraint
    • Find if a subset sums to a Detailed Target
    • Min/Max number of ways to reach a target using elements

    Interview Questions

    Amazon
    Google
    Microsoft
    Facebook
    LinkedIn
    Facebook
    Amazon
    Uber
    Google
    Airbnb
    Palantir

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required