Find Array Given Subset Sums Problem
Description
LeetCode Problem 1982.
You are given an integer n representing the length of an unknown array that you are trying to recover. You are also given an array sums containing the values of all 2^n subset sums of the unknown array (in no particular order).
Return the array ans of length n representing the unknown array. If multiple answers exist, return any of them.
An array sub is a subset of an array arr if sub can be obtained from arr by deleting some (possibly zero or all) elements of arr. The sum of the elements in sub is one possible subset sum of arr. The sum of an empty array is considered to be 0.
Note: Test cases are generated such that there will always be at least one correct answer.
Example 1:
Input: n = 3, sums = [-3,-2,-1,0,0,1,2,3]
Output: [1,2,-3]
Explanation: [1,2,-3] is able to achieve the given subset sums:
- []: sum is 0
- [1]: sum is 1
- [2]: sum is 2
- [1,2]: sum is 3
- [-3]: sum is -3
- [1,-3]: sum is -2
- [2,-3]: sum is -1
- [1,2,-3]: sum is 0
Note that any permutation of [1,2,-3] and also any permutation of [-1,-2,3] will also be accepted.
Example 2:
Input: n = 2, sums = [0,0,0,0]
Output: [0,0]
Explanation: The only correct answer is [0,0].
Example 3:
Input: n = 4, sums = [0,0,5,5,4,-1,4,9,9,-1,4,3,4,8,3,8]
Output: [0,-1,4,5]
Explanation: [0,-1,4,5] is able to achieve the given subset sums.
Constraints:
1 <= n <= 15sums.length == 2^n-10^4 <= sums[i] <= 10^4
Solution
Approach: Shift, Then Peel Off the Smallest Sum
Shift all subset sums by m = -min(sums) (the sum of the negative values), so that they become the subset sums of the array with every value replaced by its absolute value. All values are now non-negative.
Remove the empty-subset sum 0. Among the sums left, the smallest one must be the smallest value a[0]. Then remove every sum that can be formed from the values found so far and, again, the smallest remaining sum is the next value. Repeat until n values are found. Counting sums in a map (with the sorted distinct sums and a moving pointer) makes each removal cheap.
Finally the real array has some of these values negated. Their negatives add up to -m, so look for a subset of the values whose sum is m and flip its signs; any such subset gives a valid answer.
Complexity: time O(2^n * n) and space O(2^n).
class Solution:
def recoverArray(self, n: int, sums: List[int]) -> List[int]:
m = -min(sums)
cnt = {}
for x in sums:
cnt[x + m] = cnt.get(x + m, 0) + 1
keys = sorted(cnt)
p = 0
cnt[0] -= 1
while cnt[keys[p]] == 0:
p += 1
ans = [keys[p]]
for i in range(1, n):
for j in range(1 << i):
if j >> (i - 1) & 1:
s = sum(ans[k] for k in range(i) if j >> k & 1)
cnt[s] -= 1
while cnt[keys[p]] == 0:
p += 1
ans.append(keys[p])
for i in range(1 << n):
s = sum(ans[j] for j in range(n) if i >> j & 1)
if s == m:
for j in range(n):
if i >> j & 1:
ans[j] *= -1
break
return ans