#1982Hard~60 min

Find Array Given Subset Sums

Time O(n * 2^n) · Space O(1) · Official statement on LeetCode

cpppython

Solutions

// Time:  O(n * 2^n), len(sums) = 2^n
// Space: O(1)

// [proof]
// - let d = sorted_sums[0]-sorted_sums[1] and d != -d (d = 0 is trival), where one of +d/-d is the smallest positive or largest negative number of the original solution of [S1, ..., S(2^n)]
// - given Sp-d = 0 for some p in [1, 2^n] and Sq-(-d) = 0 for some q in [1, 2^n]
//   assume d is a number of the original solution of [S1, ..., S(2^n)] (the proof where -d is a number of the original solution is vice versa)
//   let Sq = x1+...+xi where 1 <= i <= n-1
//   let [d]+[x1, ..., xi]+[x(i+1), ..., x(n-1)] be the original solution
//   => new_sums([S1, ..., S(2^n)], d)
//      = subset_sums([x1, ..., xi]+[x(i+1), ..., x(n-1)])
//   if we choose -d as a number of a solution of [S1, ..., S(2^n)]
//   => new_sums([S1, ..., S(2^n)], -d)
//      = new_sums([S1, ..., S(2^n)], -(x1+...+xi))
//      = subset_sums([(-x1), ..., (-xi)]+[x(i+1), ..., x(n-1)])
//      => [-d]+[(-x1), ..., (-xi)]+[x(i+1), ..., x(n-1)] is also a solution
//
// [conclusion]
// - if new_sums with +d/-d (including d = 0) both contain zero, we can choose either one
// - if only one of new_sums with +d/-d contains zero, we can only choose the one with zero since subset_sums must contain zero

// optimized from solution4 (not using unordered_map), runtime: 188 ms
class Solution {
public:
    vector<int> recoverArray(int n, vector<int>& sums) {
        sort(begin(sums), end(sums));  // Time: O(2^n * log(2^n)) = O(n * 2^n)
        int shift = 0, l = size(sums);
        vector<int> result;
        for (; n--; l /= 2) {  // log(2^n) times, each time costs O(2^(n-len(result))), Total Time: O(2^n)
            const int new_shift = sums[0] - sums[1];
            assert(new_shift <= 0);
            bool has_zero = false;
            for (int i = 0, j = 0, k = 0; i < l; ++i) {
                if (k < j && sums[k] == sums[i]) {  // skip shifted one
                    ++k;
                } else {
                    if (shift == sums[i] - new_shift) {
                        has_zero = true;
                    }
                    sums[j++] = sums[i] - new_shift;
                }
            }
            if (has_zero) {  // contain 0, choose this side
                result.emplace_back(new_shift);
            } else {  // contain no 0, choose another side and shift 0 offset
                result.emplace_back(-new_shift);
                shift -= new_shift;
            }
        }
        return result;
    }
};

// Time:  O(2^n + n * r), len(sums) = 2^n
//                      , r = max(sums)-min(sums)
// Space: O(2^n + r)
// optimized from solution4 (not using unordered_map), runtime: 148 ms
class Solution2 {
public:
    vector<int> recoverArray(int n, vector<int>& sums) {
        const int min_sum = *min_element(cbegin(sums), cend(sums));
        const int max_sum = *max_element(cbegin(sums), cend(sums));
        vector<int> dp(max_sum - min_sum + 1);
        for (const auto& sum : sums) {
            ++dp[sum - min_sum];
        }
        vector<int> sorted_sums;
        for (int x = min_sum; x <= max_sum; ++x) {
            if (dp[x - min_sum]) {
                sorted_sums.emplace_back(x);
            }
        }
        int shift = 0;
        vector<int> result;
        while (n--) { // log(2^n) times, each time costs O(2^(n-len(result)))+O(r), Total Time: O(2^n + n * r)
            vector<int> new_dp(max_sum - min_sum + 1);
            vector<int> new_sorted_sums;
            const int new_shift = (dp[sorted_sums[0] - min_sum] == 1) ? sorted_sums[0] - sorted_sums[1] : 0;
            assert(new_shift <= 0);
            for (const auto& x : sorted_sums) {
                if (!dp[x - min_sum]) {
                    continue;
                }
                dp[(x - new_shift) - min_sum] -= new_shift ? dp[x - min_sum] : dp[x - min_sum] / 2;
                new_dp[(x - new_shift) - min_sum] = dp[x - min_sum];
                new_sorted_sums.emplace_back(x - new_shift);
            }
            dp = move(new_dp);
            sorted_sums = move(new_sorted_sums);
            if (dp[shift - min_sum]) {  // contain 0, choose this side
                result.emplace_back(new_shift);
            } else {  // contain no 0, choose another side and shift 0 offset
                result.emplace_back(-new_shift);
                shift -= new_shift;
            }
        }
        return result;
    }
};

// Time:  O(n * 2^n), len(sums) = 2^n
// Space: O(2^n)
// optimized from solution4, runtime: 344 ms
class Solution3 {
public:
    vector<int> recoverArray(int n, vector<int>& sums) {
        unordered_map<int, int> dp;
        for (const auto& sum : sums) {
            ++dp[sum];
        }
        vector<int> sorted_sums;
        for (const auto& [k, _] : dp) {
            sorted_sums.emplace_back(k);
        }
        sort(begin(sorted_sums), end(sorted_sums));  // Time: O(2^n * log(2^n)) = O(n * 2^n)
        int shift = 0;
        uint32_t total = 0;
        for (const auto& [k, v] : dp) {
            total |= v;
        }
        const uint32_t basis = total & -total;  // find rightmost bit 1
        if (basis > 1) {
            for (auto& [_, v] : dp) {
                v /= basis;
            }
        }
        vector<int> result(bit_length(basis) - 1);
        n -= bit_length(basis) - 1;
        while (n--) {  // log(2^n) times, each time costs O(2^(n-len(result))), Total Time: O(2^n)
            unordered_map<int, int> new_dp;
            vector<int> new_sorted_sums;
            const int new_shift = (dp[sorted_sums[0]] == 1) ? sorted_sums[0] - sorted_sums[1] : 0;
            assert(new_shift <= 0);
            for (const auto& x : sorted_sums) {
                if (!dp[x]) {
                    continue;
                }
                dp[x - new_shift] -= new_shift ? dp[x] : dp[x] / 2;
                new_dp[x - new_shift] = dp[x];
                new_sorted_sums.emplace_back(x - new_shift);
            }
            dp = move(new_dp);
            sorted_sums = move(new_sorted_sums);
            if (dp.count(shift)) {  // contain 0, choose this side
                result.emplace_back(new_shift);
            } else {  // contain no 0, choose another side and shift 0 offset
                result.emplace_back(-new_shift);
                shift -= new_shift;
            }
        }
        return result;
    }

private:
    int bit_length(int x) {
        return x != 0 ? 32 - __builtin_clz(x) : 1;
    }
};

// Time:  O(n * 2^n), len(sums) = 2^n
// Space: O(2^n)
// runtime: 344 ms
class Solution4 {
public:
    vector<int> recoverArray(int n, vector<int>& sums) {
        unordered_map<int, int> dp;
        for (const auto& sum : sums) {
            ++dp[sum];
        }
        vector<int> sorted_sums;
        for (const auto& [k, _] : dp) {
            sorted_sums.emplace_back(k);
        }
        sort(begin(sorted_sums), end(sorted_sums));  // Time: O(2^n * log(2^n)) = O(n * 2^n)
        int shift = 0;
        vector<int> result;
        while (n--) {  // log(2^n) times, each time costs O(2^(n-len(result))), Total Time: O(2^n)
            unordered_map<int, int> new_dp;
            vector<int> new_sorted_sums;
            const int new_shift = (dp[sorted_sums[0]] == 1) ? sorted_sums[0] - sorted_sums[1] : 0;
            assert(new_shift <= 0);
            for (const auto& x : sorted_sums) {
                if (!dp[x]) {
                    continue;
                }
                dp[x - new_shift] -= new_shift ? dp[x] : dp[x] / 2;
                new_dp[x - new_shift] = dp[x];
                new_sorted_sums.emplace_back(x - new_shift);
            }
            dp = move(new_dp);
            sorted_sums = move(new_sorted_sums);
            if (dp.count(shift)) {  // contain 0, choose this side
                result.emplace_back(new_shift);
            } else {  // contain no 0, choose another side and shift 0 offset
                result.emplace_back(-new_shift);
                shift -= new_shift;
            }
        }
        return result;
    }
};

Beginner Explanation

What is Find Array Given Subset Sums?

Find Array Given Subset Sums (LeetCode #1982) is a Hard problem that primarily trains math.

How to think about it

  1. Restate the goal in your own words before coding.
  2. Work a tiny example by hand so the invariant becomes obvious.
  3. Identify the pattern — this problem aligns with dynamic programming.
  4. Only then translate the idea into code.

Why this problem matters

Hard problems force you to combine patterns and prove complexity carefully — interview gold. Official solution notes mention: Math, DP, OrderedDict.

AlgoForge explanations are original teaching notes. Always open the official problem statement on LeetCode for constraints and examples.

Interview Walkthrough

Interview approach for Find Array Given Subset Sums

Opening (30–60 seconds)

  • Clarify inputs/outputs and edge cases (empty input, single element, duplicates, overflow).
  • State a brute force so the interviewer knows you can solve it naively.
  • Propose the optimal direction tied to dynamic programming.

Core solution narrative

  1. Define the state you track (pointers, DP cell, set membership, stack top, etc.).
  2. Explain the transition when you process the next element.
  3. Call out time (O(n * 2^n)) and space (O(1)) before coding.
  4. Code cleanly; narrate variable names.

What interviewers listen for

  • Correctness on edge cases
  • Complexity honesty
  • Ability to discuss trade-offs (e.g., hash map space vs. sort + two pointers)

Follow-up questions they may ask

  • Can you solve it with less memory?
  • What if the input stream is infinite / doesn't fit in RAM?
  • How would tests look for adversarial inputs?

Optimized Approach

Optimized solution notes

The reference solutions on AlgoForge target O(n * 2^n) time and O(1) space.

Pattern focus: dynamic programming

Use the pattern as a checklist:

  • dynamic programming — confirm the invariant holds after each step

Multiple methods appear in the source solutions — compare them and explain when each is preferable.

Implementation tips

  • Prefer readable names over micro-optimizations in interviews.
  • Extract helpers only when they clarify (e.g., expand-around-center, DFS visit).
  • After AC-level logic, re-scan for off-by-one and null checks.

Complexity Analysis

Complexity

Measure Bound
Time O(n * 2^n)
Space O(1)

How to justify this in an interview

  • Time: count loops, map/set operations, and recursive branching; state average vs worst case if relevant.
  • Space: include hash maps, recursion stack, and output allocation when the problem asks for it.

If your implementation differs from the reference, re-derive big-O from your code — never memorize a complexity you cannot defend.

Common Mistakes

Common mistakes on Find Array Given Subset Sums

  1. Skipping edge cases — empty collections, single-element inputs, max constraints.
  2. Wrong invariant for dynamic programming — updating state too early or too late.
  3. Mutating input unexpectedly when the problem forbids it.
  4. Off-by-one in windows, ranges, or binary search bounds.
  5. Ignoring overflow / precision for integer arithmetic problems.
  6. Overengineering — jumping to an advanced structure when a simpler approach works.

Alternative Approaches

Alternatives

The source file includes more than one method. Compare:

  1. Primary optimized path — best complexity for typical interviews.
  2. Secondary approach — often brute force, sorting-based, or space-optimized variant.

Practice articulating when you would pick each (constraints, readability, follow-ups).

Edge Cases

Edge cases checklist

  • Minimum input size
  • Maximum input size / time limits
  • Duplicates and already-sorted input
  • Negative numbers / zeros (if applicable)
  • Disconnected structures (graphs/trees)
  • Single path vs branching recursion depth

Pattern Recognition

Spotting this pattern

Signal phrases that point to dynamic programming:

  • Sorted input or ability to sort without changing the answer class
  • Need for contiguous subarray / substring → consider sliding window
  • Need for O(1) membership → hash set/map
  • Optimal substructure + overlapping subproblems → DP
  • Connectivity / components → graph DFS/BFS or Union-Find

Primary topics: math.

Follow-up Interview Questions

Follow-ups

  1. How does the solution change if the input is a stream?
  2. Can you solve it in-place?
  3. What if duplicates must be handled differently?
  4. How would you parallelize the approach?
  5. Design tests that would break a buggy implementation.

Practice Recommendations

What to practice next

  1. Re-solve Find Array Given Subset Sums in a second language (cpp, python).
  2. Drill 3–5 more problems tagged math.
  3. Teach the solution out loud in under 5 minutes.
  4. Add this problem to your revision calendar in 3 days and 14 days.

Visualization

Conceptual diagram for Find Array Given Subset Sums: show input structure (math), highlight the moving parts of the dynamic programming approach, and annotate each step with the maintained invariant and complexity.

Study checklist

  • Read the official problem statement on LeetCode
  • Solve on paper / whiteboard first
  • Implement the dynamic programming approach
  • Verify edge cases from the checklist
  • State time and space complexity aloud
  • Compare with the AlgoForge reference solution
  • Schedule a revision session

Revision notes

Find Array Given Subset Sums (#1982) — Hard. Pattern: dynamic programming. Complexity: O(n * 2^n) time / O(1) space. Re-derive the invariant before coding.

FAQs

What is the time complexity of Find Array Given Subset Sums?+

The reference solutions aim for O(n * 2^n) time and O(1) space. Always re-derive complexity from the code you write in the interview.

What pattern does Find Array Given Subset Sums use?+

It primarily maps to dynamic programming, within the broader topic of math.

Is Find Array Given Subset Sums good for interviews?+

Yes — as a Hard problem it is a solid practice target. Pair it with related problems in the same pattern family for spaced repetition.

Where can I read the official statement?+

Open the official LeetCode page for constraints and examples: https://leetcode.com/problems/find-array-given-subset-sums/