Find Array Given Subset Sums - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
n = 3, sums = [-3,-2,-1,0,0,1,2,3]
›
Output:
[1,2,-3]
💡 Note:
The array [1,2,-3] generates subset sums: [] = 0, [1] = 1, [2] = 2, [-3] = -3, [1,2] = 3, [1,-3] = -2, [2,-3] = -1, [1,2,-3] = 0. When sorted: [-3,-2,-1,0,0,1,2,3]
Example 2 — Small Array
$
Input:
n = 2, sums = [0,0,0,0]
›
Output:
[0,0]
💡 Note:
The array [0,0] generates all zero subset sums: [] = 0, [0] = 0, [0] = 0, [0,0] = 0
Example 3 — Single Element
$
Input:
n = 1, sums = [0,5]
›
Output:
[5]
💡 Note:
The array [5] generates subset sums: [] = 0, [5] = 5
Constraints
- 1 ≤ n ≤ 15
- sums.length == 2n
- -104 ≤ sums[i] ≤ 104
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code