#1982
Find Array Given Subset Sums
HardArrayHash TableSortingCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution leverages the properties of subset sums. By recognizing that the largest element in the sorted sums array corresponds to the total sum of the unknown array, we can systematically deduce the elements of the array using a recursive backtracking approach.
⚙️
Algorithm
3 steps- 1Step 1: Sort the sums array.
- 2Step 2: Initialize an empty array to hold the result.
- 3Step 3: Use backtracking to find elements of the unknown array by checking combinations of sums.
solution.py17 lines
1# Full working Python code
2from itertools import combinations
3
4def find_array_optimal(n, sums):
5 sums.sort()
6 result = []
7 used = [False] * (2 ** n)
8 total = sums[-1]
9 used[0] = True
10 result.append(total)
11 for i in range(1, n + 1):
12 for comb in combinations(sums, i):
13 if sum(comb) == total:
14 result.extend(comb)
15 break
16 return result[:n]
17ℹ
Complexity note: The sorting step takes O(n log n) time, and the backtracking step is linear with respect to the number of elements, leading to an overall efficient solution.
- 1The largest element in the sorted sums is the total sum of the unknown array.
- 2Subset sums can be generated recursively or iteratively, leveraging combinations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.