Bird
Raised Fist0
DSA Typescriptprogramming

0 1 Knapsack Problem in DSA Typescript

Choose your learning style10 modes available
Mental Model
We want to pick items with weights and values to maximize value without exceeding a weight limit. Each item can be chosen only once.
Analogy: Imagine packing a backpack for a trip. You have limited space (weight limit) and many items with different usefulness (value). You want to pack the most useful combination without overloading.
Backpack capacity: 5
Items:
[Item1: weight=2, value=3]
[Item2: weight=3, value=4]
[Item3: weight=4, value=5]

Backpack (capacity slots): [ ] [ ] [ ] [ ] [ ]
We try to fill these slots with items without exceeding capacity.
Dry Run Walkthrough
Input: items: [(weight=2, value=3), (weight=3, value=4), (weight=4, value=5)], capacity=5
Goal: Find the maximum total value of items that fit in the backpack without exceeding capacity 5
Step 1: Start with no items, capacity 0 to 5, all values 0
DP table rows: items 0 to 3, columns: capacity 0 to 5
Row 0 (no items): 0 0 0 0 0 0
Why: Base case: no items means no value regardless of capacity
Step 2: Consider item 1 (weight=2, value=3), update DP for capacities 0 to 5
Row 1:
Capacity 0,1: 0 (item too heavy)
Capacity 2-5: max of not taking or taking item 1
Values: 0 0 3 3 3 3
Why: If capacity >= 2, we can take item 1 and get value 3
Step 3: Consider item 2 (weight=3, value=4), update DP for capacities 0 to 5
Row 2:
Capacity 0-2: same as row 1
Capacity 3: max(3,4)=4
Capacity 4: max(3,4)=4
Capacity 5: max(3,3+4)=7
Why: At capacity 5, taking item 2 plus item 1 (capacity 2) gives value 7
Step 4: Consider item 3 (weight=4, value=5), update DP for capacities 0 to 5
Row 3:
Capacity 0-3: same as row 2
Capacity 4: max(4,5)=5
Capacity 5: max(7,5)=7
Why: At capacity 5, best is still 7 from previous items
Result:
DP table last row: 0 0 3 4 5 7
Maximum value achievable: 7
Annotated Code
DSA Typescript
class Item {
  constructor(public weight: number, public value: number) {}
}

function knapsack01(items: Item[], capacity: number): number {
  const n = items.length;
  const dp: number[][] = Array.from({ length: n + 1 }, () => Array(capacity + 1).fill(0));

  for (let i = 1; i <= n; i++) {
    const { weight, value } = items[i - 1];
    for (let w = 0; w <= capacity; w++) {
      if (weight > w) {
        dp[i][w] = dp[i - 1][w]; // can't take item i
      } else {
        dp[i][w] = Math.max(dp[i - 1][w], dp[i - 1][w - weight] + value); // max of taking or not
      }
    }
  }

  return dp[n][capacity];
}

// Driver code
const items = [new Item(2, 3), new Item(3, 4), new Item(4, 5)];
const capacity = 5;
const maxValue = knapsack01(items, capacity);
console.log(maxValue);
for (let i = 1; i <= n; i++) {
iterate over items to build DP table row by row
for (let w = 0; w <= capacity; w++) {
iterate over all capacities from 0 to max capacity
if (weight > w) { dp[i][w] = dp[i - 1][w]; }
if item weight exceeds current capacity, skip item
else { dp[i][w] = Math.max(dp[i - 1][w], dp[i - 1][w - weight] + value); }
choose max value between skipping or taking the item
OutputSuccess
7
Complexity Analysis
Time: O(n * capacity) because we fill a table with n items and capacity columns
Space: O(n * capacity) because we store results for each item and capacity combination
vs Alternative: Compared to brute force exponential approach, DP reduces time drastically by storing intermediate results
Edge Cases
empty items list
returns 0 as no items to choose
DSA Typescript
const n = items.length;
capacity zero
returns 0 as no capacity to carry items
DSA Typescript
for (let w = 0; w <= capacity; w++) {
items heavier than capacity
items skipped, result 0 if none fit
DSA Typescript
if (weight > w) { dp[i][w] = dp[i - 1][w]; }
When to Use This Pattern
When you need to pick items with weights and values to maximize value without exceeding a limit, use 0 1 Knapsack DP to efficiently find the best combination.
Common Mistakes
Mistake: Not checking if item weight fits current capacity before taking it
Fix: Add condition to skip item if weight > current capacity
Mistake: Using 1D array without careful update order causing incorrect results
Fix: Use 2D DP or update 1D array backwards to avoid overwriting needed values
Summary
Finds the max value of items fitting in a capacity-limited knapsack with each item chosen once.
Use when selecting items with weights and values to maximize total value without exceeding capacity.
The key is building a table of best values for each item and capacity step by step.

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 minimum weight of items selected
B. The total weight of items without exceeding the value limit
C. The number of items selected regardless of weight
D. The total value of items without exceeding the weight limit

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 constraint is the maximum weight the knapsack can carry, so total weight must not exceed this limit.
  3. Final Answer:

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

    Maximize value under weight limit = The total value of items without exceeding the weight limit [OK]
Hint: Maximize value, not weight, under capacity limit [OK]
Common Mistakes:
  • Confusing weight limit with value limit
  • Trying to maximize weight instead of value
  • Ignoring the weight constraint
2. Which of the following TypeScript function signatures correctly represents the 0 1 Knapsack function?
easy
A. function knapsack(weights: number[], values: number[], capacity: number): number
B. function knapsack(weights: number, values: number, capacity: number[]): number[]
C. function knapsack(weights: string[], values: string[], capacity: string): string
D. function knapsack(weights: number[], values: number[], capacity: string): void

Solution

  1. Step 1: Check parameter types

    Weights and values should be arrays of numbers, capacity a number, and return type a number representing max value.
  2. Step 2: Match correct signature

    function knapsack(weights: number[], values: number[], capacity: number): number matches this: arrays for weights and values, number for capacity, returns number.
  3. Final Answer:

    function knapsack(weights: number[], values: number[], capacity: number): number -> Option A
  4. Quick Check:

    Correct types and return = function knapsack(weights: number[], values: number[], capacity: number): number [OK]
Hint: Weights and values are number arrays; capacity is a number [OK]
Common Mistakes:
  • Using string types instead of number
  • Swapping array and single number types
  • Incorrect return type
3. What is the output of the following TypeScript code snippet for 0 1 Knapsack?
const weights = [1, 3, 4];
const values = [15, 50, 60];
const capacity = 5;

function knapsack(w: number[], v: number[], c: number): number {
  const n = w.length;
  const dp = Array(n + 1).fill(null).map(() => Array(c + 1).fill(0));
  for (let i = 1; i <= n; i++) {
    for (let j = 1; j <= c; j++) {
      if (w[i - 1] <= j) {
        dp[i][j] = Math.max(dp[i - 1][j], v[i - 1] + dp[i - 1][j - w[i - 1]]);
      } else {
        dp[i][j] = dp[i - 1][j];
      }
    }
  }
  return dp[n][c];
}

console.log(knapsack(weights, values, capacity));
medium
A. 65
B. 60
C. 75
D. 50

Solution

  1. Step 1: Understand DP table filling

    For capacity 5, items: (1,15), (3,50), (4,60). Check combinations: - Item1 + Item2: weight 4, value 65 - Item3 alone: weight 4, value 60 - Item2 alone: weight 3, value 50 - Item1 + Item3: weight 5, value 75
  2. Step 2: Find max value under capacity

    Item1 + Item3 total weight 5, value 75 is max possible under capacity 5.
  3. Final Answer:

    75 -> Option C
  4. Quick Check:

    Max value with capacity 5 = 75 [OK]
Hint: Check all item combos fitting capacity, pick max value [OK]
Common Mistakes:
  • Ignoring combined items
  • Choosing single highest value item only
  • Miscomputing weights or values
4. Identify the bug in this 0 1 Knapsack TypeScript function and select the fix:
function knapsack(weights: number[], values: number[], capacity: number): number {
  const n = weights.length;
  const dp = Array(n + 1).fill([]).map(() => Array(capacity + 1).fill(0));
  for (let i = 1; i <= n; i++) {
    for (let w = 1; w <= capacity; w++) {
      if (weights[i - 1] <= w) {
        dp[i][w] = Math.max(dp[i - 1][w], values[i - 1] + dp[i - 1][w - weights[i - 1]]);
      } else {
        dp[i][w] = dp[i - 1][w];
      }
    }
  }
  return dp[n][capacity];
}
medium
A. Change Array(n + 1).fill([]) to Array(n + 1).fill(null)
B. Change Array(n + 1).fill([]) to Array(n + 1).fill([]).map(() => Array(capacity + 1).fill(0))
C. No bug, code is correct
D. Change Array(n + 1).fill([]) to Array(n + 1).fill(0)

Solution

  1. Step 1: Examine the dp array initialization

    The code uses Array(n + 1).fill([]).map(() => Array(capacity + 1).fill(0)), but fill([]) fills all elements with the same array reference, which is then overridden by map creating new arrays. However, the initial fill([]) is unnecessary and can cause confusion or bugs if map is removed.
  2. Step 2: Correct initialization

    Better to initialize dp as Array(n + 1).fill(null).map(() => Array(capacity + 1).fill(0)) or directly with map to ensure independent arrays without shared references.
  3. Final Answer:

    Change Array(n + 1).fill([]) to Array(n + 1).fill([]).map(() => Array(capacity + 1).fill(0)) -> Option B
  4. Quick Check:

    Ensure dp rows are independent arrays to avoid shared reference bugs [OK]
Hint: Use map to create independent arrays for dp rows [OK]
Common Mistakes:
  • Assuming fill([]) creates independent arrays
  • Ignoring shared reference issues
  • Claiming no bug when shared references exist
5. Given items with weights [2, 3, 5, 7] and values [10, 5, 15, 7], and a knapsack capacity of 10, which set of items maximizes value without exceeding capacity?
hard
A. Items with weights 2, 3, and 5 (total value 30)
B. Items with weights 3 and 7 (total value 12)
C. Items with weights 5 and 7 (total value 22)
D. Items with weights 2 and 7 (total value 17)

Solution

  1. Step 1: Calculate total weights and values for each option

    Items with weights 2, 3, and 5 (total value 30): weights 2+3+5=10, values 10+5+15=30 Items with weights 3 and 7 (total value 12): weights 3+7=10, values 5+7=12 Items with weights 5 and 7 (total value 22): weights 5+7=12 (exceeds capacity) Items with weights 2 and 7 (total value 17): weights 2+7=9, values 10+7=17
  2. Step 2: Choose max value under capacity

    Items with weights 2, 3, and 5 (total value 30) fits capacity exactly and has highest value 30.
  3. Final Answer:

    Items with weights 2, 3, and 5 (total value 30) -> Option A
  4. Quick Check:

    Max value under capacity 10 = 30 [OK]
Hint: Sum weights ≤ capacity; pick max value combo [OK]
Common Mistakes:
  • Choosing items exceeding capacity
  • Ignoring combined item values
  • Selecting fewer items with lower total value
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