GeeksforGeeks Medium

Subset Sums

Subset Sums is a GFG problem (Medium). Given an array arr of integers, return the sums of all subsets of the array, in any order. The empty subset counts, with total 0.

  • An array of n elements has 2^n subsets, so the answer holds 2^n numbers. With n at most 15, that is at most 32,768 values.
  • Equal elements still form different subsets, so repeated totals stay in the output.
Constraints
  • 1 <= arr.length <= 15
  • 0 <= arr[i] <= 10^5
recursionsubsets
Open on GeeksforGeeks ↗
02

Intuition

Build the list of totals one element at a time. Before any element, the only subset is the empty one, so the list is [0].

When a new element x arrives, every subset so far splits in two: a copy without x, which keeps its total, and a copy with x, whose total grows by x. So the new list is the old list plus every old total increased by x.

The list doubles with each element, and after n elements it holds 2^n totals, one per subset. No subset is ever built or copied. Only totals are kept, so each new total costs a single addition.

How to spot this pattern

The output is one number per subset, so the answer itself is exponential. When every element is independently in or out and only a running total matters, carry the totals instead of the subsets.

03

Approach

Try it first

Before reading on, write down the totals for one element, then for two. How does the second list come from the first? Aim for O(2^n) time.

1

Start from the empty subset

Set sums = [0]. The empty subset is always part of the answer, and every other subset grows out of it by adding elements one at a time.

2

Double the list for each element

For each x, take the m totals that were in the list before x arrived and append sums[k] + x for each of them. The first half of the list is now every subset without x, and the second half is every subset with it.

3

Why every subset appears exactly once

After the first i elements, the list has one total per subset of those i elements. A subset of i + 1 elements either skips the new one, so it is in the old half, or takes it, so it is in the new half. It cannot be in both, and it cannot be missing.

4

Return the list unsorted

Return sums as built. The checker sorts the output before comparing, so spending O(2^n log 2^n) on a sort of your own buys nothing at all.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def subsetSums(self, arr):
▶3 sums = [0]
▶4 for x in arr:
▶5 m = len(sums)
▶6 for k in range(m):
▶7 sums.append(sums[k] + x)
▶8 return sums
start0+2+3start: the empty subset has total 0
sums[0]
Before any element is used, the only subset is the empty one, and its total is 0. Every other subset will grow out of it. Each row below is the list after one more element.
start0+202+30 plus 2 → new total 2
x2
m1totals before 2
sums[0, 2]
Old total 0 comes from a subset that does not use this 2. Adding this 2 to it gives a new subset with total 2. That was the last of the 1 old totals, so the list has doubled to 2.
start0+202+30230 plus 3 → new total 3
x3
m2totals before 3
sums[0, 2, 3]
Old total 0 comes from a subset that does not use this 3. Adding this 3 to it gives a new subset with total 3. The 2 old totals stay where they are; only copies with 3 are appended.
start0+202+302352 plus 3 → new total 5
x3
m2totals before 3
sums[0, 2, 3, 5]
Old total 2 comes from a subset that does not use this 3. Adding this 3 to it gives a new subset with total 5. That was the last of the 2 old totals, so the list has doubled to 4.
start0+202+30235all 4 subset totals → return the list
len(sums)42^2
result[0, 2, 3, 5]
Every element has been in or out once, so the list holds 4 totals, one per subset. Repeated values are different subsets that happen to add up the same, so they all stay. The checker sorts the list itself.
05

Take-or-skip recursion

go(i, s) has decided the elements before index i, and s is the total of the ones it took. It branches into taking arr[i] and skipping it. When i reaches the end, every element is decided, so s is one subset's total and is recorded.

▶1class Solution:
▶2 def subsetSums(self, arr):
▶3 out = []
▶4 
▶5 def go(i, s):
▶6 if i == len(arr):
▶7 out.append(s)
▶8 return
▶9 go(i + 1, s + arr[i])
▶10 go(i + 1, s)
▶11 
▶12 go(0, 0)
▶13 return out
06

Common pitfalls

Growing the list while looping over it

✗ Wrong
for s in sums:
    sums.append(s + x)
✓ Right
m = len(sums)
for k in range(m):
    sums.append(sums[k] + x)

The loop keeps meeting the totals it just appended, so even arr = [2] never finishes in Python. Java throws ConcurrentModificationException, and a C++ range loop over a vector that reallocates is undefined behaviour. Fix the count before the loop.

Removing repeated totals

✗ Wrong
return sorted(set(sums))
✓ Right
return sums

For [1, 2, 1] the expected answer has 8 values, [0, 1, 1, 2, 2, 3, 3, 4], because the two 1s are different subsets. A set keeps only 5. Distinct sums are a separate problem.

07

Edge cases

Zeros in the array

A zero still doubles the list, so [0, 5] gives [0, 0, 5, 5]. Taking or skipping the zero are two different subsets with the same total.

08

Complexity

Time
O(2^n)
Space
O(2^n)
Each of the 2^n totals is made by one addition from a total already in the list, so the work equals the output size. Writing 2^n numbers takes 2^n steps, so no method can be faster. Only the output is stored.
09

Subset Sums FAQ

How is this different from listing the subsets themselves?

Subsets returns the subsets themselves, and copying each one costs up to n, so it runs in O(n · 2^n). Here only the totals are needed, so each subset costs O(1) and the whole run is O(2^n).

Do I need every sum to check one target?

No. If the question is whether some subset hits one given total, keep a yes/no table of reachable totals instead, as in Subset Sum Equals Target. That costs O(n · target) rather than O(2^n).

What if the array had 40 elements?

2^40 totals is too many, but the same doubling still helps. Split the array into two halves of 20, list each half's totals (about a million each), sort one list, and combine the halves with binary search or two pointers. This is called meet in the middle.