Subset sum

Groups that add up exactly · Part of Strategies

Key idea

Practice

6 questions · about 3 min

Explained step by step

Subset sum

Given an array of positive integers and a target, you look for every combination that adds up to the target. In the first version, each item can be used as many times as needed, and the order does not matter. With [3, 4, 5] and target 9, the solutions are {3, 3, 3} and {4, 5}. {5, 4} does not count separately, because it is the same subset as {4, 5}.

If you adapt the permutations code, adding each choice until the target is reached, with [3, 4, 5] and target 9 you get [3, 3, 3], [4, 5] and [5, 4]. The problem is that the search tells the order of choices apart, and a subset has no order. Removing repeats at the end is expensive: with many items and a large target there are a great many, and to compare 2 lists you first have to sort them.

There are 2 more improvements. The first: sort the array before starting. That way, as soon as a choice takes the sum past the target, the for loop is cut, because the ones after it are bigger and would go past too. The second: instead of keeping a sum, each choice is subtracted from the target, and the solution is saved when the target reaches 0. With [3, 4, 5] and 9: choosing 4 leaves 5, choosing 5 leaves 0, and {4, 5} is saved.

In the second version the array can have repeated values and each item is used only once. With [4, 4, 5] and target 9, the previous code gives [4, 5] twice, once with each 4. Repeats come from trying equal values in the same round. Since the array is sorted, equal ones sit together: if the current item equals the previous one in that round, it is skipped. And to avoid using an item twice, the next round starts at i + 1.

Pruning

Repeats can be pruned during the search. If 3 and 4 were chosen in the first 2 rounds, all the [3, 4, ...] have already been produced. If later the first choice is 4, the 3 must be skipped in the second round, because [4, 3, ...] would repeat. The general rule: the chosen indexes never go down. A variable start is used: after choosing item i, the next round starts at i.

Backtracking

The 2 versions change 2 details. If each item can repeat, the next round starts at i; if it is used once, at i + 1. And if the array has repeated values, equal ones are skipped in the same round. Unlike permutations, the list selected is not needed: start already prevents going back. With [3, 4, 5] and 9 there are 2 solutions; with [4, 4, 5] and 9, only one: {4, 5}.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Groups that add up exactly