#1982
Hard Algorithms Find array given subset sums
Array Divide and Conquer
49.5% acceptance
Feb 25, 2026
632
44
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.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn recover_array(n: i32, sums: Vec<i32>) -> Vec<i32> {
use std::collections::BTreeMap;
fn solve(mut sums: Vec<i32>, n: usize) -> Vec<i32> {
if n == 0 {
return vec![];
}
sums.sort();
let d = sums[1] - sums[0]; // difference between two smallest
for &elem in &[d, -(d)] {
let mut freq: BTreeMap<i32, i32> = BTreeMap::new();
for &s in &sums {
*freq.entry(s).or_insert(0) += 1;
}
let mut without = vec![];
let mut ok = true;
for &s in &sums {
let cnt = freq.get_mut(&s).unwrap();
if *cnt == 0 { continue; }
*cnt -= 1;
if elem >= 0 {
// s → without, s+elem → with
without.push(s);
if let Some(cnt2) = freq.get_mut(&(s + elem)) {
if *cnt2 > 0 { *cnt2 -= 1; }
else { ok = false; break; }
} else { ok = false; break; }
} else {
// s → with, s+(-elem) = s+d → without
without.push(s + d);
if let Some(cnt2) = freq.get_mut(&(s + d)) {
if *cnt2 > 0 { *cnt2 -= 1; }
else { ok = false; break; }
} else { ok = false; break; }
}
}
if ok && without.contains(&0) {
let mut result = solve(without, n - 1);
result.push(elem);
return result;
}
}
vec![]
}
solve(sums, n as usize)
}
}