Bit Manipulation · Pattern 5 of 6

Sum over subsets (SOS) DP

For every mask, add up the values stored at all of its submasks. Handling one bit at a time does this in O(B · 2^B) instead of O(3^B), and it answers "how many items fit inside this mask?" for every mask at once.

1 variation · 1 problem

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Values are small (under 2^16 or 2^20), so you can index an array by them
  • Count pairs or triples whose AND (or OR) is zero
  • For each mask, a sum or count over all its submasks or supermasks

The template

Sum over Subsets (SOS) DP
// f[mask] becomes the sum of the original f[sub] over every submask sub of mask
int[] subsetSums(int[] f, int bits) {
    for (int b = 0; b < bits; b++)
        for (int mask = 0; mask < (1 << bits); mask++)
            if ((mask & (1 << b)) != 0) f[mask] += f[mask ^ (1 << b)];   // add the side without bit b
    return f;
}

int countTriplets(int[] nums) {             // ordered (i, j, k) with nums[i] & nums[j] & nums[k] == 0
    int bits = 16, full = (1 << bits) - 1;
    int[] f = new int[1 << bits];
    for (int a : nums) for (int b : nums) f[a & b]++;   // pairs grouped by their AND
    subsetSums(f, bits);
    int res = 0;
    for (int c : nums) res += f[full & ~c];  // the pair AND must avoid every bit of c
    return res;
}

The variations

  1. 1Count items that fit inside a mask

    x & c == 0 means x is a submask of the complement of c. Count every pair by its AND, run SOS once so each mask knows how many pair ANDs fit inside it, then each third number is one lookup at full & ~c.

Mistakes to avoid

  • Putting the mask loop outside the bit loop: each bit must be fully processed before the next, or submasks get counted more than once.
  • Forgetting full & ~c: ~c alone is negative and is not a valid index.
  • Picking bits too small for the values, so some values index past the array.
Next: Bits meet number theory: gcd and powers of two →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.