Sub topic 12
Pseudo-Polynomial Time and NP-Hardness
This chapter assumes you know Big-O notation, the bottom-up DP table from earlier chapters, and the one-array version knapsack_01_1d. It explains why the O(nW) algorithm counts as "pseudo-polynomial" rather than polynomial. It also explains why that label fits with the 0/1 knapsack problem being NP-hard.
The Puzzle
The DP table has n + 1 rows and W + 1 columns, and each cell takes constant work. That gives O(nW) time, which looks polynomial. Yet the 0/1 knapsack problem is NP-hard, and nobody knows a polynomial algorithm for any NP-hard problem. Both statements are true. The answer lies in how we measure the size of the input.
Input Size Is Measured in Bits
Complexity theory measures running time against the length of the input: the number of bits needed to write it down. A list of n items needs about n numbers. The capacity W is a single number, and writing it takes only about log₂ W bits.
Let b be the number of bits in W. Then W can be as large as 2^b − 1, so the running time is:
- O(nW) = O(n · 2^b)
That is exponential in b. If you add one bit to the capacity, the table can double in width, while the input grows by a single character. An algorithm whose running time is polynomial in the numeric values of the input, but not in their bit length, is called pseudo-polynomial.
| Capacity W | Bits in W | DP cells for n = 100 | Practical? |
|---|---|---|---|
| 10^3 | 10 | about 10^5 | Instant |
| 10^6 | 20 | about 10^8 | Seconds in C, slow in Python |
| 10^9 | 30 | about 10^11 | No |
| 10^18 | 60 | about 10^20 | Never |
The input in the last row is tiny: 100 items and one 60-bit number. The DP is still hopeless on it.
Seeing the Growth Directly
The code below counts the cells the one-array DP visits. It shows that the work depends on the value of W, not on how many digits W has.
def knapsack_01_1d_counted(values, weights, capacity):
dp = [0] * (capacity + 1)
cells = 0
for v, w in zip(values, weights):
for c in range(capacity, w - 1, -1):
dp[c] = max(dp[c], dp[c - w] + v)
cells += 1
return dp[capacity], cells
values = [60, 100, 120]
for scale in [1, 10, 100, 1000]:
weights = [10 * scale, 20 * scale, 30 * scale]
capacity = 50 * scale
best, cells = knapsack_01_1d_counted(values, weights, capacity)
print(f"scale={scale:5d} bits(W)={capacity.bit_length():3d} best={best} cells={cells}")Output:
scale= 1 bits(W)= 6 best=220 cells=90
scale= 10 bits(W)= 9 best=220 cells=873
scale= 100 bits(W)= 13 best=220 cells=8703
scale= 1000 bits(W)= 16 best=220 cells=87003Each scaled-up instance is the same problem with the same answer. Multiplying W by 10 adds about 3.3 bits to the input and multiplies the work by about 10.
Why Knapsack Is NP-Hard
The decision version of knapsack asks: "Is there a subset with total weight at most W and total value at least K?" This version is NP-complete. It was on Karp's 1972 list of NP-complete problems, which came out of a reduction from Subset Sum.
Subset Sum asks: given positive integers a₁, …, aₙ and a target T, does some subset add up to exactly T? The reduction to knapsack takes one step:
- For each number aᵢ, create an item with value aᵢ and weight aᵢ.
- Set capacity W = T and value target K = T.
- Any feasible subset has total value equal to its total weight, which is at most T. So its value is at least T only when its sum is exactly T.
So a fast knapsack solver would also solve Subset Sum fast. Subset Sum is NP-complete, so knapsack is NP-hard. The optimization version is at least as hard as the decision version, since knowing the optimum value answers the decision question.
The two facts fit together. The reduction keeps the numbers the same size, so the hard Subset Sum instances are the ones with huge numbers, where T has many bits. The O(nW) DP is slow on exactly those instances. If P ≠ NP, no algorithm runs in time polynomial in n and log W.
Weak Versus Strong NP-Hardness
NP-hard problems split into two groups:
| Kind | Meaning | Examples |
|---|---|---|
| Weakly NP-hard | Hard only when the numbers are large; a pseudo-polynomial algorithm exists | 0/1 knapsack, Subset Sum, Partition |
| Strongly NP-hard | Stays hard even when every number is bounded by a polynomial in n | Bin packing, TSP, multidimensional knapsack with many constraints |
A weakly NP-hard problem becomes easy when the numbers are small. For a strongly NP-hard problem, small numbers do not help: a pseudo-polynomial algorithm would imply P = NP. This difference is why knapsack, unlike bin packing, has a fully polynomial-time approximation scheme, which a later chapter covers.
Practical Consequences and Gotchas
The cost of units
Scaling weights changes W, and with it the running time. Weights in kilograms with W = 50 give 51 columns. The same weights in grams give 50,001 columns. Measuring in grams when kilograms would do slows you down by 1,000 times.
Divide out a common factor
If every weight shares a factor g, divide all weights by g and divide the capacity by g with floor division. Every achievable total weight is a multiple of g, so rounding the capacity down loses nothing.
from functools import reduce
from math import gcd
def knapsack_01_1d(values, weights, capacity):
dp = [0] * (capacity + 1)
for v, w in zip(values, weights):
for c in range(capacity, w - 1, -1):
dp[c] = max(dp[c], dp[c - w] + v)
return dp[capacity]
def shrink(weights, capacity):
g = reduce(gcd, weights)
return [w // g for w in weights], capacity // g
weights, capacity = shrink([1000, 2000, 3000], 5999)
print(weights, capacity) # [1, 2, 3] 5
print(knapsack_01_1d([60, 100, 120], weights, capacity)) # 220This trick only helps when a common factor exists. It cannot rescue an instance with large, unrelated weights.
Fractional weights
The DP indexes an array by weight, so weights must be integers. With weights like 0.37, you have to multiply by a power of ten to make them integers, and W grows by the same factor. Rounding to make the numbers smaller is no longer exact. Rounding weights down can let an infeasible subset through, and rounding up can rule out the true optimum.
Memory hits a wall before time does
Even the one-array version holds W + 1 entries. For W = 10^9, that is about 8 GB with 64-bit integers, and much more as Python ints in a list. Memory often decides that the weight-indexed DP is out before running time does.
Choosing what to do
When W is too large, the later chapters offer other options:
- Large W, small total value: index the DP by value instead, in O(n · ΣV).
- Both large, n at most about 40: meet in the middle, in O(2^(n/2) · n).
- Both large, n large: branch and bound with a fractional bound, which is often fast in practice but exponential in the worst case.
- A near-optimal answer is enough: the FPTAS, which runs in time polynomial in n and 1/ε.
Exercise
An instance has n = 60 items and capacity W = 2^40. How many bits does writing W take, roughly how many cells would the weight-indexed DP visit, and is the input "large"?
Show answer
W takes 41 bits. The DP visits about n · W = 60 · 2^40 ≈ 6.6 × 10^13 cells, which is far too many. The input itself is small: 60 items plus one 41-bit number. That gap between a small input and a huge amount of work is what pseudo-polynomial means.
Exercise
Use the Subset Sum reduction to build the knapsack instance for numbers [3, 7, 12] and target T = 15. What does knapsack011d return, and what does that tell you about the Subset Sum question?
Show answer
The items are values [3, 7, 12] and weights [3, 7, 12], with capacity 15. The best value within weight 15 is 15, from items 3 and 12. The optimum reaches T = 15, so the answer to Subset Sum is yes: 3 + 12 = 15.
Exercise
Why can't we make the DP polynomial by dividing every weight by 1000 and rounding to the nearest integer?
Show answer
Rounding changes which subsets fit. Rounding weights down can let a subset whose true weight is over W count as feasible. Rounding up can exclude the true optimum. The result is no longer exact. Rounding only becomes useful when we accept an approximate answer with a proven error bound, which is the idea behind the FPTAS. The FPTAS rounds values, not weights, so every solution it returns still fits.