What is the Knapsack problem?
Why Interviewers Ask This
Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.
Answer
The Knapsack problem is a classic optimization problem: given n items each with weight w[i] and value v[i], and a knapsack with capacity W, maximize the total value of items that fit without exceeding the weight limit. Variants: 0/1 Knapsack: each item can be taken or not (0 or 1 times). DP solution: dp[i][w] = max value using first i items with capacity w. Recurrence: dp[i][w] = max(dp[i-1][w], v[i] + dp[i-1][w-w[i]]) if w[i] ≤ w. Time: O(n×W), Space: O(n×W), optimized to O(W). This is called pseudo-polynomial time — polynomial in n and W, but W can be exponential in its bit length. Unbounded Knapsack: each item can be taken unlimited times. dp[w] = max(dp[w], v[i] + dp[w-w[i]]). Fractional Knapsack: items can be broken (take a fraction). Greedy solution: sort by value/weight ratio, take as much of the highest ratio item as possible. O(n log n). Only the fractional variant has a greedy solution. Applications: financial portfolio optimization, cutting problems, resource allocation, cargo loading. The 0/1 knapsack DP solution demonstrates subset sum and bounded optimization patterns used in many other DP problems.
Common Mistake
A common mistake is memorizing definitions without understanding implications. When asked this question, go one level deeper — explain what happens when this concept is misused or ignored.
Previous
What is the difference between depth and height of a tree?
Next
What is the Longest Common Subsequence (LCS)?