Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Pseudo-Polynomial Time

Why O(nW) is not polynomial, and weak versus strong NP-hardness.

Subset sum is NP-complete, yet a table decides it for a thousand numbers in a blink. There is no contradiction: the table's width is the value of the target, while the input spells that value with only about log⁡2t\log_2 t bits. Give every number 30 more bits of precision and the input grows by 30 bits per number, while the table grows about a billionfold.

What you’ll learn

  • Measure input size in bits, define pseudo-polynomial time with Max(I)\mathrm{Max}(I), and show that Θ(nW)\Theta(nW) is exponential in the length of WW but polynomial when numbers are written in unary.
  • Explain, through the reduction from 3-SAT, why subset sum is NP-complete only because its numbers may have polynomially many digits.
  • Define strong NP-hardness, prove that a strongly NP-hard problem has no pseudo-polynomial algorithm unless P = NP, and classify partition, knapsack, 3-partition and bin packing.
  • Choose between a table over weights, a table over values and meet in the middle from the sizes of the numbers, and state what fine-grained complexity says about beating Θ(nW)\Theta(nW).

Polynomial in what?

Complexity theory measures running time against the length of the input in bits. A knapsack instance with nn items whose weights, values and capacity are below 2b2^b has length L=Θ(nb)L=\Theta(nb). The table of the Optimized lesson costs Θ(nW)\Theta(nW), and with WW close to 2b2^b that is

Θ(nW)=Θ(n⋅2b)=n⋅2Θ(L/n).\Theta(nW)=\Theta(n\cdot2^{b})=n\cdot2^{\Theta(L/n)}.

One more bit in every number roughly doubles the work, while the input grows by only n+1n+1 bits. The table is fast exactly when the numbers are small, and that is a statement about their values, not about the length of the input.

Capacity WWBits to write WWColumns in the table
10310^310103+110^3+1
10610^620106+110^6+1
10910^930109+110^9+1
101810^{18}601018+110^{18}+1
Each row adds 10 bits to the input and multiplies the table by about 1,000.
Predict before you look

A subset-sum instance has n=1000n=1000 numbers and a target tt, and the bitset table has t+1t+1 columns. Every number, and the target, gets 10 more bits of precision (each becomes about 2102^{10} times larger). By about what factor does the table grow?

Show the answer

1024

The table has t+1t+1 columns, and tt grows by a factor of 210=10242^{10}=1024. The input grows by only 10×100110\times1001 bits, about 1.25 kilobytes. Ten more bits cost a thousandfold more time: exponential in the length of the numbers.

Where the hardness hides: in the digits

Subset sum is NP-complete: it is one of Karp's 21 problems (1972), where it is called KNAPSACK. So any proof that it is NP-hard must produce instances whose numbers are exponentially large in their length. If a reduction from 3-SAT produced numbers bounded by a polynomial, the Θ(nt)\Theta(nt) table would solve 3-SAT in polynomial time. The classic reduction shows where the large numbers come from.

Derivation3-SAT reduces to subset sum
  1. yi=0⋯1⋯0⏟variables  [xi∈C1]⋯[xi∈Cm]⏟clauses,zi likewise with ¬xiy_i=\underbrace{0\cdots1\cdots0}_{\text{variables}}\;\underbrace{[x_i\in C_1]\cdots[x_i\in C_m]}_{\text{clauses}},\qquad z_i\text{ likewise with }\lnot x_i

    Take a 3-CNF formula with variables x1,…,xnx_1,\dots,x_n and clauses C1,…,CmC_1,\dots,C_m. Every number has n+mn+m decimal digits: one per variable, one per clause. For each variable make two numbers, yiy_i ("xix_i true") and ziz_i ("xix_i false"), with a 1 in digit xix_i; yiy_i also has a 1 in digit CjC_j when the literal xix_i occurs in CjC_j, and ziz_i when ¬xi\lnot x_i does.

  2. t=1 1⋯1⏟n 3 3⋯3⏟mt=\underbrace{1\,1\cdots1}_{n}\ \underbrace{3\,3\cdots3}_{m}

    For each clause add two slack numbers gj=hjg_j=h_j with a single 1 in digit CjC_j. The target has a 1 in every variable digit and a 3 in every clause digit:

  3. clause column ≤3+2=5<10\text{clause column}\ \le 3+2=5<10

    No carries. A clause digit receives at most 3 from literals and 2 from slacks, at most 5 < 10, so the digits add independently. A variable digit equal to 1 forces exactly one of yi,ziy_i,z_i: a truth assignment.

  4. φ satisfiable  ⟺  ∃ S: ∑a∈Sa=t\varphi\ \text{satisfiable}\iff\exists\,S:\ \textstyle\sum_{a\in S}a=t

    Both directions. A clause digit must reach 3 and the slacks give at most 2, so at least one chosen literal is true in every clause: the assignment satisfies the formula. Conversely, a satisfying assignment gives each clause 1 to 3 true literals, and 2, 1 or 0 slacks fill the digit up to 3. So the formula is satisfiable iff some subset sums to tt.

  5. Length=O((n+m)2),t≈10 n+m\mathrm{Length}=O\big((n+m)^2\big),\qquad t\approx 10^{\,n+m}

    Sizes. There are 2n+2m2n+2m numbers of n+mn+m digits each, a polynomial length; the reduction is a polynomial-time reduction. But the target is about 10n+m10^{n+m}, so the table would have about 10n+m10^{n+m} columns: no contradiction with Θ(nt)\Theta(nt).

Numberx1x_1x2x_2x3x_3C1C_1C2C_2
y1y_110010
z1z_110001
y2y_201011
z2z_201000
y3y_300101
z3z_300110
g1=h1g_1=h_100010
g2=h2g_2=h_200001
tt11133
The formula (x1∨x2∨¬x3)∧(¬x1∨x2∨x3)(x_1\lor x_2\lor\lnot x_3)\land(\lnot x_1\lor x_2\lor x_3). The assignment "all true" picks y1+y2+y3=11122y_1+y_2+y_3=11122, and one slack per clause, g1+g2=11g_1+g_2=11, completes the target 1113311133.
Think first Subset sum is NP-complete, and it has an O(nt)O(nt) algorithm. Does that prove P = NP?

No. O(nt)O(nt) is polynomial in the value tt, which takes only about log⁡2t\log_2t bits to write. The reduction from 3-SAT produces targets near 10n+m10^{n+m}, where the table is exponentially large, so nothing follows about P versus NP. Proving P = NP this way would need an algorithm polynomial in nn and log⁡t\log t.

Strong NP-hardness

DerivationProof
  1. timeA(I) ≤ q(Length(I), Max(I))\mathrm{time}_A(I)\ \le\ q\big(\mathrm{Length}(I),\ \mathrm{Max}(I)\big)

    Let Π\Pi be strongly NP-hard with polynomial pp, and let Πp\Pi_p be its restriction to the instances with Max(I)≤p(Length(I))\mathrm{Max}(I)\le p(\mathrm{Length}(I)); by definition Πp\Pi_p is NP-hard. Suppose an algorithm AA solves Π\Pi in time bounded by a polynomial qq:

  2. timeA(I) ≤ q(Length(I), p(Length(I)))\mathrm{time}_A(I)\ \le\ q\big(\mathrm{Length}(I),\ p(\mathrm{Length}(I))\big)

    On an instance of Πp\Pi_p, substitute the bound on Max(I)\mathrm{Max}(I). What remains is a polynomial in Length(I)\mathrm{Length}(I) alone:

  3. NP⊆P\mathrm{NP}\subseteq\mathrm{P}

    So AA solves the NP-hard problem Πp\Pi_p in polynomial time. Every problem in NP reduces to Πp\Pi_p in polynomial time, hence

The canonical strongly NP-complete number problem is 3-PARTITION: given 3m3m positive integers with B/4<ai<B/2B/4<a_i<B/2 and total mBmB, can they be split into mm triples that each sum to BB? Garey and Johnson (1975) proved it NP-complete even when BB is bounded by a polynomial in mm, and it passes strong hardness on to many problems with numbers:

ProblemPseudo-polynomial algorithm?Status
Subset sum, partitionΘ(nt)\Theta(nt) table over sumsweakly NP-complete
0/1 knapsackΘ(nW)\Theta(nW) over weights, or Θ(n∑ivi)\Theta(n\sum_i v_i) over valuesweakly NP-hard
Scheduling jobs on 2 identical machines to finish earliesttable over the first machine's loadweakly NP-hard (it is partition)
The same with mm machines, mm part of the inputnone unless P = NPstrongly NP-hard (from 3-PARTITION)
Bin packing: nn items into kk bins of capacity BBnone unless P = NPstrongly NP-hard (3-PARTITION is the case k=mk=m)
TSP with integer distancesnone unless P = NPstrongly NP-hard: distances 1 and 2 encode Hamiltonian cycle
Weak or strong is a property of the problem, not of an algorithm: it says whether small numbers make the problem easy.
Check your understanding

In a bin-packing instance all item sizes and the capacity BB are integers at most n2n^2, and the number of bins kk is part of the input. Can some algorithm polynomial in nn and BB decide whether kk bins suffice?

  1. Yes: keep a table over the loads of all kk bins, as in knapsack
  2. Not unless P = NP: bin packing stays NP-hard when its numbers are polynomially bounded
  3. Yes: small numbers make every number problem easy
  4. Yes: meet in the middle over the items
Show the answer

B. Not unless P = NP: bin packing stays NP-hard when its numbers are polynomially bounded

Bin packing contains 3-PARTITION, which is NP-hard even with numbers bounded by a polynomial. An algorithm polynomial in nn and BB would solve those instances in polynomial time, so it exists only if P = NP.

The same substitution rules out fully polynomial-time approximation schemes for strongly NP-hard optimization problems whose optimal values are polynomially bounded integers: see Approximating Knapsack.

Living with large numbers

Weak NP-hardness is good news in practice: it names the feature of an instance that makes it hard. Read the constraints, see which quantity is small, and index the table by it, or pick a method that does not need a table.

What is smallMethodTime
The capacity WWTable over weights (the Optimized lesson)Θ(nW)\Theta(nW)
The total value V=∑iviV=\sum_i v_iTable over values: the least weight that reaches each total valueΘ(nV)\Theta(nV)
All weights share a factor ggDivide the weights by gg, and WW by gg rounding downΘ(nW/g)\Theta(nW/g)
The number of items, n≤40n\le40Meet in the middle: subset sums of each half, then match them (Horowitz & Sahni, 1974)O(2n/2n)O(2^{n/2}n)
Nothing, but a near-optimal answer is enoughRound the values: an FPTAS (Approximating Knapsack)polynomial in nn and 1/ε1/\varepsilon
The table over values is also the engine of the FPTAS.
python
def knapsack_by_value(weights, values, W):
    V = sum(values)
    INF = float('inf')
    least = [0] + [INF] * V              # least[q]: least weight with value exactly q
    for w, v in zip(weights, values):
        for q in range(V, v - 1, -1):    # downward: each item at most once
            least[q] = min(least[q], least[q - v] + w)
    return max(q for q in range(V + 1) if least[q] <= W)

print(knapsack_by_value([10**9, 6 * 10**8, 5 * 10**8], [7, 4, 4], 11 * 10**8))   # 8

Weights near 10910^9 would need a billion columns; total values up to 15 need 16. The two lighter items (weight 1.1×1091.1\times10^9, value 8) beat the heaviest one alone (value 7).

Key takeaways

  • Running time is measured in input bits: Θ(nW)\Theta(nW) is Θ(n 2b)\Theta(n\,2^b) for bb-bit numbers, so it is pseudo-polynomial, polynomial in Length(I)\mathrm{Length}(I) and Max(I)\mathrm{Max}(I), or in unary.
  • Subset sum, partition and knapsack are weakly NP-hard: reductions to them, like the digit construction from 3-SAT, must create exponentially large numbers.
  • A strongly NP-hard problem (3-PARTITION, bin packing, TSP) stays NP-hard with polynomially bounded numbers, so it has no pseudo-polynomial algorithm unless P = NP.
  • When WW is large, change the table (index it by value), split the search (meet in the middle) or settle for an approximation; fine-grained conjectures say Θ(nW)\Theta(nW) cannot be beaten by much for 0/1 knapsack.

Check yourself

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

Question 1

Which running time for 0/1 knapsack with nn items and capacity WW would be a genuinely polynomial-time algorithm, and so would prove P = NP?

  1. O(nW)O(nW)
  2. O(nW)O(n\sqrt W)
  3. O(n3log⁡2W)O(n^3\log^2W)
  4. O(Wlog⁡W)O(W\log W)
Show the answer

C. O(n3log⁡2W)O(n^3\log^2W)

The input length is about nlog⁡Wn\log W bits, so a bound polynomial in nn and log⁡W\log W is polynomial in the input length. Any bound that grows like a power of WW itself is exponential in the number of bits of WW.

Question 2

3-PARTITION is strongly NP-complete. Which statement follows?

  1. It has no polynomial-time algorithm, even if P = NP
  2. It has no pseudo-polynomial algorithm unless P = NP
  3. Its hard instances must contain exponentially large numbers
  4. It can be solved by a table over sums, like partition
Show the answer

B. It has no pseudo-polynomial algorithm unless P = NP

Strong NP-hardness means it stays NP-hard on instances whose numbers are bounded by a polynomial in the length. A pseudo-polynomial algorithm would run in polynomial time on those instances, and so would solve an NP-hard problem in polynomial time.

Question 3

Which of these problems is weakly NP-hard, that is, NP-hard but solvable in pseudo-polynomial time?

  1. Bin packing: can nn items be packed into kk bins of capacity BB?
  2. Partition: can the numbers be split into two groups with equal sums?
  3. 3-PARTITION
  4. The traveling salesman problem with integer distances
Show the answer

B. Partition: can the numbers be split into two groups with equal sums?

Partition is subset sum with target S/2S/2, solved in O(nS)O(nS) time by the table. The other three remain NP-hard with polynomially bounded numbers.

Question 4

Suppose someone gave a polynomial-time reduction from 3-SAT to subset sum whose numbers were all bounded by a polynomial in the formula's size. What would follow?

  1. Nothing new: the classic reduction already does that
  2. P = NP, because the O(nt)O(nt) table would then decide 3-SAT in polynomial time
  3. Subset sum would become strongly NP-hard but still in P
  4. 3-SAT would become weakly NP-hard
Show the answer

B. P = NP, because the O(nt)O(nt) table would then decide 3-SAT in polynomial time

With tt bounded by a polynomial, the table runs in polynomial time on the reduced instances, so composing the reduction with the table decides 3-SAT in polynomial time. That is why every known reduction to subset sum produces exponentially large numbers.

Further reading

  • M. R. Garey & D. S. Johnson, "'Strong' NP-completeness results: Motivation, examples, and implications," Journal of the ACM 25(3) (1978), 499–508.
  • M. R. Garey & D. S. Johnson, Computers and Intractability: A Guide to the Theory of NP-Completeness (Freeman, 1979), §4.2, "Number problems and strong NP-completeness".
  • R. M. Karp, "Reducibility among combinatorial problems," in Complexity of Computer Computations (Plenum, 1972), 85–103.
  • M. Cygan, M. Mucha, K. Węgrzycki & M. Włodarczyk, "On problems equivalent to (min,+)-convolution," ACM Transactions on Algorithms (2019); ICALP 2017.
  • C. Jin, "0-1 Knapsack in nearly quadratic time," STOC 2024.