Subset Sum
Given a set of positive integers and a target , is there a subset that adds up to exactly ? 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 time, which seems to contradict the hardness until one remembers what input size means.
The problem
with the numbers written in binary. It is in NP: the certificate is the subset , and adding it up takes polynomial time.
3-CNF-SAT reduces to SUBSET-SUM
Let have variables and clauses ; assume no clause contains both a variable and its negation. Build numbers with decimal digits, one digit per variable followed by one digit per clause:
- For each variable , two numbers and . Both have a 1 in digit . In the clause digits, has a 1 in digit if the literal occurs in , and has a 1 there if occurs in . All other digits are 0.
- For each clause , two slack numbers and with a 1, respectively a 2, in digit and zeros elsewhere.
- The target 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 and ), 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$
() Given a satisfying assignment, take if is true and otherwise. Each variable digit sums to 1. Clause digit receives one unit for each true literal of , between 1 and 3. Add slack numbers to reach exactly 4: and if it is 1, if it is 2, if it is 3.
() A subset summing to must contain exactly one of for each (digit is 1 and no carries arrive). Set true if is chosen. The slacks contribute at most 3 to digit , so at least one literal number contributes to it: some literal of is true under the assignment. So every clause is satisfied.
There are numbers of 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.
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 , and add the numbers one by one: after processing , a sum is reachable if it was before or was. This is the 0/1 knapsack DP with values equal to weights (0/1 Knapsack and Pseudo-Polynomial Time): time and space.
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 in about bits, so is exponential in the input length. The instances produced by the reduction above show it concretely: their target has decimal digits, so , 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 , the DP is polynomial.
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 into two halves, lists all subset sums of each, sorts one list and looks up for every of the other: 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.
#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 that made reachable, and then was reachable using numbers before 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 and for each clause digit?
- To make the numbers distinct
- 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
- To avoid carries into the variable digits
- Because clauses have two literals
Why can the reduction's sums be checked digit by digit?
- Because the numbers are prime
- Because every digit position sums to at most 6, so no carries occur in base 10
- Because the target is a power of 10
- Because there are few numbers
The DP for subset sum runs in time. Why does that not show P = NP?
- Because the DP is wrong for large
- Because can be exponential in the number of bits of the input
- Because can be large
- Because the DP needs a sorted input
What is the running time of the meet-in-the-middle algorithm for subset sum?