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
Find Array Given Subset Sums INPUT n = 3 (array length) sums array (2^n = 8 values): -3 -2 -1 0 0 1 2 3 Sorted sums: [-3,-2,-1,0,0,1,2,3] All 2^3 subset sums from unknown array ? a b c ALGORITHM STEPS 1 Sort & Find Diff d = sums[1] - sums[0] d = -2 - (-3) = 1 2 Split into Two Sets Separate sums with/without d [-3,-2,0,1] [-2,-1,1,2] 3 Check for Zero Pick set containing 0 Found: [-3,-2,0,1] has 0 4 Recurse Repeat with smaller set Add d to result array [1,2,-3] found n=2 n=1 FINAL RESULT Recovered Array: 1 2 -3 Verification: Empty set: 0 {1}: 1 {2}: 2 {-3}: -3 {1,2}: 3 {1,-3}: -2 {2,-3}: -1 {1,2,-3}: 0 [-3,-2,-1,0,0,1,2,3] OK - Matches input sums! Output: [1, 2, -3] Key Insight: The difference between the smallest two subset sums (after sorting) gives a candidate element. Divide sums into two groups: those containing this element and those without. Recurse on the set containing 0 (empty subset sum). This divide-and-conquer reduces 2^n sums to 2^(n-1) each iteration. TutorialsPoint - Find Array Given Subset Sums | Divide and Conquer Approach
Asked in
Google 15 Facebook 12 Amazon 8
23.4K Views
Medium Frequency
~45 min Avg. Time
876 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen