Subset Sum

Understand the various techniques used to solve the subset sum problem efficiently.

Subset sum problem and its description

Let’s consider a more complicated problem called subset sum: Given a set X of positive integers and target integer T, is there a subset of elements in X that add up to T? Notice that there can be more than one such subset. For example, if X=8,6,7,5,3,10,9X = {8,6,7,5,3,10,9} and T=15T = 15, the answer is True, because the subsets 8,7{8,7} and 7,5,3{7,5,3} and 6,9{6,9} and 5,10{5,10} all add up to 15. On the other hand, if X=11,6,5,1,7,13,12X = {11,6,5,1,7,13,12} and T=15T = 15, the answer is False.

There are two trivial cases. If the target value TT is zero, then we can immediately return True because the empty set is a subset of every set XX, and the elements of the empty set add up to zero. On the other hand, if T<0T < 0, or if T0T\neq 0 but the set XX is empty, then we can immediately return False.

For the general case, consider an arbitrary element xXx ∈ X. (We’ve already handled the case where XX is empty.) There is a subset of XX that sums to TT if and only if one of the following statements is true:

  • There is a subset of XX that includes xx and whose sum is TT.
  • There is a subset of XX that excludes xx and whose sum is TT.

In the first case, there must be a subset of X \{x}X\space \backslash \left\{ x\right\} that sums to TxT − x; in the second case, there must be a subset of X \{x}X\space \backslash \left\{ x\right\} that sums to TT. So we can solve SubsetSum(X,T)SubsetSum(X,T) by reducing it to two simpler instances: SubsetSum(X \{x},Tx)SubsetSum(X\space \backslash \left\{ x\right\}, T-x) and SubsetSum(X \{x},T)SubsetSum(X\space \backslash \left\{ x\right\}, T). The resulting recursive algorithm is shown below.

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy