Data Structures & AlgorithmsHardTCS NQT Digital · Product Company SDE
Problem: Which statement correctly contrasts 0/1 knapsack and fractional knapsack?
- A. Both are solved optimally by the same greedy algorithm
- B. 0/1 knapsack is solved by greedy, fractional needs DP
- C. Neither can be solved in polynomial time
- D. Fractional knapsack is solved optimally by a greedy value/weight-ratio approach, but the same greedy strategy is not optimal for 0/1 knapsack, which needs DP
Correct answer: D. Fractional knapsack is solved optimally by a greedy value/weight-ratio approach, but the same greedy strategy is not optimal for 0/1 knapsack, which needs DP
When items can be split, taking the highest value/weight ratio first is always optimal (fractional knapsack). Once items must be taken whole, that greedy choice can be suboptimal, so 0/1 knapsack requires O(nW) DP over weight capacity.
More Coding Interview Problems questions
- Problem: Activity selection (pick the maximum number of non-overlapping intervals from a set) is solved optimally by which greedy strategy?
- Problem: Which of these coin systems is a classic counterexample where the greedy 'always take the largest coin' algorithm fails to find…
- Problem: Huffman coding builds an optimal prefix-free binary code for a set of symbol frequencies. Which greedy step does it repeat?
- Problem: What is the time complexity of computing the longest increasing subsequence using patience-sorting with binary search, versus the…
- Problem: The longest common subsequence (LCS) of two strings of length n and m is typically solved with which approach and complexity?
- Problem: Subset-sum (does any subset of n integers sum exactly to a target T?) has a DP solution running in O(nT). Why is this not…