Checking an answer
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.
A friend says yes and hands you a pick: one bit per number, 1 for use it, 0 for skip it. Their pick is 1, 1, 0, 1. A pick like this, offered as proof of a yes, is called a certificate.
check() walks the numbers once and adds the picked ones: s goes 3, 8, 8, 15. s equals t, so the pick is right. That is 4 loop passes for 4 numbers: checking costs O(n) steps.
Finding an answer
With no pick handed over, solve() tries them all. product counts through picks like an odometer, rightmost bit fastest. There are 2^4 = 16 picks. Here the 14th, 1, 1, 0, 1, is the first that check() accepts.
Every extra number doubles the picks: 2^n. With 20 numbers that is 1,048,576. With 60 it is about 1.2 × 10^18, some 36 years at a billion picks a second. Checking one pick still takes only n steps.
P, NP and NP-complete
P is the set of decision problems some algorithm solves in polynomial time: O(n^k) steps for a fixed k. Example: is there a path from s to t of length at most d? Dijkstra answers that fast, so it is in P.
NP is the set of decision problems where every yes has a certificate that a polynomial-time verifier accepts, and no certificate fools it on a no. Subset sum is in NP: check() is that verifier.
Every problem in P is also in NP: a verifier can ignore the certificate and solve the problem itself, still in polynomial time. So P sits inside NP. Brute force also shows NP problems are solvable in exponential time.
A problem is NP-hard if every NP problem reduces to it: converts into it in polynomial time. NP-complete means NP-hard and in NP. Subset sum is NP-complete: Karp proved it in 1972, under the name knapsack.
If any NP-complete problem had a polynomial algorithm, every NP problem would, and P would equal NP. Nobody has found one or proved it impossible. Most experts think P ≠ NP. A proof either way wins $1 million.
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.