Bird
Raised Fist0
DSA Javascriptprogramming

0 1 Knapsack Problem in DSA Javascript

Choose your learning style10 modes available
Mental Model
We want to pick items with values and weights to maximize value without exceeding weight limit. Each item can be chosen only once.
Analogy: Imagine packing a backpack for a trip. You have limited space and many items. You want to pack the most valuable things without overloading the bag.
Items: [weight, value]
[2, 3]  [3, 4]  [4, 5]  [5, 8]
Knapsack capacity: 5

Backpack capacity -> [0] [1] [2] [3] [4] [5]
Values stored here for best packing
Dry Run Walkthrough
Input: items: [(2,3), (3,4), (4,5), (5,8)], capacity: 5
Goal: Find max value we can carry without exceeding capacity 5
Step 1: Start with no items, all capacities have value 0
DP array: [0, 0, 0, 0, 0, 0]
Why: Base case: no items means no value
Step 2: Consider item 1 (weight 2, value 3), update DP for capacities ≥ 2
DP array: [0, 0, 3, 3, 3, 3]
Why: We can take item 1 if capacity allows, so value 3 for capacities 2 to 5
Step 3: Consider item 2 (weight 3, value 4), update DP for capacities ≥ 3
DP array: [0, 0, 3, 4, 4, 7]
Why: At capacity 5, taking item 2 plus item 1 (capacity 2 left) gives 7
Step 4: Consider item 3 (weight 4, value 5), update DP for capacities ≥ 4
DP array: [0, 0, 3, 4, 5, 7]
Why: At capacity 4, item 3 alone is better than previous 4; at 5, previous 7 remains best
Step 5: Consider item 4 (weight 5, value 8), update DP for capacity 5
DP array: [0, 0, 3, 4, 5, 8]
Why: At capacity 5, item 4 alone (value 8) beats previous 7
Result:
DP array final: [0, 0, 3, 4, 5, 8]
Max value = 8
Annotated Code
DSA Javascript
class Knapsack {
  constructor(items, capacity) {
    this.items = items; // array of [weight, value]
    this.capacity = capacity;
  }

  solve() {
    const dp = Array(this.capacity + 1).fill(0);
    // Iterate over each item
    for (const [weight, value] of this.items) {
      // Traverse capacities backwards to avoid reuse of same item
      for (let cap = this.capacity; cap >= weight; cap--) {
        // Update dp[cap] if taking this item is better
        dp[cap] = Math.max(dp[cap], dp[cap - weight] + value);
      }
    }
    return dp[this.capacity];
  }
}

// Driver code
const items = [[2, 3], [3, 4], [4, 5], [5, 8]];
const capacity = 5;
const knapsack = new Knapsack(items, capacity);
console.log(knapsack.solve());
for (const [weight, value] of this.items) {
iterate over each item to consider including it
for (let cap = this.capacity; cap >= weight; cap--) {
iterate capacities backward to avoid reusing the same item multiple times
dp[cap] = Math.max(dp[cap], dp[cap - weight] + value);
update dp for capacity cap by choosing max between skipping or taking current item
OutputSuccess
8
Complexity Analysis
Time: O(n * W) because we process each of the n items for each capacity up to W
Space: O(W) because we use a one-dimensional array of size capacity+1
vs Alternative: Naive recursive approach has exponential time; DP reduces it to polynomial time
Edge Cases
empty items list
returns 0 because no items to pick
DSA Javascript
for (const [weight, value] of this.items) {
capacity zero
returns 0 because no capacity to hold items
DSA Javascript
const dp = Array(this.capacity + 1).fill(0);
items heavier than capacity
items are skipped, dp remains 0 for those capacities
DSA Javascript
for (let cap = this.capacity; cap >= weight; cap--) {
When to Use This Pattern
When you need to maximize value with limited capacity and each item can be chosen once, use 0 1 Knapsack dynamic programming to efficiently find the best combination.
Common Mistakes
Mistake: Iterating capacities forward causing reuse of the same item multiple times
Fix: Iterate capacities backward to ensure each item is only counted once
Mistake: Not initializing dp array properly leading to incorrect base values
Fix: Initialize dp array with zeros to represent no items chosen
Summary
Find the maximum value of items that fit in a knapsack without exceeding capacity, choosing each item at most once.
Use when you have a set of items with weights and values and a limited capacity to maximize total value.
The key is to build solutions for smaller capacities and items, updating best values without reusing items.

Practice

(1/5)
1. What does the 0 1 Knapsack Problem aim to maximize given a set of items with weights and values?
easy
A. The total value of items without exceeding the weight limit
B. The total weight of items without exceeding the value limit
C. The number of items selected regardless of weight
D. The minimum weight of items selected

Solution

  1. Step 1: Understand the problem goal

    The 0 1 Knapsack Problem tries to select items to maximize total value without exceeding the weight capacity.
  2. Step 2: Identify the constraint

    The total weight of selected items must not exceed the knapsack's weight limit.
  3. Final Answer:

    The total value of items without exceeding the weight limit -> Option A
  4. Quick Check:

    Maximize value with weight limit = B [OK]
Hint: Remember: maximize value, not weight or count [OK]
Common Mistakes:
  • Confusing weight limit with value limit
  • Thinking the problem maximizes number of items
  • Ignoring the weight constraint
2. Which of the following is the correct way to initialize the DP array for the 0 1 Knapsack Problem in JavaScript?
easy
A. const dp = new Array(n + 1).fill(new Array(W + 1).fill(0));
B. const dp = Array(n + 1).fill(Array(W + 1).fill(0));
C. const dp = Array.from({ length: n + 1 }, () => Array(W + 1).fill(0));
D. const dp = Array(n).fill(Array(W).fill(0));

Solution

  1. Step 1: Understand DP array initialization

    We need a 2D array where each row is a separate array to avoid reference issues.
  2. Step 2: Choose correct initialization

    Using Array.from with a function creates independent inner arrays, preventing shared references.
  3. Final Answer:

    const dp = Array.from({ length: n + 1 }, () => Array(W + 1).fill(0)); -> Option C
  4. Quick Check:

    Independent inner arrays = A [OK]
Hint: Use Array.from with function to avoid shared references [OK]
Common Mistakes:
  • Using fill with array directly causing shared references
  • Initializing with wrong dimensions
  • Forgetting to fill inner arrays
3. What is the output of the following code snippet for weights = [1, 3, 4], values = [15, 50, 60], and W = 5?
function knapsack(weights, values, W) {
  const n = weights.length;
  const dp = Array.from({ length: n + 1 }, () => Array(W + 1).fill(0));
  for (let i = 1; i <= n; i++) {
    for (let w = 1; w <= W; w++) {
      if (weights[i - 1] <= w) {
        dp[i][w] = Math.max(dp[i - 1][w], dp[i - 1][w - weights[i - 1]] + values[i - 1]);
      } else {
        dp[i][w] = dp[i - 1][w];
      }
    }
  }
  return dp[n][W];
}

console.log(knapsack([1, 3, 4], [15, 50, 60], 5));
medium
A. 65
B. 80
C. 60
D. 75

Solution

  1. Step 1: Trace DP table filling

    Check items one by one and weights up to 5:
    - Item 1 (weight 1, value 15): dp[1][1..5] = 15
    - Item 2 (weight 3, value 50): dp[2][3] = max(15, 0+50)=50, dp[2][4]=max(15,15+50)=65, dp[2][5]=max(15,15+50)=65
    - Item 3 (weight 4, value 60): dp[3][4]=max(65,0+60)=65, dp[3][5]=max(65,15+60)=75
  2. Step 2: Find final answer

    The maximum value for weight 5 is dp[3][5] = 75.
  3. Final Answer:

    75 -> Option D
  4. Quick Check:

    Max value at W=5 = 75 [OK]
Hint: Trace DP table row by row for each item [OK]
Common Mistakes:
  • Adding values without checking weight limit
  • Confusing indices in dp array
  • Forgetting to compare including vs excluding item
4. Identify the bug in this 0 1 Knapsack implementation and select the fix:
function knapsack(weights, values, W) {
  const n = weights.length;
  const dp = Array.from({ length: n + 1 }, () => Array(W + 1).fill(0));
  for (let i = 1; i <= n; i++) {
    for (let w = 1; w <= W; w++) {
      if (weights[i] <= w) {
        dp[i][w] = Math.max(dp[i - 1][w], dp[i - 1][w - weights[i]] + values[i]);
      } else {
        dp[i][w] = dp[i - 1][w];
      }
    }
  }
  return dp[n][W];
}
medium
A. Change weights[i] and values[i] to weights[i - 1] and values[i - 1]
B. Change loop to start i from 0 instead of 1
C. Initialize dp with zeros using fill(1)
D. Change inner loop to run from w = 0 to W - 1

Solution

  1. Step 1: Identify index error in array access

    Arrays in JavaScript are zero-indexed, but loop starts at 1, so weights[i] accesses out-of-bound or wrong element.
  2. Step 2: Correct index usage

    Use weights[i - 1] and values[i - 1] to access correct item corresponding to dp row i.
  3. Final Answer:

    Change weights[i] and values[i] to weights[i - 1] and values[i - 1] -> Option A
  4. Quick Check:

    Fix index offset = D [OK]
Hint: Remember dp row i corresponds to item i-1 [OK]
Common Mistakes:
  • Using wrong indices causing undefined values
  • Changing loop start incorrectly
  • Incorrect dp initialization
5. Given items with weights = [2, 3, 5, 7], values = [10, 5, 15, 7], and knapsack capacity W = 10, which set of items maximizes value without exceeding weight? Select the correct maximum value.
Note: You can only take each item once.
hard
A. 25
B. 30
C. 27
D. 22

Solution

  1. Step 1: Consider all item combinations within weight limit 10

    Possible combinations:
    - Items 1,2,3: weights 2+3+5=10, values 10+5+15=30 (exceeds capacity? No, equals 10)
    - Items 1,3,4: weights 2+5+7=14 (exceeds 10)
    - Items 2,3,4: weights 3+5+7=15 (exceeds 10)
    - Items 1,4: weights 2+7=9, values 10+7=17
    - Items 3 alone: weight 5, value 15
    - Items 1,2,4: weights 2+3+7=12 (exceeds 10)
  2. Step 2: Find max value without exceeding weight

    Best valid combination is items 1,2,3 with total weight 10 and value 30. But since weight is exactly 10, it's valid.
    Check if any other combination gives more value:
    Items 1,3: weight 7, value 25
    Items 3,4: weight 12 (exceeds)
    So max value is 30.
  3. Final Answer:

    30 -> Option B
  4. Quick Check:

    Max value with W=10 = 30 [OK]
Hint: Try all combos within weight limit to find max value [OK]
Common Mistakes:
  • Ignoring exact weight limit equality
  • Adding values of items exceeding capacity
  • Missing best combination
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard