Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1982: Find Array Given Subset Sums

In this guide, we solve Leetcode #1982 Find Array Given Subset Sums in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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).

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Array, Divide and Conquer

Intuition

The problem splits naturally into smaller subproblems.

Solving each part independently makes the whole problem manageable.

Approach

Divide the input, solve recursively, then merge results.

This structure often yields clean and efficient code.

Steps:

  • Divide into subproblems.
  • Solve recursively.
  • Merge to get final answer.

Example

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.

Python Solution

class Solution: def recoverArray(self, n: int, sums: List[int]) -> List[int]: m = -min(sums) sl = SortedList(x + m for x in sums) sl.remove(0) ans = [sl[0]] for i in range(1, n): for j in range(1 << i): if j >> (i - 1) & 1: s = sum(ans[k] for k in range(i) if j >> k & 1) sl.remove(s) ans.append(sl[0]) for i in range(1 << n): s = sum(ans[j] for j in range(n) if i >> j & 1) if s == m: for j in range(n): if i >> j & 1: ans[j] *= -1 break return ans

Complexity

The time complexity is O(n log n) (typical). The space complexity is O(log n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy