Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

Subset Sum, Faster

Bitset DP, and near-linear pseudo-polynomial algorithms.

Bellman's table answers "does some subset of nn numbers sum to tt?" in O(nt)O(nt) time, and for sixty years that looked like the end of the story. In 2017 two papers broke it, one reaching O~(n+t)\tilde O(n+t), and soon after a lower bound based on the Strong Exponential Time Hypothesis showed that the dependence on tt cannot be improved much further.

What you’ll learn

  • Run the subset-sum table as shifts and ORs of a bitset, prove its invariant, and count its cost: O(nt/w)O(nt/w) word operations on a word RAM.
  • Compute all subset sums up to tt with sumsets and the FFT, and analyze the divide and conquer behind the O~(σ)\tilde O(\sigma) bound.
  • Explain the ideas of the O~(n+t)\tilde O(n+t) algorithms (color coding; power series) and state the SETH-based lower bound that rules out t1−ε2o(n)t^{1-\varepsilon}2^{o(n)}.
  • Solve subset sum with huge numbers in O∗(2n/2)O^*(2^{n/2}) time by meet in the middle and in O∗(2n/4)O^*(2^{n/4}) space by Schroeppel and Shamir, and say what is open below 2n/22^{n/2}.

Bellman's table as a bitset

Let Ri⊆{0,…,t}R_i\subseteq\{0,\dots,t\} be the set of sums of subsets of the first ii numbers that are at most tt, stored as a bit vector of length t+1t+1 (bit ss set iff s∈Ris\in R_i). Bellman's recurrence (1957) is one line of bit operations:

R0={0},Ri=(Ri−1 ∪ (Ri−1+ai−1))∩[0,t]⟺R ← (R ∣ (R≪a)) & mask.R_0=\{0\},\qquad R_i=\big(R_{i-1}\ \cup\ (R_{i-1}+a_{i-1})\big)\cap[0,t]\quad\Longleftrightarrow\quad R\ \leftarrow\ \big(R\ \mathtt{|}\ (R\ll a)\big)\ \&\ \mathrm{mask}.

Invariant: a subset of the first ii numbers either avoids ai−1a_{i-1} (its sum is in Ri−1R_{i-1}) or contains it (its sum is ai−1a_{i-1} more than a sum in Ri−1R_{i-1}). On a word RAM with ww-bit words, shifting and ORing a (t+1)(t+1)-bit vector costs ⌈(t+1)/w⌉\lceil (t+1)/w\rceil word operations, so the whole table costs O(n t/w)O(n\,t/w): the same cells, 64 at a time (word-parallelism).

cpp
#include <bitset>
#include <cstdio>
#include <vector>

const int MAXT = 100000;                     // largest target, fixed at compile time

bool subset_sum(const std::vector<int>& a, int t) {
    std::bitset<MAXT + 1> reach;             // reach[s] == 1 <=> some subset sums to s
    reach[0] = 1;
    for (int x : a) reach |= reach << x;     // bits shifted past MAXT are dropped
    return reach[t];
}

int main() {
    printf("%d %d\n", subset_sum({2, 3, 7}, 12), subset_sum({2, 3, 7}, 11));   // 1 0
}

The contest idiom: std::bitset packs the table into 64-bit words, so n=1000n=1000 and t=105t=10^5 cost about 1.6×1061.6\times10^6 word operations.

Predict before you look

With n=1000n=1000 numbers, target t=106t=10^6 and 64-bit words, about how many million word operations does the bitset table perform?

Show the answer

15.6

n⋅t/64=103⋅106/64≈1.56×107n\cdot t/64=10^3\cdot10^6/64\approx1.56\times10^7, about 15.6 million: a fraction of a second, against 10910^9 cell updates for the plain table. It is still pseudo-polynomial: dividing by 64 is a constant factor.

Sumsets and the FFT

Write Σ(A)\Sigma(A) for the set of all subset sums of a multiset AA, and X+Y={x+y:x∈X, y∈Y}X+Y=\{x+y: x\in X,\ y\in Y\} for the sumset. If AA and BB are disjoint, every subset of A∪BA\cup B is a subset of AA plus a subset of BB, so

Σ(A∪B)=Σ(A)+Σ(B).\Sigma(A\cup B)=\Sigma(A)+\Sigma(B).

A sumset is a convolution in disguise: for X,Y⊆[0,u]X,Y\subseteq[0,u], multiply the polynomials ∑x∈Xzx\sum_{x\in X}z^x and ∑y∈Yzy\sum_{y\in Y}z^y; the exponents with nonzero coefficients are exactly X+YX+Y. With the FFT (see The Fast Fourier Transform) that takes O(ulog⁡u)O(u\log u) time, however large XX and YY are.

text
ALL-SUMS(A, u):                      # every subset sum of the multiset A that is at most u
    if |A| = 1: return {0, a} ∩ [0, u]          # A = {a}
    split A into two halves A1, A2
    S1 ← ALL-SUMS(A1, min(u, sum(A1)))
    S2 ← ALL-SUMS(A2, min(u, sum(A2)))
    return SUMSET(S1, S2) ∩ [0, u]      # FFT of two 0/1 vectors of length ≤ min(u, sum(A)) + 1

Call ALL-SUMS(A, t). Every number is positive, so sums above the cap can be dropped at every level.

DerivationWhy the caps make it Õ(σ)
  1. ∑jmin⁡ ⁣(u, ∑Aj) ≤ σ\sum_{j}\min\!\big(u,\ \textstyle\sum A_j\big)\ \le\ \sigma

    Let σ=∑iai\sigma=\sum_ia_i. At recursion depth dd the subproblems partition AA, and each one's cap is at most the sum of its own items, so the caps at one depth add up to at most σ\sigma:

  2. T(A)=O(σlog⁡σlog⁡n)=O~(σ)T(A)=O(\sigma\log\sigma\log n)=\tilde O(\sigma)

    An FFT on vectors of length cc costs O(clog⁡c)O(c\log c), so one depth costs O(σlog⁡σ)O(\sigma\log\sigma), and there are ⌈log⁡2n⌉\lceil\log_2n\rceil depths:

  3. O~(min⁡{n t, t4/3, σ})\tilde O\big(\min\{\sqrt n\,t,\ t^{4/3},\ \sigma\}\big)

    With the cap tt at every call instead, depth dd would cost 2d⋅tlog⁡t2^d\cdot t\log t, and the total would grow to O(ntlog⁡t)O(nt\log t), worse than the bitset. Koiliaris and Xu (SODA 2017; journal version 2019) combined sumset recursions of this kind with further ideas to obtain a deterministic algorithm for all subset sums up to tt:

Near-linear time, and a matching lower bound

Two randomized algorithms reach O~(n+t)\tilde O(n+t), near-linear in the length of one row of Bellman's table.

  • Bringmann (SODA 2017) groups the numbers into layers by size. A subset with sum at most tt contains fewer than 2j+12^{j+1} numbers larger than t/2j+1t/2^{j+1}, so only few large numbers can be used together. Inside a layer he uses color coding: a random partition of the numbers into groups in which, with good probability, the numbers of a fixed solution land in different groups. Each group then contributes at most one number, and the work reduces to sumsets of short lists with small caps. The error is one-sided: a "yes" is always correct.
  • Jin and Wu (SOSA 2019) count instead of deciding, with a generating function and power-series arithmetic modulo a prime.
DerivationJin and Wu: subset sums by a logarithm and an exponential
  1. P(x)=∏i=0n−1(1+xai)=∑sNs xsP(x)=\prod_{i=0}^{n-1}\big(1+x^{a_i}\big)=\sum_{s}N_s\,x^s

    The coefficient of xsx^s in this product counts the subsets with sum ss:

  2. ln⁡P(x)=∑iln⁡(1+xai)=∑i∑k≥1(−1)k+1k xkai\ln P(x)=\sum_{i}\ln\big(1+x^{a_i}\big)=\sum_{i}\sum_{k\ge1}\frac{(-1)^{k+1}}{k}\,x^{k a_i}

    Take logarithms. The product becomes a sum, and each factor has a sparse series:

  3. ∑v=1t⌊tv⌋ ≤ t∑v=1t1v=O(tlog⁡t)\sum_{v=1}^{t}\Big\lfloor\frac tv\Big\rfloor\ \le\ t\sum_{v=1}^{t}\frac1v=O(t\log t)

    Only exponents up to tt matter. Group equal values: cvc_v copies of vv contribute cvc_v times the series of vv, which has ⌊t/v⌋\lfloor t/v\rfloor terms. Over the distinct values that is O(tlog⁡t)O(t\log t) terms in all, by the harmonic series:

  4. P≡exp⁡(ln⁡P)(modxt+1, p)⟹O~(n+t) time, one-sided errorP\equiv\exp(\ln P)\pmod{x^{t+1},\ p}\qquad\Longrightarrow\qquad\tilde O(n+t)\ \text{time, one-sided error}

    Exponentiate the truncated series with Newton's method in O~(t)\tilde O(t) arithmetic operations, working modulo a random prime p>tp>t so that dividing by k≤tk\le t is allowed. If Nt≢0(modp)N_t\not\equiv0\pmod p, some subset sums to tt. If Nt≠0N_t\ne0, it is at most 2n2^n, so it has at most nn prime factors, and a random prime from a large enough range rarely divides it.

The proof is a reduction from kk-SAT that encodes a formula into the digits of subset-sum instances. A corollary is a "direct-OR" theorem: deciding whether at least one of NN instances with target tt is a yes-instance takes (Nt)1−o(1)(Nt)^{1-o(1)} time under SETH, so batching instances does not help. The same paper shows that a classic pseudo-polynomial algorithm for bicriteria shortest paths (Joksch, 1966) is essentially optimal.

Check your understanding

Which of these algorithms for subset sum would refute SETH, according to this theorem?

  1. An O(n+tlog⁡2t)O(n+t\log^2t) algorithm
  2. An O(t0.99⋅n100)O(t^{0.99}\cdot n^{100}) algorithm
  3. An O(2n/2)O(2^{n/2}) algorithm
  4. An O(nt/64)O(nt/64) bitset algorithm
Show the answer

B. An O(t0.99⋅n100)O(t^{0.99}\cdot n^{100}) algorithm

n100=2100log⁡2nn^{100}=2^{100\log_2n} is 2o(n)2^{o(n)}, so t0.99n100t^{0.99}n^{100} has the forbidden form t1−ε2o(n)t^{1-\varepsilon}2^{o(n)} with ε=0.01\varepsilon=0.01. The other three are already known, or consistent with the bound.

When the numbers are huge

If the numbers have about nn bits, every pseudo-polynomial bound is exponential, and the question becomes how far below 2n2^n one can go.

Meet in the middle (Horowitz & Sahni, 1974): split the numbers into halves and list the 2n/22^{n/2} subset sums of each half in sorted order (adding one number to a sorted list LL is a merge of LL and L+aL+a, so this costs O(2n/2)O(2^{n/2}) in all). Then walk the two lists with two pointers, one ascending and one descending, looking for a pair that sums to tt. Time and space O(2n/2)O(2^{n/2}); see Meet in the Middle.

Schroeppel and Shamir (1981) keep the time and cut the space. Split the numbers into quarters with sorted lists L1,…,L4L_1,\dots,L_4 of 2n/42^{n/4} sums each, generate the 2n/22^{n/2} sums of L1+L2L_1+L_2 in increasing order with a min-heap that holds one candidate per element of L1L_1, and those of L3+L4L_3+L_4 in decreasing order with a max-heap. The two-pointer walk then runs over these virtual lists: O∗(2n/2)O^*(2^{n/2}) time and O∗(2n/4)O^*(2^{n/4}) space.

SettingBest knownSource
Worst case, timeO∗(2n/2)O^*(2^{n/2})Horowitz & Sahni (1974)
Worst case, space with time O∗(2n/2)O^*(2^{n/2})O∗(2n/4)O^*(2^{n/4}), then O∗(20.249999n)O^*(2^{0.249999n}) (randomized)Schroeppel & Shamir (1981); Nederlof & Węgrzycki (STOC 2021)
Random instances with t≈2nt\approx2^n (density about 1)about 20.291n2^{0.291n}, heuristicBecker, Coron & Joux (2011), after Howgrave-Graham & Joux (2010)
Small ttO~(n+t)\tilde O(n+t), randomizedBringmann (2017); Jin & Wu (2019)
O∗O^* hides polynomial factors. The algorithms for random instances use the representation technique: a solution can be split into two halves in many ways, so it is enough to find one of them.

Key takeaways

  • The subset-sum table is a bitset: R←R ∣ (R≪a)R\leftarrow R\,|\,(R\ll a) for each number, O(nt/w)O(nt/w) word operations; folding duplicates leaves O(S)O(\sqrt S) numbers when the total SS is small.
  • Subset sums of disjoint parts combine by sumsets, which the FFT computes in O(ulog⁡u)O(u\log u); divide and conquer with caps gives O~(σ)\tilde O(\sigma), and Koiliaris and Xu reach O~(n t)\tilde O(\sqrt n\,t) deterministically.
  • Randomized O~(n+t)\tilde O(n+t) algorithms exist (Bringmann 2017; Jin & Wu 2019), and under SETH no algorithm runs in t1−ε2o(n)t^{1-\varepsilon}2^{o(n)}: near-linear in tt is the end of the road.
  • With huge numbers, meet in the middle runs in O∗(2n/2)O^*(2^{n/2}) and Schroeppel–Shamir cuts the space to O∗(2n/4)O^*(2^{n/4}); beating 2n/22^{n/2} in the worst case is open.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

The bitset table runs in O(nt/w)O(nt/w) word operations. Why is it still not a polynomial-time algorithm for subset sum?

  1. Because ww is a constant, and ntnt is exponential in the number of bits of tt
  2. Because shifting a bitset costs O(t)O(t) per bit
  3. Because the table needs nn rows of tt bits
  4. It is polynomial on the word RAM, where words have log⁡t\log t bits
Show the answer

A. Because ww is a constant, and ntnt is exponential in the number of bits of tt

Word parallelism divides the work by ww, typically 64 or about log⁡t\log t, which is far from enough: tt itself is exponential in its length, so nt/wnt/w is too. The bitset is a constant-factor (or logarithmic) speedup of a pseudo-polynomial algorithm.

Question 2

What does the SETH-based lower bound of Abboud, Bringmann, Hermelin and Shabtay say about subset sum?

  1. No algorithm runs in O(nt)O(nt) time
  2. No algorithm runs in O~(n+t)\tilde O(n+t) time
  3. The dependence on tt cannot be lowered to t1−εt^{1-\varepsilon}, even with any 2o(n)2^{o(n)} factor, so O~(n+t)\tilde O(n+t) is optimal up to subpolynomial factors
  4. Subset sum needs 2n/22^{n/2} time on every instance
Show the answer

C. The dependence on tt cannot be lowered to t1−εt^{1-\varepsilon}, even with any 2o(n)2^{o(n)} factor, so O~(n+t)\tilde O(n+t) is optimal up to subpolynomial factors

Under SETH there is no t1−ε2o(n)t^{1-\varepsilon}2^{o(n)} algorithm for any ε>0\varepsilon>0. Bringmann's randomized O~(n+t)\tilde O(n+t) algorithm is consistent with this, and matches it up to subpolynomial factors.

Question 3

You must solve subset sum for n=50n=50 numbers of 80 bits each, exactly. Which approach is feasible?

  1. The bitset table over sums up to tt
  2. Bringmann's O~(n+t)\tilde O(n+t) algorithm
  3. Meet in the middle: about 3.4×1073.4\times10^7 sums per half, then match them
  4. Brute force over all 2502^{50} subsets
Show the answer

C. Meet in the middle: about 3.4×1073.4\times10^7 sums per half, then match them

225≈3.4×1072^{25}\approx3.4\times10^7 sums per half, generated in sorted order and matched with two pointers: a few hundred million simple steps. Every pseudo-polynomial method pays for t≈280t\approx2^{80}.

Further reading

  • K. Bringmann, "A near-linear pseudopolynomial time algorithm for subset sum," SODA 2017.
  • K. Koiliaris & C. Xu, "Faster pseudopolynomial time algorithms for subset sum," ACM Transactions on Algorithms 15(3) (2019); SODA 2017.
  • C. Jin & H. Wu, "A simple near-linear pseudopolynomial time randomized algorithm for subset sum," SOSA 2019.
  • A. Abboud, K. Bringmann, D. Hermelin & D. Shabtay, "SETH-based lower bounds for subset sum and bicriteria path," ACM Transactions on Algorithms 18(1) (2022); SODA 2019.
  • R. Schroeppel & A. Shamir, "A T=O(2n/2)T=O(2^{n/2}), S=O(2n/4)S=O(2^{n/4}) algorithm for certain NP-complete problems," SIAM Journal on Computing 10(3) (1981), 456–464.