What is the subset sum problem?

Why Interviewers Ask This

This tests whether you can apply Data Structures & Algorithms knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.

Answer

The Subset Sum problem: given a set of n positive integers and a target sum S, determine if there exists a subset with sum exactly S. DP solution: dp[i][s] = true if a subset of first i elements sums to s. Recurrence: dp[i][s] = dp[i-1][s] (exclude item i) OR dp[i-1][s-arr[i]] (include item i, if arr[i] ≤ s). Base: dp[0][0] = true, dp[i][0] = true (empty subset sums to 0). Time: O(n×S). Space: O(n×S), optimized to O(S) using 1D DP (traverse right to left: dp[s] = dp[s] || dp[s-arr[i]]). This is a 0/1 Knapsack variant (value = weight). Variants: (1) Count subsets with given sum; (2) Minimum difference partition — partition into two subsets with minimum sum difference; (3) Equal sum partition — can we partition into two equal halves? Reduce to subset sum with target = totalSum/2; (4) Number of subsets with given difference. NP-completeness: Subset Sum is NP-complete in general (no known polynomial algorithm for arbitrary sizes). The DP solution is pseudo-polynomial (polynomial in n and S, but S can be exponential in its bit length). Applications: cryptography, resource allocation, scheduling, target sum (allow +/-) problems.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Data Structures & Algorithms answers easy to follow.