Sub topic 17
Pseudo-Polynomial Time and Subset Sum
This chapter assumes you already know three things from earlier chapters: Subset Sum is NP-complete, a polynomial-time algorithm runs in time bounded by a polynomial in the input size, and a reduction carries hardness from one problem to another. You should also be comfortable reading Big-O bounds and short Python functions.
Subset Sum looks like a contradiction at first. It is NP-complete, yet a short dynamic program solves it in O(n · T) time, where n is the count of numbers and T is the target. That bound looks polynomial. If it were, P would equal NP. The way out is to be precise about what "input size" means.
Input Size Is Measured in Bits
A running time is polynomial only if it is bounded by a polynomial in the length of the input encoding, the number of bits needed to write the instance down. For most graph problems this detail rarely matters, because a graph with V vertices and E edges takes roughly V + E symbols to write.
Numbers behave differently. Writing the integer T in binary takes about b = log₂(T) bits. The value of T is about 2^b. A loop that runs T times therefore runs about 2^b times, which is exponential in the bit length of T.
An algorithm is pseudo-polynomial if its running time is polynomial in the input length and in the numeric value of the largest number in the input, but not necessarily polynomial in the input length alone.
The Dynamic Program
The algorithm keeps a Boolean table reachable, where reachable[s] is true when some subset of the numbers seen so far sums to s. Each new number x can extend every sum already reachable by x.
def subset_sum_dp(numbers, target):
"""numbers: non-negative integers; target: non-negative integer."""
reachable = [False] * (target + 1)
reachable[0] = True
for x in numbers:
for s in range(target, x - 1, -1):
if reachable[s - x]:
reachable[s] = True
return reachable[target]
print(subset_sum_dp([3, 34, 4, 12, 5, 2], 9)) # True (4 + 5)
print(subset_sum_dp([3, 34, 4, 12, 5, 2], 30)) # False (without 34 the max is 26)
print(subset_sum_dp([], 0)) # True (the empty subset)The inner loop runs from high sums down to low ones. That order matters. If it ran upward, reachable[s - x] might already have been set during the same pass over x, and the algorithm would reuse x more than once. That would solve the unbounded variant, a different problem.
The outer loop runs n times and the inner loop at most T + 1 times, so the time is O(n · T) and the memory is O(T).
Common errors
- Counting T as size. Saying "O(n · T) is polynomial" treats T as if it were the length of the input. It is the value of one input field.
- Ascending inner loop. As explained above, this silently allows repeated use of an element.
- Negative inputs. With negative numbers,
s - xcan exceedtargetor index from the end of a Python list without raising an error. You need an offset table that covers the range from the sum of negatives to the sum of positives. - Huge targets. The list has T + 1 entries. A 40-bit target needs about a trillion Booleans, so memory runs out long before time does.
Watching the Exponential Appear
Hold n fixed and let the target grow by bits:
| Bits in T | Table cells (≈ T) | Practical? |
|---|---|---|
| 8 | 256 | Instant |
| 16 | 65,536 | Instant |
| 32 | about 4.3 × 10⁹ | Gigabytes of memory, slow |
| 64 | about 1.8 × 10¹⁹ | Impossible |
Adding one bit to T adds one symbol to the input but doubles the work. That is the signature of exponential time. In the other direction, when the numbers in an instance are small, for example below a million, the algorithm is fast in practice even with thousands of items. Instances that come from real scheduling or budgeting often have small integers like this.
Weak and Strong NP-Completeness
Pseudo-polynomial algorithms divide NP-complete problems with numbers into two groups.
- A problem is weakly NP-complete if it is NP-complete but has a pseudo-polynomial algorithm. Subset Sum, Partition, and 0/1 Knapsack are weakly NP-complete.
- A problem is strongly NP-complete if it stays NP-complete even when every number in the instance is bounded by a polynomial in the input length. Equivalently, it stays NP-complete when numbers are written in unary, where the value 7 is written as seven marks. Examples include 3-Partition, Bin Packing, and the decision version of the Traveling Salesperson Problem.
The unary view explains the difference. If Subset Sum's numbers are written in unary, the input length is at least T, so O(n · T) becomes polynomial in the input length and that version is in P. For a strongly NP-complete problem, a pseudo-polynomial algorithm would solve the unary version in polynomial time, which would put an NP-complete problem in P. So strongly NP-complete problems have no pseudo-polynomial algorithm unless P = NP.
Problems that contain no numbers at all, such as 3-SAT, Vertex Cover, and 3-Coloring, are strongly NP-complete automatically. Their hardness does not depend on large magnitudes.
Why the Distinction Pays Off
Pseudo-polynomial algorithms lead to practical tools. For 0/1 Knapsack, the same table idea indexed by profit gives a fully polynomial-time approximation scheme (FPTAS). The scheme rounds the profits down to fewer significant bits, which shrinks the table, and then runs the exact pseudo-polynomial algorithm on the rounded profits. The result is within a factor (1 − ε) of optimal, in time polynomial in both n and 1/ε. Strongly NP-hard problems cannot have an FPTAS unless P = NP, so whether a problem is weakly or strongly NP-complete tells you which approximation results are possible. The final chapter covers coping strategies in more detail.
A rule of thumb for engineers: when an NP-complete problem's only source of difficulty is large integers, check the magnitudes in your real data first. If they are small, or can be scaled down without much loss, an exact or near-exact pseudo-polynomial method may be enough.
Exercise
Subset Sum has an O(n · T) algorithm. Explain in one or two sentences why this does not place Subset Sum in P.
Show answer
The input encodes T in about log₂(T) bits, so O(n · T) equals O(n · 2^b) for a b-bit target. That is exponential in the input length, and polynomial time is measured against input length, not numeric value.
Exercise
An instance has n = 200 numbers and target T = 5,000,000. Roughly how many inner-loop steps does subsetsumdp perform, and is that practical?
Show answer
About n · T = 200 × 5,000,000 = 10⁹ steps. That takes minutes in pure Python and seconds in compiled code or with NumPy, and the table holds about 5 million entries, so it is practical.
Exercise
What goes wrong if the inner loop is written as for s in range(x, target + 1) instead of iterating downward? Give a concrete input where the answer changes.
Show answer
Ascending order lets the same number be used repeatedly within one pass. With numbers [3] and target 6, the ascending loop sets reachable[3] and then reachable[6] from it, returning True, but the correct 0/1 answer is False.
Exercise
Is 3-Coloring weakly or strongly NP-complete, and why?
Show answer
It is strongly NP-complete. Its instances contain no numbers whose magnitudes could be large, so restricting numbers to polynomial size changes nothing and it remains NP-complete.
Exercise
Subset Sum written in unary is in P. Why does that not contradict Subset Sum (in binary) being NP-complete?
Show answer
The unary encoding makes the input exponentially longer, so the O(n · T) algorithm is polynomial in that longer length. They are different problems with different input sizes, and the NP-completeness reduction relies on binary encoding of large numbers.