Fractional Knapsack Problem in DSA Javascript - Time & Space Complexity
We want to understand how the time needed to solve the Fractional Knapsack Problem changes as the number of items grows.
Specifically, how the sorting and selection steps affect the total work done.
Analyze the time complexity of the following code snippet.
function fractionalKnapsack(items, capacity) {
items.sort((a, b) => (b.value / b.weight) - (a.value / a.weight));
let totalValue = 0;
for (let item of items) {
if (capacity === 0) break;
let take = Math.min(item.weight, capacity);
totalValue += take * (item.value / item.weight);
capacity -= take;
}
return totalValue;
}
This code sorts items by value per weight, then takes as much as possible from the best items until capacity is full.
- Primary operation: Sorting the items array by value-to-weight ratio.
- How many times: Sorting typically takes about n log n steps for n items.
- Secondary operation: One loop through all items to pick fractions.
- How many times: Loop runs at most n times, once per item.
As the number of items increases, sorting takes more time, growing faster than just going through the list.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 * log 10 ≈ 33 steps for sorting + 10 steps for picking |
| 100 | About 100 * log 100 ≈ 664 steps for sorting + 100 steps for picking |
| 1000 | About 1000 * log 1000 ≈ 9966 steps for sorting + 1000 steps for picking |
Pattern observation: Sorting dominates and grows a bit faster than just the number of items.
Time Complexity: O(n log n)
This means the time needed grows a little faster than the number of items because of sorting, but the picking step grows linearly.
[X] Wrong: "The loop to pick items is the slowest part, so time complexity is O(n)."
[OK] Correct: Sorting the items first takes more time than just looping, so it controls the total time.
Understanding how sorting affects the overall time helps you explain your solution clearly and shows you know where the main work happens.
"What if the items were already sorted by value-to-weight ratio? How would the time complexity change?"
Practice
Fractional Knapsack Problem?Solution
Step 1: Understand the problem goal
The fractional knapsack problem allows taking parts of items to maximize total value within a weight limit.Step 2: Compare options
Maximize total value by taking fractions of items within weight limit correctly states maximizing value by taking fractions. Others ignore fractions or value maximization.Final Answer:
Maximize total value by taking fractions of items within weight limit -> Option AQuick Check:
Fractional knapsack = maximize value with fractions [OK]
- Thinking only whole items can be taken
- Ignoring value and focusing on weight
- Confusing with 0/1 knapsack problem
Solution
Step 1: Identify sorting criteria
We must sort items by descending value-to-weight ratio (value/weight) to pick best items first.Step 2: Check each code snippet
items.sort((a, b) => (b.value / b.weight) - (a.value / a.weight)); sorts descending by (value/weight). Others sort incorrectly by inverse or by value or weight alone.Final Answer:
items.sort((a, b) => (b.value / b.weight) - (a.value / a.weight)); -> Option AQuick Check:
Sort by descending value/weight ratio [OK]
- Sorting by weight or value alone
- Sorting ascending instead of descending
- Using inverse ratio (weight/value)
const items = [
{value: 60, weight: 10},
{value: 100, weight: 20},
{value: 120, weight: 30}
];
const capacity = 50;
function fractionalKnapsack(items, capacity) {
items.sort((a, b) => (b.value / b.weight) - (a.value / a.weight));
let totalValue = 0;
let remaining = capacity;
for (const item of items) {
if (item.weight <= remaining) {
totalValue += item.value;
remaining -= item.weight;
} else {
totalValue += item.value * (remaining / item.weight);
break;
}
}
return totalValue;
}
console.log(fractionalKnapsack(items, capacity));Solution
Step 1: Sort items by value/weight ratio
Ratios: 60/10=6, 100/20=5, 120/30=4. Sorted order: item1, item2, item3.Step 2: Add items until capacity 50
Take item1 fully (weight 10, value 60), remaining 40.
Take item2 fully (weight 20, value 100), remaining 20.
Take fraction of item3: (20/30)*120 = 80.
Total value = 60 + 100 + 80 = 240.Final Answer:
240 -> Option BQuick Check:
Sum values with fractions = 240 [OK]
- Not sorting by ratio correctly
- Taking items without fractions
- Miscomputing fraction value
function fractionalKnapsack(items, capacity) {
items.sort((a, b) => (a.value / a.weight) - (b.value / b.weight));
let totalValue = 0;
let remaining = capacity;
for (const item of items) {
if (item.weight <= remaining) {
totalValue += item.value;
remaining -= item.weight;
} else {
totalValue += item.value * (remaining / item.weight);
break;
}
}
return totalValue;
}Solution
Step 1: Analyze sorting order
The code sorts items ascending by value/weight ratio, but we need descending to pick best items first.Step 2: Check other parts
Return statement exists, fraction formula is correct, 'let' is appropriate for totalValue.Final Answer:
Sorting is ascending; should be descending by value/weight ratio -> Option DQuick Check:
Sort descending by ratio to maximize value [OK]
- Sorting ascending instead of descending
- Ignoring fraction calculation correctness
- Confusing variable declarations
items = [
{value: 40, weight: 2},
{value: 100, weight: 20},
{value: 50, weight: 10},
{value: 60, weight: 12}
];
capacity = 30;What is the maximum total value achievable using the fractional knapsack approach?
Solution
Step 1: Calculate value/weight ratios and sort descending
Ratios:
Item1: 40/2=20
Item2: 100/20=5
Item3: 50/10=5
Item4: 60/12=5
Sorted order: Item1, then Items 2,3,4 (equal ratio 5).Step 2: Pick items until capacity 30
Take Item1 fully: weight 2, value 40, remaining 28.
Next, take Item2 fully: weight 20, value 100, remaining 8.
Then take fraction of Item3: fraction = 8/10 = 0.8, value = 50 * 0.8 = 40.
Total value = 40 + 100 + 40 = 180.Step 3: Check if taking Item4 fraction is better
Item4 has same ratio as Item3, but we already used remaining capacity on Item3 fraction.
So total value remains 180.Final Answer:
180 -> Option CQuick Check:
Sum values with fractions = 180 [OK]
- Ignoring highest ratio item first
- Not taking fractions correctly
- Adding values without considering capacity
Ready to prove it?
Pass the test and this pattern moves unknown
