TL;DR
Big-O notation says how the work an algorithm does grows as its input gets bigger. You write to mean "for large inputs, the cost is at most some fixed multiple of ". Constant factors and small terms are dropped, so only the shape of the growth remains.
That shape is what decides whether a method still works when the input is a million times larger. Two algorithms that both "work" can differ by a factor of a million in running time, and big-O tells you which one will survive.
Where you'll see it: in the complexity column of any algorithms textbook, in library documentation for sorting and hashing, and in code review when someone asks why a nested loop will not scale.
Intuition
Counting steps, not seconds
Seconds depend on the machine, the language and the compiler. To compare methods fairly, count the basic steps an algorithm takes as a function of the input size , the number of items it has to handle. A loop that touches each item once takes about steps. Two nested loops over the same items take about .
Now ask what happens when doubles. A single pass doubles the work. A nested pass quadruples it. A binary search barely notices: doubling adds only one more step (it works by repeated halving, so its cost is a Logarithm of ). Big-O is a label for that behaviour as grows large.
Why ignore the constants
Suppose one method takes steps and another takes . Both grow in a straight line, and the second is only 2.5 times slower on any machine. The gap between a straight line and a parabola is far bigger. For large inputs the growth rate dominates, so the constant is set aside.
The same reasoning drops small terms. In , the term is dominated by once exceeds 1000, so for large inputs the cost is essentially .
- log n
- n
- n log n
- n^2
flowchart LR A[Count steps as a function of n] --> B[Keep the fastest-growing term] B --> C[Drop constant multipliers] C --> D[Write O of that growth]
The math
The definition
We write if there exist a constant and a threshold such that
Here is the actual cost, is the simpler reference function such as , or , is a constant that absorbs machine speed and implementation details, and says "only for inputs large enough". Small inputs are allowed to misbehave.
Two related symbols are used too. means grows at least as fast as , the same definition with . means both hold: the growth is pinned down exactly up to constants.
The standard growth classes
Common classes, ordered from fastest to slowest growth:
Here means "is contained in", so every function is also . The rest of this lesson is about recognising which class a piece of code falls into.
Simplification rules
- Drop constants. .
- Keep the dominant term. .
- Sequential steps add, then take the maximum. If one part costs and the next costs , the total is .
- Nested loops multiply. A loop of steps inside another loop of steps costs .
Worked derivation
Show that is . We need constants and . Try . The inequality is equivalent to . The left side is at , and it becomes non-negative once (at it equals ) and keeps growing from there. So and work.
Now show that is not . Any bound fails for large , because eventually exceeds for every constant . The growth rate is genuinely quadratic.
Worked examples
Take the function below, which checks whether a list contains any duplicate.
def has_duplicate(items):
for i in range(len(items)):
for j in range(i + 1, len(items)):
if items[i] == items[j]:
return True
return False- Let and items . The outer loop runs for .
- The inner loop for compares 3 with 1, 4 and 1 and finds no match. For it compares 1 with 4, then with the last 1, finds the duplicate on the second comparison and returns
True. - In the worst case, with no duplicates, the comparisons are .
- For that is comparisons. For it is .
- Dropping constants and lower-order terms gives .
Interpretation: doubling the list roughly quadruples the worst-case work. A set-based version runs in on average, which is why the set version is the standard choice.
Compare bubble sort, which takes about comparisons, with merge sort, which takes about . Assume a machine that performs simple comparisons per second and ignore constant factors, which are of similar size in both cases.
- For , bubble sort needs about comparisons.
- At per second, that is seconds, about 17 minutes.
- Merge sort needs about . Since , that is about comparisons.
- At per second, that is seconds.
- The ratio is .
Interpretation: at a million items the choice between and is the difference between a coffee break and an instant. At ten items the two are indistinguishable, so the asymptotic label matters only as the input grows.
Each step of binary search halves the remaining range, so after steps the range holds about items. The search ends when that is about 1, which means , so .
- For , , so at most about 20 comparisons are needed.
- For , , so about 30 comparisons.
- Multiplying the input by a thousand adds only about 10 comparisons.
Interpretation: logarithmic cost is why a phone book, a database index and a sorted array all find items so quickly. It is the reason is treated as nearly constant in practice.
Tradeoffs and failure modes
Big-O is a tool for comparing methods at large sizes. It is not a full account of speed.
| Situation | What goes wrong | Better approach |
|---|---|---|
| Small inputs | A higher-order method with a small constant may be faster, and the threshold may not have been reached | Measure with a benchmark at realistic sizes |
| Worst case versus typical case | Quicksort is in the worst case but on average; a hash table lookup is on average but in the worst case | State which case you mean; choose by the input you expect |
| Memory and cache effects | Two methods with the same count of steps can differ greatly if one jumps around memory, see [[io-complexity | IO complexity]] |
| Hidden costs | A line that looks like , such as string concatenation in a loop, may copy the whole string each time | Check what each library call really does |
| Constants that matter | Two methods can differ by a large factor in practice | Use big-O to pick the family, then profile |
Use big-O when inputs can grow unpredictably, when you need to compare algorithms before implementing them, and when a design must still work at scale. Do not rely on it alone when the input is always small or when a constant factor is the bottleneck.
History
The notation comes from number theory. In 1894 Paul Bachmann used the symbol to describe how fast a function grows in his work on the distribution of numbers. Edmund Landau popularised it in the following years, which is why it is sometimes called a Landau symbol.
Computer science adopted it for algorithms in the 1960s and 1970s, when analysis of algorithms became a discipline. Donald Knuth proposed the and notations in a 1976 note, to fix a common ambiguity: alone says only an upper bound, while many authors meant an exact rate. His textbook series did much to make the notation standard. Big-O is now the common language for describing how software scales.
Check yourself
QuestionRecall: what does f(n) = O(g(n)) mean in plain words?Show answer
QuestionComputation: show that 2n^2 + 10n is O(n^2), giving constants c and n_0.Show answer
QuestionWhy: why does the nested loop in the duplicate-check example cost O(n^2) even though the inner loop starts at i + 1?Show answer
QuestionApplied: a colleague's join of two lists of 100,000 records runs a full comparison of every pair. Estimate the work and propose a better approach.Show answer
Sources
- Big O notation (Wikipedia): https://en.wikipedia.org/wiki/Big_O_notation
- Time complexity (Wikipedia): https://en.wikipedia.org/wiki/Time_complexity
- Analysis of algorithms (Wikipedia): https://en.wikipedia.org/wiki/Analysis_of_algorithms