TExcelTAD

Subset Sum

Given a set of positive integers and a target tt, is there a subset that adds up to exactly tt? Subset sum is the simplest NP-complete problem about numbers, and the source of hardness for knapsack, partition, bin packing and scheduling with deadlines. Its NP-completeness proof is a lovely reduction from 3-CNF-SAT in which decimal digits play the role of gadgets. It also has a dynamic program that runs in O(nt)O(nt) time, which seems to contradict the hardness until one remembers what input size means.

The problem

SUBSET-SUM={⟨S,t⟩:some S′⊆S has ∑s∈S′s=t},\text{SUBSET-SUM} = \Bigl\{ \langle S, t \rangle : \text{some } S' \subseteq S \text{ has } \sum_{s \in S'} s = t \Bigr\},

with the numbers written in binary. It is in NP: the certificate is the subset S′S', and adding it up takes polynomial time.

3-CNF-SAT reduces to SUBSET-SUM

Let ϕ\phi have variables x1,…,xnx_1, \ldots, x_n and clauses C1,…,CkC_1, \ldots, C_k; assume no clause contains both a variable and its negation. Build numbers with n+kn + k decimal digits, one digit per variable followed by one digit per clause:

  • For each variable xix_i, two numbers viv_i and vi′v_i'. Both have a 1 in digit xix_i. In the clause digits, viv_i has a 1 in digit CjC_j if the literal xix_i occurs in CjC_j, and vi′v_i' has a 1 there if ¬xi\lnot x_i occurs in CjC_j. All other digits are 0.
  • For each clause CjC_j, two slack numbers sjs_j and sj′s_j' with a 1, respectively a 2, in digit CjC_j and zeros elsewhere.
  • The target tt has a 1 in every variable digit and a 4 in every clause digit.

No digit position can overflow: a variable digit receives at most 2 (from viv_i and vi′v_i'), and a clause digit at most 3 from the literal numbers and 3 from its slacks, at most 6. So there are no carries in base 10, and a sum can be checked digit by digit.

Proof that $\phi$ is satisfiable iff some subset sums to $t$

(⇒\Rightarrow) Given a satisfying assignment, take viv_i if xix_i is true and vi′v_i' otherwise. Each variable digit sums to 1. Clause digit CjC_j receives one unit for each true literal of CjC_j, between 1 and 3. Add slack numbers to reach exactly 4: sj′s_j' and sjs_j if it is 1, sj′s_j' if it is 2, sjs_j if it is 3.

(⇐\Leftarrow) A subset summing to tt must contain exactly one of vi,vi′v_i, v_i' for each ii (digit xix_i is 1 and no carries arrive). Set xix_i true if viv_i is chosen. The slacks contribute at most 3 to digit CjC_j, so at least one literal number contributes to it: some literal of CjC_j is true under the assignment. So every clause is satisfied.

There are 2n+2k2n + 2k numbers of n+kn + k digits, so the instance is built in polynomial time and SUBSET-SUM is NP-complete. The program builds the instance for a small formula, prints the numbers in a digit table and confirms by brute force over all subsets that the reduction preserves satisfiability, on this formula and on random ones.

python · try it yourself
import random
from itertools import product, combinations

def reduce(phi, n):
    """phi: clauses of literals (+i / -i, variables 1..n); returns (named numbers, target)"""
    k = len(phi)
    digits = lambda d: int("".join(map(str, d)))
    nums = []
    for i in range(1, n + 1):
        for sign, name in [(1, f"v{i}"), (-1, f"v{i}'")]:
            d = [1 if j == i - 1 else 0 for j in range(n)] + [1 if sign * i in c else 0 for c in phi]
            nums.append((name, digits(d)))
    for j in range(k):
        for val, name in [(1, f"s{j + 1}"), (2, f"s{j + 1}'")]:
            nums.append((name, digits([0] * n + [val if jj == j else 0 for jj in range(k)])))
    return nums, digits([1] * n + [4] * k)

def subset_sum(values, t):
    return any(sum(c) == t for r in range(len(values) + 1) for c in combinations(values, r))

def satisfiable(phi, n):
    return any(all(any(a[abs(l) - 1] == (l > 0) for l in c) for c in phi) for a in product([False, True], repeat=n))

phi = [[1, -2, 3], [-1, 2, 3], [-1, -2, -3]]
nums, t = reduce(phi, 3)
width = len(str(t))
print("        x1 x2 x3 C1 C2 C3")
for name, v in nums:
    print(f"{name:6}  " + "  ".join(str(v).zfill(width)))
print("target  " + "  ".join(str(t)))
print("phi satisfiable:", satisfiable(phi, 3), " subset sums to t:", subset_sum([v for _, v in nums], t))

rng = random.Random(10)
agree = 0
for trial in range(40):
    n = 3
    phi = []
    while len(phi) < rng.randint(2, 4):
        vs = rng.sample(range(1, n + 1), 3)
        phi.append([v * rng.choice([1, -1]) for v in vs])
    nums, t = reduce(phi, n)
    agree += satisfiable(phi, n) == subset_sum([v for _, v in nums], t)
print("random formulas where both answers agree:", agree, "of 40")
        x1 x2 x3 C1 C2 C3
v1      1  0  0  1  0  0
v1'     1  0  0  0  1  1
v2      0  1  0  0  1  0
v2'     0  1  0  1  0  1
v3      0  0  1  1  1  0
v3'     0  0  1  0  0  1
s1      0  0  0  1  0  0
s1'     0  0  0  2  0  0
s2      0  0  0  0  1  0
s2'     0  0  0  0  2  0
s3      0  0  0  0  0  1
s3'     0  0  0  0  0  2
target  1  1  1  4  4  4
phi satisfiable: True  subset sums to t: True
random formulas where both answers agree: 40 of 40

The pseudo-polynomial dynamic program

Keep the set of reachable sums, a Boolean array R[0..t]R[0..t], and add the numbers one by one: after processing ss, a sum xx is reachable if it was before or x−sx - s was. This is the 0/1 knapsack DP with values equal to weights (0/1 Knapsack and Pseudo-Polynomial Time): O(nt)O(nt) time and O(t)O(t) space.

text
SUBSET-SUM-DP(S, t)
1  R[0] = true; R[1 .. t] = false
2  for each s in S
3      for x = t downto s               // downward: each number used at most once
4          R[x] = R[x] or R[x - s]
5  return R[t]

This does not prove P = NP. The input encodes tt in about lg⁡t\lg t bits, so O(nt)O(nt) is exponential in the input length. The instances produced by the reduction above show it concretely: their target has n+kn + k decimal digits, so t≈10n+kt \approx 10^{n + k}, and the DP table would be astronomically long. Subset sum is weakly NP-complete: hard only when the numbers are large. When the numbers are bounded by a polynomial in nn, the DP is polynomial.

python · try it yourself
def subset_sum_dp(S, t):
    R = [True] + [False] * t
    cells = 0
    for s in S:
        for x in range(t, s - 1, -1):
            R[x] = R[x] or R[x - s]
            cells += 1
    return R[t], cells

print(subset_sum_dp([3, 34, 4, 12, 5, 2], 9))
print(subset_sum_dp([3, 34, 4, 12, 5, 2], 30))
for n_vars, k in [(3, 3), (5, 8), (10, 20)]:
    t = int("1" * n_vars + "4" * k)
    print(f"reduction from {n_vars} variables and {k} clauses: t has {len(str(t))} digits, "
          f"DP would need about {2 * (n_vars + k)} * {t:.1e} cells")
(True, 26)
(False, 129)
reduction from 3 variables and 3 clauses: t has 6 digits, DP would need about 12 * 1.1e+05 cells
reduction from 5 variables and 8 clauses: t has 13 digits, DP would need about 26 * 1.1e+12 cells
reduction from 10 variables and 20 clauses: t has 30 digits, DP would need about 60 * 1.1e+29 cells

The other classic exact method, meet in the middle (Horowitz and Sahni, 1974), splits SS into two halves, lists all 2n/22^{n/2} subset sums of each, sorts one list and looks up t−xt - x for every xx of the other: O(2n/2n)O(2^{n/2} n) time, independent of the size of the numbers.

In C++

The DP in C++ with a std::vector<bool>, including the reconstruction of one subset: remember, for each sum, which number first reached it.

cpp · try it yourself
#include <cstdio>
#include <vector>

int main() {
    std::vector<int> S = {14, 27, 9, 33, 41, 6, 18, 23};
    int t = 100;
    std::vector<int> first(t + 1, -1);         // index of the number that first reached this sum
    std::vector<bool> R(t + 1, false);
    R[0] = true;
    for (int i = 0; i < (int)S.size(); i++)
        for (int x = t; x >= S[i]; x--)
            if (!R[x] && R[x - S[i]]) { R[x] = true; first[x] = i; }
    if (!R[t]) { std::printf("no subset sums to %d\n", t); return 0; }
    std::printf("subset summing to %d:", t);
    for (int x = t; x > 0; x -= S[first[x]]) std::printf(" %d", S[first[x]]);
    std::printf("\n");
    int reachable = 0;
    for (bool r : R) reachable += r;
    std::printf("%d of the sums 0..%d are reachable\n", reachable, t);
}
subset summing to 100: 18 41 27 14
68 of the sums 0..100 are reachable

The walk back works because first[x] is set only once, by the first number ii that made xx reachable, and then x−Six - S_i was reachable using numbers before ii only, so the walk never reuses a number. Practise with Subset Sum.

Test yourself

In the reduction from 3-CNF-SAT, why are the slack numbers 11 and 22 for each clause digit?

  1. To make the numbers distinct
  2. So that any clause digit with 1, 2 or 3 true literals can be topped up to exactly 4, but a digit with 0 true literals cannot
  3. To avoid carries into the variable digits
  4. Because clauses have two literals

Why can the reduction's sums be checked digit by digit?

  1. Because the numbers are prime
  2. Because every digit position sums to at most 6, so no carries occur in base 10
  3. Because the target is a power of 10
  4. Because there are few numbers

The DP for subset sum runs in O(nt)O(nt) time. Why does that not show P = NP?

  1. Because the DP is wrong for large tt
  2. Because tt can be exponential in the number of bits of the input
  3. Because nn can be large
  4. Because the DP needs a sorted input

What is the running time of the meet-in-the-middle algorithm for subset sum?

  1. O(nt)O(nt)
  2. O(2n/2n)O(2^{n/2} n)
  3. O(2n)O(2^n)
  4. O(n2)O(n^2)