AI State of the Art
Fundamentals/Machine Learning: The Basics/26 min
Section 3

Big-O Notation and Complexity: P, NP, Kolmogorov

Listen as a podcast →

Why does a GPS find your route in 2 seconds, but struggles with 1,000 cities?

You use Google Maps every day. Finding the shortest path between two points? Easy, solved in milliseconds. But now, imagine you're asked to find the shortest circuit visiting 1,000 cities exactly once (the famous traveling salesman problem). Even the world's best supercomputers can't solve it optimally. Why?

The answer comes down to two letters: P and NP. And this distinction is perhaps the most important question in all of computer science, including for AI.

First, the O(...) notation

This notation turns up on every other page of the course. Worth setting down properly once.

When we write that a computation is O(something) (read aloud as "big-O of") we are not giving a time in seconds. We are answering one question only: if I double the amount of data, how much does the work grow? Everything else is deliberately ignored: how fast the machine is, which programming language, any constant multiplier. Only the shape of the growth counts.

Call nn the size of the input: the number of items to sort, cities to visit, words in a text. Then:

NotationWhat it meansIf nn doubles, the work...
O(1)O(1)The work does not depend on nn at allstays the same
O(log⁡n)O(\log n)Each doubling of nn adds one notch of workgoes up by one notch
O(n)O(n)The work is proportional to nndoubles
O(nlog⁡n)O(n \log n)Slightly more than proportionaldoubles, plus a bit
O(n2)O(n^2)The work follows the square of nnis multiplied by 4
O(n3)O(n^3)The work follows the cube of nnis multiplied by 8
O(2n)O(2^n)Each extra element doubles the workgets squared
O(n!)O(n!)The work follows the factorial of nnbecomes astronomical

Two notations deserve a word. 2n2^n reads "two to the power nn": 2 multiplied by itself nn times. At n=10n = 10 that is about a thousand; at n=60n = 60 it exceeds the number of grains of sand on Earth. And n!n! reads "nn factorial": the product 1×2×3×⋯×n1 \times 2 \times 3 \times \dots \times n, which is the number of ways of ordering nn objects. At n=20n = 20 it is already 2.4 billion billion.

The dividing line falls in one specific place. The upper rows, where nn sits in the base and the exponent is fixed (n2n^2, n3n^3), are called polynomial: they stay computable. The bottom two rows, where nn moves up into the exponent or into a factorial, are called exponential: they become impossible very quickly, whatever machine you own. Everything that follows on this page turns on that boundary.

Complexity classes: P, NP, and the wall

The P class: the "easy" problems

A problem is in P (for polynomial time) if we know how to solve it with a computation whose cost follows a fixed power of the input size. Concretely:

  • Sorting a list of nn elements -> O(nlog⁡n)O(n \log n)
  • Shortest path in a network (Dijkstra's algorithm) -> O(n2)O(n^2)
  • Multiplying two tables of numbers of size n×nn \times n -> O(n3)O(n^3)

Doubling nn therefore multiplies the work by 2, 4 or 8 depending on the case: that stays manageable. A polynomial algorithm, even a slow one, remains runnable in practice.

Chart of operations against number of elements, showing the O(1), O(log n), O(n), O(n log n), O(n squared), O(2 to the n) and O(n factorial) curves, with colored bands from excellent to horrible.
Number of operations as a function of input size. The O(1), O(log n), O(n) and O(n log n) curves stay flat along the bottom: these are the algorithms you can actually run. O(n squared) already climbs noticeably, while O(2 to the n) and O(n factorial) shoot up almost vertically within the first few dozen elements. This is the wall separating P problems from NP-complete ones, drawn as a picture.Source : Big-O Cheat Sheet, via Greg Hilston

The NP class: easy to verify, hard to find

NP (for nondeterministic polynomial time) contains problems whose solution can be verified in polynomial time, even if finding it seems exponentially hard.

The acronym trap

The N in NP does not stand for "non-polynomial". It comes from "nondeterministic", an imaginary machine allowed to guess the right answer in one shot. NP therefore contains the whole of P: anything you can solve quickly, you can certainly also check quickly.

The classic analogy: imagine a giant sudoku grid of size n×nn \times n. Verifying that a filled grid is correct? Easy, you walk through each row, each column and each block. But finding the solution from a blank grid? The number of possibilities explodes.

P = NP?

The question "P = NP?" is one of the seven Millennium Prize Problems set by the Clay Mathematics Institute in 2000, each carrying a one-million-dollar prize. It asks: can every problem whose solution can be verified quickly also be solved quickly? Most computer scientists think not (written P ≠ NP, "P is not equal to NP") but nobody has proved it.

NP-complete: the hardest of the hard

NP-complete problems are the hardest in NP. A problem is NP-complete if:

  1. It is in NP (a solution can be verified in polynomial time);
  2. Every other problem in NP can be reduced to it, restated in its language, via a transformation that is itself fast.

That second condition is what gives the class its bite: solve a single NP-complete problem in polynomial time and the reduction hands you every other one for free, proving P = NP. Famous examples:

ProblemDescriptionWhy it's hard
SAT, satisfiabilityFind true/false values making a logical formula with nn variables come out trueTwo values per variable gives 2n2^n combinations
Travelling salesmanShortest circuit through nn citiesThere are n!n! possible visiting orders
KnapsackMaximize the value carried in a bag of limited capacityEach item is taken or left, so 2n2^n choices
Graph colouringColour the nodes of a network with kk colours so no two neighbours matchknk^n colourings to examine
Euler diagram of complexity classes: a large NP-Hard region on top, an NP region below, their overlap forming NP-Complete, and a small P region fully contained inside NP.
The Euler diagram that sums it all up, drawn under the assumption that P is not equal to NP. P (the easy problems) sits inside NP (the easy-to-verify problems). NP-complete problems are exactly the overlap between NP and NP-hard: the hardest problems in NP. NP-hard spills outside NP because it also contains problems we cannot even verify quickly. If P = NP were ever proved, the small P bubble would swell until it covered all of NP.Source : GeeksforGeeks

What does this have to do with AI?

You might be wondering what any of this has to do with machine learning. The connection is in fact very tight.

Training is NP-hard

Training a neural network optimally (finding the weights that perfectly minimize the loss function) is an NP-hard problem, meaning at least as hard as the NP-complete ones. In theory, gradient descent should not work at all. Yet it works remarkably well. Why?

  • The loss landscape (the mental picture of a terrain whose altitude is the model's error and whose directions of travel are its weights) offers, once the directions are numerous enough, a multitude of routes down to good solutions. In sufficiently wide networks you do not get stuck in catastrophic local minima: dips in the terrain you cannot leave by going downhill.
  • We are not after the optimal solution, only a good enough one.
  • Overparameterization (giving the model far more weights than it strictly needs) multiplies the acceptable solutions, so SGD (Stochastic Gradient Descent) stumbles onto one without trouble.

The picture: finding the way out of a maze. On a flat plan, in two dimensions, it is laborious. In a maze with a thousand dimensions there are exits on every side.

Model complexity and problem complexity

Attention in transformers costs O(n2)O(n^2) in both memory and compute, where nn is the number of tokens, the word fragments a text is chopped into. Formally n2n^2 is polynomial, hence in P. But for a sequence of 100,000 tokens that is 10 billion pairs to evaluate: the wall is right there, without ever leaving P. This is what motivated Flash Attention, linear attention and the other optimizations covered in the State of the Art part.

So complexity does not only say what is "possible" or "impossible". It says what is feasible in practice with the hardware you have.

Kolmogorov complexity: to compress is to understand

There's another way to think about complexity, deeper and more connected to artificial intelligence. It's Kolmogorov complexity.

The fundamental idea

The Kolmogorov complexity of an object (a string of characters, an image, a dataset) is the length of the shortest computer program that can produce it.

Consider these two 1,000-character strings:

  • aaaaaaaaaaaa..., the letter "a" a thousand times. The program print("a" * 1000) produces it: about twenty characters. Low complexity, the object is highly compressible.
  • xK9$mP2c&Lw..., a thousand characters drawn at random. No program is shorter than the string itself: the only way to produce it is to copy it out. Maximum complexity, the object is incompressible.

K(x)=min⁡{ ∣p∣  :  U(p)=x }K(x) = \min\{\,|p| \;:\; U(p) = x\,\}

Symbol by symbol: xx is the object being measured; pp is a candidate program; ∣p∣|p| that program's length in characters; UU is a universal Turing machine, an idealized computer able to run any program, needed so that "program length" means something independent of the language you picked; the colon reads "such that"; and min⁡\min means "take the smallest value". In one sentence: among all programs that output xx, keep the length of the shortest.

Worth noting in passing: this quantity is not computable. No algorithm can, in general, find the shortest program producing a given object. Kolmogorov gives a frame of thought, not a measuring instrument.

Compressing, predicting, understanding

Here is the central link: a good compressor is a good predictor, and the reverse. If you can predict the next token in a sequence, you can compress that sequence, because you only need to encode the surprises, what you did not see coming. Conversely, if you compress well, it is because you grasped the regularities: you understood the structure of the data.

It is in this sense that a large language model is a compressor of its training corpus. It learned to predict the next word, which amounts to spotting the regularities in a very large body of text. Next-token prediction and compression are two faces of the same objective.

On the reading list attributed to Ilya Sutskever

People often cite a list of some thirty papers that Ilya Sutskever, co-founder of OpenAI, is said to have recommended as the foundation for understanding AI, reportedly including the book Kolmogorov Complexity and Algorithmic Randomness by Shen, Uspensky and Vereshchagin along with Scott Aaronson's post The First Law of Complexodynamics. The list circulates widely but was never published by its supposed author: treat it as an anecdote, not a source. The compression-intelligence connection itself does not depend on the anecdote.

Quantifying the Rise and Fall of Complexity in Closed Systems: The Coffee Automaton (Aaronson et al., 2014)

Minimum description length

The minimum description length principle (MDL) applies Kolmogorov's intuition directly to machine learning: the best model is the one that compresses the data best, that is, the one minimizing this sum:

MDL=L(model)+L(data∣model)\text{MDL} = L(\text{model}) + L(\text{data} \mid \text{model})

Term by term: LL denotes a length counted in bits, a bit being the smallest unit of information, the answer to one yes-or-no question. L(model)L(\text{model}) is the number of bits needed to write the model itself, meaning its weights. L(data∣model)L(\text{data} \mid \text{model}), where the vertical bar reads "given", is the number of bits needed to describe what the model fails to explain: its residual errors. In one sentence: add the cost of the model to the cost of what it misses, and keep whichever total is lowest.

The two terms pull in opposite directions, and that is the point. A model that is too simple writes down in few bits but leaves a lot of error to describe. A model that is too complex leaves almost no error but is expensive to write down. The balance point is Occam's razor put into a formula: the simplest explanation that accounts for the observations.

This is exactly the reasoning behind regularization: penalize the model's "description length". Weight decay is minimum description length under another name.

Emergent complexity: the coffee paradox

One last concept, taken from the paper cited above: emergent complexity.

Scott Aaronson, Sean Carroll and Lauren Ouellette studied a curious phenomenon they call the "coffee automaton". Pour milk into black coffee: there is a brief moment when the swirls form extremely complex patterns. Neither the uniform black coffee at the start, which a single sentence describes, nor the evenly blended drink at the end, which a single sentence also describes. Complexity emerges in the middle, between the initial order and the final disorder.

It is a useful metaphor for AI: interesting models are neither trivially simple nor purely random. They capture the intermediate structure of the world, the regularities that are neither obvious nor unpredictable.

Why all this matters for you

ConceptWhat it changes in practice
O(...) notationThe shared language for saying what a computation will cost as the data grows
P and NPExplains why optimal training is out of reach, and why gradient descent works anyway
The O(n2)O(n^2) costSets the limit on attention, and motivates Flash Attention and linear attention
KolmogorovCompressing, predicting and understanding are three views of one act
Minimum description lengthThe theoretical footing of regularization and model selection
Emergent complexityUseful models capture intermediate structure, between the obvious and the random

Computational complexity is not an abstract maths topic. It is the frame that explains why AI works, where its limits lie and how they get pushed. Choosing an architecture, deciding on a context window size, accepting or refusing a quadratic cost: that is applied complexity theory, whether you call it that or not.

Check your understanding0 / 5

1. When we say an algorithm is O(n²), what exactly are we claiming?

2. What does the N in NP stand for?

3. Transformer attention costs O(n²), which is polynomial, hence in P. Does that mean the computation is always feasible?

4. Training a neural network optimally is NP-hard. Why does gradient descent work anyway?

5. In what sense is a large language model a compressor of its training corpus?