Ctrl K

Array From Its Subset Sums

Hard
Someone picked an array of size integers (they may be negative and may repeat) and wrote down the sums of all its subsets, 2^size numbers in arbitrary order. A subset is what remains after crossing out any elements, possibly all of them, so the empty subset sums to 0. If different subsets share a sum, that sum is written once per subset. Given the list totals, recover the hidden array. The elements may be returned in any order. The input is guaranteed to come from some array, and that array is determined uniquely up to the order of its elements.
Example 1
size=2, totals=[0, 7, 3, 4] → [3, 4]

The array [3, 4]: the empty pick gives 0, single elements give 3 and 4, both together give 7.

Example 2
size=3, totals=[3, -2, 8, 0, 6, 1, 5, 3] → [-2, 3, 5]

These are the subset sums of [5, -2, 3]: 0, 5, -2, 3, 5 + (-2) = 3, 5 + 3 = 8, -2 + 3 = 1 and 5 + (-2) + 3 = 6. The sum 3 appears twice because two different subsets produce it.

Example 3
size=1, totals=[0, -6] → [-6]
Constraints
  • 1 ≤ size ≤ 15
  • len(totals) == 2^size
  • -10⁴ ≤ totals[i] ≤ 10⁴
  • The answer exists and is unique up to order
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsMedian Across Two Arrays HardCity Block Outline HardSmaller Values to the Right HardWindow Sums Within a Band HardPairs With a Steep Drop Hard
loading Python…
Input
size=2, totals=[0, 7, 3, 4]
Expected
[3, 4]

Run checks the first 3 tests in your browser. Submit checks all 28 tests on the server, hidden ones included.