Taro Logo

Find Array Given Subset Sums

Hard
Asked by:
Mindtickle
0 views
Topics:
ArraysDivide and ConquerSorting

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 2n 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 <= 15
  • sums.length == 2n
  • -104 <= sums[i] <= 104

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the elements in the hidden array be negative, or are we guaranteed that all numbers are non-negative?
  2. Is it guaranteed that a valid hidden array always exists for the given subset sums?
  3. If there are multiple valid hidden arrays that could produce the same set of subset sums, does it matter which one I return?
  4. How should the subset sums be represented in the input? Specifically, will the input array always contain exactly $2^n$ integers?
  5. Is there any constraint on the order in which I should return the elements of the reconstructed array?

Brute Force Solution

Approach

The algorithm reconstructs the original elements by iteratively reducing the collection of subset sums by half. In each iteration, the difference between the smallest two sums gives the absolute value of one original number. By partitioning the current sums into pairs that differ by this value, we can determine the remaining sums and decide the sign of the element based on which half contains zero.

Here's how the algorithm would work step-by-step:

  1. Sort the list of subset sums in non-decreasing order.
  2. Iterate through each of the n steps to identify one element at a time.
  3. Calculate the candidate difference using the two smallest values in the current list.
  4. Partition the sums into two lists such that each element in the second list equals an element in the first list plus the candidate difference.
  5. Check which of the two partitions contains zero, as the empty subset must always sum to zero.
  6. Append the candidate with the appropriate sign to the result and replace the current sums with the valid partition.

Code Implementation

from collections import Counter

def recover_array(length, sums):
    # Sort the initial subset sums to process the smallest elements first
    sums.sort()
    result = []
    current_sums = sums
    
    for _ in range(length):
        # The difference between the two smallest values corresponds to an absolute candidate value
        difference = current_sums[1] - current_sums[0]
        counts = Counter(current_sums)
        subset_without_diff = []
        subset_with_diff = []
        
        # Partition current sums into two halves matching pairs with the difference
        for value in current_sums:
            if counts[value] > 0:
                counts[value] -= 1
                counts[value + difference] -= 1
                subset_without_diff.append(value)
                subset_with_diff.append(value + difference)
        
        # Choose the partition that includes zero to ensure the empty subset is preserved
        if 0 in subset_without_diff:
            result.append(difference)
            current_sums = subset_without_diff
        else:
            result.append(-difference)
            current_sums = subset_with_diff
            
    return result

Big(O) Analysis

Time Complexity
O(n * 2^n) – Sorting the initial array takes O(2^n * log(2^n)) which is O(n * 2^n). In each of the n iterations, the array of size up to 2^n is partitioned in linear time relative to its size, leading to an overall time complexity of O(n * 2^n).
Space Complexity
O(2^n) – A hash map and auxiliary arrays are used in each step to partition the subset sums, requiring memory proportional to the number of sums, which is at most 2^n.

Optimal Solution

Approach

The algorithm reconstructs the original array by repeatedly finding an element that must belong to the subset sums. At each iteration, the difference between the smallest two subset sums gives the absolute value of one array element. The subset sums are partitioned into two halves differing by this value, and the half containing zero is selected to ensure consistent subset generation.

Here's how the algorithm would work step-by-step:

  1. Sort the input subset sums in ascending order.
  2. Compute the difference between the first two elements, which represents a valid element magnitude.
  3. Partition the current subset sums into two equal groups where each element in one group maps to an element shifted by the difference in the other group.
  4. Check which group contains zero to decide whether the element is positive or negative.
  5. Append the determined element to the result and replace the current sums with the valid partition.
  6. Repeat this elimination process until all n original elements are recovered.

Code Implementation

from collections import Counter

def recover_array(n, sums):
    # Sort the given subset sums to identify differences between paired elements.
    sorted_sums = sorted(sums)
    result = []
    for step in range(n):
        difference = sorted_sums[1] - sorted_sums[0]
        counts = Counter(sorted_sums)
        group_excluding = []
        group_including = []
        for value in sorted_sums:
            if counts[value] > 0:
                counts[value] -= 1
                counts[value + difference] -= 1
                group_excluding.append(value)
                group_including.append(value + difference)
        # Check whether zero belongs to the excluding group to determine element sign.
        if 0 in group_excluding:
            result.append(difference)
            sorted_sums = group_excluding
        else:
            result.append(-difference)
            sorted_sums = group_including
    return result

Big(O) Analysis

Time Complexity
O(n * 2^n) – Sorting the initial array takes O(2^n * log(2^n)) = O(n * 2^n) time. In each of the n iterations, partitioning 2^k elements using a frequency counter takes linear time in the size of the remaining sums, summing to O(2^n) across all iterations.
Space Complexity
O(2^n) – The frequency hash map and temporary lists used to partition the subset sums store at most 2^n elements at any step.

Edge Cases

Input subset sums array containing a single element
How to Handle:
Return an empty array because a size of zero implies no elements to reconstruct.
Hidden array containing negative numbers
How to Handle:
The divide-and-conquer approach correctly processes absolute minimum differences regardless of the sign.
Array elements are all zeros
How to Handle:
The algorithm handles zero sums by correctly maintaining zero as the offset between subsets.
Maximum size inputs of 15 elements leading to 2 to the power of 15 subset sums
How to Handle:
Sorting the 32768 subset sums and using frequency maps ensures polynomial logarithmic time complexity to scale efficiently.
Multiple valid solutions or indistinguishable mirror arrays
How to Handle:
Returning any valid permutation satisfies the problem statement as the output order does not matter.
Integer overflow from summing large numbers
How to Handle:
Using 64-bit integer types prevents overflow during intermediate difference calculations.
Subset sums containing duplicate values
How to Handle:
Using a multiset or frequency map tracks exact multiplicities of sums to avoid losing frequency data.