Subset Sums

Pattern: Subsets

medium

With up to 34 numbers, 2³⁴ subsets are too many. Split the array in half, list every subset sum of each half (2¹⁷ each), sort one half, and for each sum in the other half count partners that bring the total into [A, B] with two binary searches.

The problem

Given n whole numbers (positive, negative or zero) and two bounds A ≤ B, count the subsets whose sum lies between A and B inclusive. The empty subset counts, with sum 0. For example, [1, -2, 3] with A = -1, B = 2 gives 5: the empty subset (0), {1} (1), {1, -2} (-1), {-2, 3} (1) and {1, -2, 3} (2).

The link above is the SPOJ problem SUBSUMS, which reads one case from input with n ≤ 34. This guide's function countSubsets solves one case, and its name is this guide's own. The answer can exceed 32 bits.

Think first

  • Why is 2³⁴ too many to list?
  • If you knew every subset sum of each half, how would you combine them?
  • Which half should be sorted, and what do you search for?

Hints

    Brute force, and why it fails

    Enumerate all 2ⁿ subsets: about 17 billion for n = 34, far too slow. Meet in the middle does about 2 × 2¹⁷ sums plus 2¹⁷ binary searches.

    The key insight

    Meet in the middle trades one huge search for two small ones and a fast way to combine them. Sorting one side turns "how many partners fit" into a pair of binary searches.

    Dry run

    left 10 
    right -2 31 

    nums = [1, -2, 3], A = -1 and B = 2. Split into [1] and [-2, 3].

    Step 1 of 4

    The plan

    left = all subset sums of nums[0 .. n/2 - 1]
    right = sorted(all subset sums of nums[n/2 .. n - 1])
    count = 0
    for x in left:
        count += upperBound(right, B - x) - lowerBound(right, A - x)
    return count
    

    Complexity

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

    Listing each half takes O(2^(n/2) × n/2), sorting adds a log factor, and each search is O(n/2). Each half's sums are stored.

    Edge cases

    • One number: two subsets, sums 0 and the number.
    • A > 0: the empty subset does not count.
    • Large counts: use 64-bit numbers.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public long countSubsets(int[] nums, int a, int b) {
            int n = nums.length, h = n / 2;
            long[] left = sums(nums, 0, h), right = sums(nums, h, n);   // meet in the middle: all sums of each half
            Arrays.sort(right);
            long count = 0;
            for (long x : left) count += countBetween(right, a - x, b - x);   // right sums that complete x into [a, b]
            return count;
        }
    
        private long[] sums(int[] nums, int from, int to) {
            int m = to - from;
            long[] out = new long[1 << m];
            for (int mask = 0; mask < (1 << m); mask++) {
                long s = 0;
                for (int i = 0; i < m; i++) if ((mask >> i & 1) == 1) s += nums[from + i];
                out[mask] = s;
            }
            return out;
        }
    
        private long countBetween(long[] sorted, long lo, long hi) {   // how many values lie in [lo, hi]
            return firstAbove(sorted, hi) - firstAbove(sorted, lo - 1);
        }
    
        private int firstAbove(long[] a, long x) {
            int lo = 0, hi = a.length;
            while (lo < hi) {
                int mid = (lo + hi) >>> 1;
                if (a[mid] > x) hi = mid;
                else lo = mid + 1;
            }
            return lo;
        }
    }

    C++

    class Solution {
    public:
        long long countSubsets(vector<int>& nums, int a, int b) {
            int n = static_cast<int>(nums.size()), h = n / 2;
            vector<long long> left = sums(nums, 0, h), right = sums(nums, h, n);   // meet in the middle
            sort(right.begin(), right.end());
            long long count = 0;
            for (long long x : left) {                      // right sums that complete x into [a, b]
                count += upper_bound(right.begin(), right.end(), static_cast<long long>(b) - x)
                       - lower_bound(right.begin(), right.end(), static_cast<long long>(a) - x);
            }
            return count;
        }
    
        vector<long long> sums(vector<int>& nums, int from, int to) {
            int m = to - from;
            vector<long long> out(1u << m);
            for (int mask = 0; mask < (1 << m); mask++) {
                long long s = 0;
                for (int i = 0; i < m; i++) if (mask >> i & 1) s += nums[from + i];
                out[mask] = s;
            }
            return out;
        }
    };

    Python

    import bisect
    
    class Solution:
        def countSubsets(self, nums: list[int], a: int, b: int) -> int:
            h = len(nums) // 2
    
            def sums(part: list) -> list:            # every subset sum of one half
                out = [0]
                for v in part:
                    out += [s + v for s in out]
                return out
    
            left, right = sums(nums[:h]), sorted(sums(nums[h:]))   # meet in the middle
            return sum(bisect.bisect_right(right, b - x) - bisect.bisect_left(right, a - x) for x in left)

    Common mistakes

    • Forgetting the empty subset on either side.
    • Using strict comparisons, which drops sums equal to A or B.
    • Counting in 32 bits.

    Similar problems