Fractional Knapsack Problem in DSA Typescript - 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, we ask: how does the work increase when we have more items to choose from?
Analyze the time complexity of the following code snippet.
function fractionalKnapsack(weights: number[], values: number[], capacity: number): number {
const n = weights.length;
const items = [];
for (let i = 0; i < n; i++) {
items.push({
weight: weights[i],
value: values[i],
ratio: values[i] / weights[i]
});
}
items.sort((a, b) => b.ratio - a.ratio);
let totalValue = 0;
let remaining = capacity;
for (const item of items) {
if (item.weight <= remaining) {
totalValue += item.value;
remaining -= item.weight;
} else {
totalValue += item.ratio * remaining;
break;
}
}
return totalValue;
}
This code sorts items by value per weight and then picks as much as possible from the best items until the capacity is full.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Sorting the items by their value-to-weight ratio.
- How many times: Sorting runs once over all items, which takes time depending on the number of items.
- Two loops run over all items: one to create the list and one to pick items.
As the number of items increases, sorting takes more time, growing faster than just looking at items one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 log 10 (sorting) + 2*10 (loops) = ~40 operations |
| 100 | About 100 log 100 + 200 = ~900 operations |
| 1000 | About 1000 log 1000 + 2000 = ~13000 operations |
Pattern observation: The sorting step dominates and grows faster than the loops, roughly like n times log n.
Time Complexity: O(n log n)
This means the time needed grows a bit faster than the number of items, mainly because of sorting.
[X] Wrong: "The main time cost is picking items, so the complexity is O(n)."
[OK] Correct: Sorting the items by ratio takes more time than just picking, so sorting dominates the total time.
Understanding this time complexity helps you explain why sorting is important before choosing items, a key skill in optimization problems.
"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 problem goal
The fractional knapsack problem allows taking parts of items to maximize value within a weight limit.Step 2: Compare options
Maximize total value by taking fractions of items within weight limit correctly states maximizing total value by taking fractions. Others focus on minimizing weight or whole items only, which is incorrect.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
- Confusing minimization with maximization
- Ignoring fractional parts of items
Solution
Step 1: Check array and object syntax
const items = [{weight: 10, value: 60}, {weight: 20, value: 100}]; uses correct array of objects syntax with curly braces and key-value pairs.Step 2: Identify syntax errors in other options
Options A, B, and D have invalid TypeScript syntax for arrays or objects.Final Answer:
const items = [{weight: 10, value: 60}, {weight: 20, value: 100}]; -> Option DQuick Check:
Array of objects syntax = const items = [{weight: 10, value: 60}, {weight: 20, value: 100}]; [OK]
- Using parentheses instead of square brackets for arrays
- Missing key names in objects
- Incorrect object literal syntax
const items = [
{weight: 10, value: 60},
{weight: 20, value: 100},
{weight: 30, value: 120}
];
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 20/30 fraction of item3: value = 120 * (20/30) = 80.
Total value = 60 + 100 + 80 = 240.Step 3: Check options
Matches 240.Final Answer:
240 -> Option CQuick Check:
Sum values with fractions = 240 [OK]
- Not sorting items by value/weight ratio
- Taking items without fractions
- Incorrect fraction calculation
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 function
The sort compares (a.value/a.weight) - (b.value/b.weight), which sorts ascending by ratio.Step 2: Understand impact on knapsack
Fractional knapsack requires descending order to pick highest value/weight first. Ascending order causes wrong selection.Final Answer:
Sorting order is ascending instead of descending by value/weight -> Option BQuick Check:
Sort descending by ratio [OK]
- Sorting ascending instead of descending
- Ignoring sorting impact on result
- Confusing variable declarations
Solution
Step 1: Calculate value/weight ratios and sort descending
Ratios: 30/5=6, 40/10=4, 140/20=7.
Sorted order: item3 (7), item1 (6), item2 (4).Step 2: Fill knapsack capacity 15
Take item3 partially: since 20 > 15, value = 140 * (15/20) = 105.
Total value = 105.
Remaining capacity 0, stop.Final Answer:
105 -> Option AQuick Check:
Fractional knapsack max value = 105 [OK]
- Not sorting by value/weight ratio
- Trying to take full items exceeding capacity
- Miscomputing fractional values
Ready to prove it?
Pass the test and this pattern moves unknown
