1818. Band Subset Sums

Medium3.5 points estimatedBitmaskBinary SearchSortingEnumeration

A treasure hunter carries n coins whose values are listed in nums; a value may be negative, standing for a debt. Any subset of the coins can be taken, including the empty subset, whose total is 0, and the total of a subset is the sum of its values.

Return how many subsets have a total that lies in the inclusive band [lo, hi]. Subsets are told apart by which positions they use, so equal values at different positions count separately. The count can be as large as 2^36, and sums reach 3.6 * 10^10, so use 64-bit integers. Trying all 2^n subsets is too slow for n = 36. Instead split the array into two halves, list all subset sums of each half, sort one list, and for every sum of the other list count matching partners with two binary searches. Intended complexity: O(2^(n/2) * n) time and O(2^(n/2)) space.

Example 1

Input:
nums = [1,2,3], lo = 3, hi = 4
Output:
3
Explanation:

The subsets with sum 3 or 4 are {3}, {1,2} and {1,3}, so the answer is 3.

Example 2

Input:
nums = [-1,1], lo = 0, hi = 0
Output:
2
Explanation:

The empty subset and {-1, 1} both sum to 0, so the answer is 2.

Constraints

1 ≤ n ≤ 36
-109 ≤ nums[i] ≤ 109
-4 * 1010 ≤ lo ≤ hi ≤ 4 * 1010

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 6,000 msC++ 1,500 msJava 3,000 msJavaScript 3,000 msTypeScript 3,000 ms

Expected complexity

Time
O(2^(n/2) * n)
Space
O(2^(n/2))

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…