1def solve(nums, t):2 n = len(nums)3 for pick in product((0, 1), repeat=n):4 if check(nums, t, pick):5 return pick6 return NoneNPPNP-complete1def check(nums, t, pick):2 s = 03 for x, p in zip(nums, pick):4 if p:5 s += x6 return s == tnums[0]3nums[1]5nums[2]6nums[3]701010101pickn4st15tries3path ≤ dsubset sum
Lamps: the pick, one bit per number (1 = use it)Plates: the classes P, NP and NP-completeA hopping block: check() adding one picked numberSubset sum on 3, 5, 6, 7 with t = 15: check() adds up one proposed pick in a single pass, while solve() tries picks one by one, 2ⁿ of them in the worst case. P holds problems solved in polynomial time, NP problems whose yes answers can be checked in polynomial time; P sits inside NP. Subset sum is NP-complete: a polynomial solve() for it would prove P = NP.

Checking an answer

  1. Subset sum: here are 4 numbers, 3, 5, 6, 7. Can you choose some of them that add up to exactly t = 15? The answer is yes or no, so this is a decision problem. Those are the problems P and NP talk about.

Finding an answer

P, NP and NP-complete

What happens

;; step 1/10 · puzzle
nums = [3, 5, 6, 7]   n = 4
t    = 15
question: is there a subset of nums with sum exactly t?
answer: YES or NO (a decision problem)

P, NP, NP-hard and NP-complete follow MIT 6.006 (Spring 2020) lecture 19 and CLRS chapter 34. They are defined for decision problems; the size n is the length of the input written in bits, which for a list of small numbers is about the number of items. Subset sum has a dynamic-programming solution that takes about n·t steps (the knapsack problem uses the same table). That is fast when t is small, but t written in b bits can be as large as 2^b, so n·t is not polynomial in the input size. It is called pseudo-polynomial.