P vs NP explained for programmers: the million dollar problem

P vs NP explained for programmers: the million dollar problem
$1,000,000prize from the Clay Institute, unclaimed since 2000
1971Stephen Cook proves that SAT is NP-complete
Thousandsof known NP-complete problems; deep down, all the same one
88%of researchers polled in 2019 believe P ≠ NP
P vs NP explained for programmers: the million dollar problem
I also explain it in this video, on my channel Articulator EN. The figures in this post are frames from the video.

The idea: checking vs solvinglink

The core idea is very simple. For some problems, finding the solution is extremely hard, but checking a solution someone hands you is trivial. The question is whether that gap is real, or whether we just haven't found the trick yet.

Think of a hard sudoku. Filling it in can take you an hour of trial and error. But if I hand you a solved one, checking it is mechanical: you make sure no row, column or box repeats a number. That takes a few lines of code and runs in an instant:

def valid_sudoku(t):  # t: 9 rows of 9 numbers
    groups = t + [list(col) for col in zip(*t)]
    groups += [[t[r][c] for r in range(i, i + 3) for c in range(j, j + 3)]
               for i in (0, 3, 6) for j in (0, 3, 6)]
    return all(sorted(g) == list(range(1, 10)) for g in groups)
A sudoku: solving it is hard, checking it means going over rows, columns and boxes
Solving is hard. Checking is easy.

A bike lock with four number wheels works the same way: without the combination, you may have to try up to 10,000 possibilities; with the code, opening it takes a second. Same with passwords: checking yours is instant, while guessing it can be impossible in practice.

There are thousands of problems like that: scheduling shifts, planning routes, fitting pieces together, resolving dependencies. In all of them, checking a proposal is fast, and to solve them the best we know is, deep down, trying a huge number of options. P vs NP asks whether that's unavoidable, or whether there is a clever method that solves them as fast as we can check them.

What does “fast” mean?link

Here programmers are on home turf: it's Big O notation. We don't measure seconds, which depend on the machine, but how the number of steps grows as the input size, n, grows. Searching an unsorted list is O(n); comparing every pair with two nested loops is O(n²).

  • Polynomial: grows like n, n², n³ or n to any fixed power. Sorting a list, shortest path with Dijkstra's algorithm, multiplying matrices. Double the input and the time gets multiplied by 2, 4 or 8, but in a controlled way.
  • Exponential: grows like 2ⁿ. It shows up when you try every combination, for example every subset of a list.
nn² steps2ⁿ steps2ⁿ at a billion operations per second
101001,024a microsecond
20400~1 milliona millisecond
502,500over a quadrillionabout 13 days
10010,000a 31-digit numberalmost 3,000 times the age of the universe
Polynomial vs exponential with a computer a thousand times faster: n² grows ×31; 2ⁿ, just +10
Polynomial grows; exponential explodes.

And here's the key: hardware won't save you. With a computer a thousand times faster, a polynomial algorithm tackles much bigger inputs; an exponential one only lets you add about ten more elements, because 2¹⁰ is roughly a thousand. That's why, in computer science, polynomial means tractable and exponential means intractable.

The classes P and NPlink

P

Problems that can be solved in polynomial time. Sorting, shortest path… and even checking whether a huge number is prime, although that wasn't proven until 2002.

NP

Problems where, if someone gives you a candidate solution (a certificate), you can check in polynomial time whether it's correct: the filled-in sudoku, the lock code.

Watch out for a common mix-up: NP does not mean “not polynomial”. It means nondeterministic polynomial.

A classic example is subset sum: given 3, 34, 4, 12, 5 and 2, do some of them add up to 9? If I tell you “4 + 5”, you check it right away. But to find it with no hints, in general, nothing much better is known than going through subsets, and with n numbers there are 2ⁿ of them:

from itertools import combinations

def check(nums, target, certificate):          # fast: polynomial
    return set(certificate) <= set(nums) and sum(certificate) == target

def search(nums, target):                      # slow: 2^n subsets
    for k in range(1, len(nums) + 1):
        for sub in combinations(nums, k):
            if sum(sub) == target:
                return sub
    return None

search([3, 34, 4, 12, 5, 2], 9)                # (4, 5)

“Nondeterministic” comes from an imaginary machine that, every time it has to choose, always gets it right on the first try, as if it could guess. That machine would solve subset sum in a moment: it guesses which numbers to take, and then checks. NP is exactly the set of problems this magic machine solves in polynomial time. Real computers can't guess: they have to try.

And one important detail: everything in P is also in NP, because if you can solve a problem quickly, to check a solution you can just solve it yourself and compare. The big question is whether they're the same set. If P = NP, everything that can be checked quickly can be solved quickly. If they're different, there are problems that can be checked quickly but can never be solved quickly.

P inside NP: are they the same set?
P sits inside NP. The million dollar question is whether they're the same.

The NP zoolink

  • The traveling salesman: a delivery driver has to visit several cities and return to the start. Is there a route shorter than a thousand kilometers? Checking a route means adding up distances, but with 20 cities there are about sixty quadrillion possible routes.
  • Map coloring: can you paint the countries with three colors so that no two neighbors share one? It's exactly the problem of scheduling exams at a university: each course is a country, two courses with students in common are neighbors, and each color is a time slot.
  • Your package dependencies: when you install with apt or pip, the package manager has to pick one version of each dependency so they're all compatible. In general, that problem is NP-complete because it's equivalent to SAT: finding true or false values that make a logical formula true.
  • Games: certain versions of Minesweeper, Tetris and sudoku, generalized to boards of any size, are NP-complete, and Candy Crush is at least as hard. That's why a good solver for big boards is so tough: it's not that you're a bad programmer, it's that the problem is like that.
The traveling salesman problem: one route through every city
The traveling salesman: checking a route is addition; finding the best one isn't.

NP-complete: they're all the same problemlink

To understand “NP-complete” you need a very programmer-friendly idea: reduction. Reducing one problem to another means writing an adapter: a fast function that translates each instance of the first into an instance of the second, so that the answer to the second gives you the answer to the first. For example, a sudoku can be translated into a SAT formula: if you have a library that solves SAT, you can solve sudokus. So SAT is at least as hard as sudoku.

In 1971, Stephen Cook proved that any problem in NP can be reduced to SAT. Leonid Levin reached the same result on his own in the Soviet Union, which is why it's called the Cook-Levin theorem. SAT was the first NP-complete problem: it's in NP, and every other one reduces to it.

The following year, Richard Karp found 21 more problems with the same property, including the traveling salesman, knapsack and graph coloring. Today we know thousands, and since they all reduce to each other, deep down they're the same problem in disguise. If someone finds a polynomial algorithm for just one of them, any one, it solves them all, and then P = NP.

The map of classes: P inside NP, NP-complete on the edge, NP-hard above it and factoring in between
The map, assuming P ≠ NP.

So here's the map: inside NP are the easy ones, the problems in P. On the edge, the NP-complete ones, the hardest of the family. Above them, the NP-hard problems, at least as tough, though they may not even be quickly checkable. And there are odd cases in between, like factoring a huge number: it's in NP, but nobody has proven that it's NP-complete.

What if P = NP?link

If P equaled NP, and with a practical algorithm on top of that, the first thing to fall would be cryptography. RSA, which protects a large share of secure connections, relies on the fact that multiplying two primes is easy while factoring the result is extremely hard. Factoring is in NP: with such an algorithm, breaking those keys would be as easy as checking them, and banking, digital signatures or cryptocurrencies would no longer be secure.

But there would also be a wonderful side: the perfect route for every truck, the best possible chip design, the optimal schedule for a hospital. And something even crazier: finding a mathematical proof would be as easy as checking it. Gödel already raised this in a letter to von Neumann in 1956, and Scott Aaronson puts it like this: if P equaled NP, everyone who could appreciate a symphony would be Mozart.

P = NP guarantees nothing practical

An n¹⁰⁰ algorithm is polynomial, but useless.

P ≠ NP doesn't make every instance hard

It's about the worst case. Modern SAT solvers handle industrial formulas with millions of variables, because real-world instances usually have structure you can exploit.

Why has nobody solved it?link

In 2000, the Clay Institute picked seven big open problems and offered a million dollars for each. P vs NP is the only one that comes from computer science. So far only one has been solved, the Poincaré conjecture, proven by Grigori Perelman… who turned down the million.

In a 2019 poll of researchers, 88% said that P ≠ NP. The intuition is strong: after decades of thousands of people looking for fast algorithms for these problems, if they existed, someone would have found one. But believing is not proving.

Why is it so hard? Because you have to show that no fast algorithm exists, not even one nobody has thought of yet. And it has been proven that certain families of techniques aren't enough on their own: three results, from 1975 (relativization), 1994 (natural proofs) and 2008 (algebrization), explain why the tools we know fall short. We need a new idea.

Meanwhile, failed proofs keep coming: Gerhard Woeginger collected more than a hundred papers claiming to have solved it, one way or the other, and all of them had errors. The most famous case was in 2010, when Vinay Deolalikar, from Hewlett-Packard Labs, published a proof that the world's top experts reviewed online within days. It didn't hold up either.

What about you, as a programmer?link

The practical part is knowing how to recognize when your problem is NP-complete. If you're asked for the optimal shift schedule or the perfect route for a hundred vans and you spend days looking for an exact and fast algorithm, you're trying to solve P vs NP without knowing it. Spotting it early saves you weeks and lets you pick a way out that actually works:

  • Brute force if the input is small: 2²⁰ is just a million.
  • Heuristics and approximations if you don't need the optimum: for the traveling salesman with normal distances (that satisfy the triangle inequality), Christofides' algorithm guarantees at most 50% more than the ideal route.
  • SAT or integer linear programming solvers, which pack decades of tricks.
  • Change the problem: coloring with two colors is in P and with three it's NP-complete; SAT with two-variable clauses is in P and with three it's NP-complete. A small change in the requirements, like allowing two versions of the same library, can turn an intractable problem into an easy one, and many package managers do exactly that.
The four ways out of an NP-complete problem
Four classic ways out of an NP-complete problem.

In shortlink

P is the set of problems that can be solved quickly; NP, the ones that can be checked quickly; and nobody knows whether they're the same. The NP-complete problems are all the same problem in disguise, and whoever finds a fast algorithm for just one of them wins the million.

In one sentence

Checking is easy; the million dollar question is whether finding is too.

Do you think P equals NP?

Sourceslink

  • “P vs NP”, among the Clay Mathematics Institute's Millennium Prize Problems, with the official problem description by Stephen Cook.
  • Stephen Cook, “The complexity of theorem-proving procedures” (1971), and Richard Karp, “Reducibility among combinatorial problems” (1972).
  • William Gasarch, “The third P =? NP poll” (2019).
  • Scott Aaronson, “Reasons to believe” (2006), and Gerhard Woeginger's “The P-versus-NP page”.
  • The video, on my channels: English and Spanish.

Continue reading

Last posts -->

Have you seen these projects?

Gymnasia

Gymnasia Gymnasia
Expo
React Native
TypeScript
OpenAI
Anthropic

Fitness app with two agents that run entirely on the device, with no backend, so the user's data never leaves the phone. A BYOK conversational coach with local tools and a remote system prompt with offline fallback, plus a food estimator that pulls macronutrients out of a photo of the plate, with barcode scanning against OpenFoodFacts.

LangGraph Deep Researcher

LangGraph Deep Researcher LangGraph Deep Researcher
Python
LangGraph
FastAPI
React
TypeScript
Docker

Multi-agent research system built with LangGraph. A supervisor breaks your question down into topics and launches search sub-agents in parallel; each one compresses its findings before handing them to a writer agent that produces the final sourced markdown report. Live streaming over WebSockets, a configurable model per role and bring-your-own API keys that are never persisted server-side.

Tau

Tau Tau
Python
LangChain

Multi-agent tutoring system for secondary school students, with one agent per subject and course material written and validated by a team of teachers. It was used with real students at a private school in Spain and at a secondary school in Colombia.

View all projects -->
>_ Available for projects

Do you have an AI project?

Let's talk.

maximofn@gmail.com

Machine Learning and AI specialist. I develop solutions with generative AI, intelligent agents and custom models.

Do you want to watch any talk?

Last talks -->

Do you want to improve with these tips?

Last tips -->

Use this locally

Hugging Face spaces allow us to run models with very simple demos, but what if the demo breaks? Or if the user deletes it? That's why I've created docker containers with some interesting spaces, to be able to use them locally, whatever happens. In fact, if you click on any project view button, it may take you to a space that doesn't work.

Flow edit

Flow edit Flow edit

FLUX.1-RealismLora

FLUX.1-RealismLora FLUX.1-RealismLora
View all containers -->
>_ Available for projects

Do you have an AI project?

Let's talk.

maximofn@gmail.com

Machine Learning and AI specialist. I develop solutions with generative AI, intelligent agents and custom models.

Do you want to train your model with these datasets?

short-jokes-dataset

HuggingFace

Dataset with jokes in English

Use: Fine-tuning text generation models for humor

231K rows 2 columns 45 MB
View on HuggingFace →

opus100

HuggingFace

Dataset with translations from English to Spanish

Use: Training English-Spanish translation models

1M rows 2 columns 210 MB
View on HuggingFace →

netflix_titles

HuggingFace

Dataset with Netflix movies and series

Use: Netflix catalog analysis and recommendation systems

8.8K rows 12 columns 3.5 MB
View on HuggingFace →
View more datasets -->