Search

Search papers and lessons

Big-O Notation

Level 2 · 9 min read

Big-O notation describes how an algorithm's cost grows as its input grows, ignoring constant factors, so you can compare methods before you run them.

On this page

  • Colour = topic mix
  • Discrete math
  • Algorithms
  • Sign in to see your progress

TL;DR

Big-O notation says how the work an algorithm does grows as its input gets bigger. You write O(g(n))O(g(n)) to mean "for large inputs, the cost is at most some fixed multiple of g(n)g(n)". 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 nn, the number of items it has to handle. A loop that touches each item once takes about nn steps. Two nested loops over the same items take about n×nn \times n.

Now ask what happens when nn doubles. A single pass doubles the work. A nested pass quadruples it. A binary search barely notices: doubling nn adds only one more step (it works by repeated halving, so its cost is a Logarithm of nn). Big-O is a label for that behaviour as nn grows large.

Why ignore the constants

Suppose one method takes 2n2n steps and another takes 5n5n. 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 n2+1000nn^2 + 1000n, the 1000n1000n term is dominated by n2n^2 once nn exceeds 1000, so for large inputs the cost is essentially n2n^2.

5101520020406080100nsteps
  • log n
  • n
  • n log n
  • n^2
Step counts for four growth classes at small n. The n^2 curve leaves the others behind quickly, while log n barely rises.
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

Definition: Big-O

We write f(n)=O(g(n))f(n) = O(g(n)) if there exist a constant c>0c \gt 0 and a threshold n0n_0 such that

f(n)≤c g(n)for every n≥n0.f(n) \le c\, g(n) \quad \text{for every } n \ge n_0.

Here f(n)f(n) is the actual cost, g(n)g(n) is the simpler reference function such as nn, nlog⁡nn \log n or n2n^2, cc is a constant that absorbs machine speed and implementation details, and n0n_0 says "only for inputs large enough". Small inputs are allowed to misbehave.

Two related symbols are used too. f(n)=Ω(g(n))f(n) = \Omega(g(n)) means ff grows at least as fast as gg, the same definition with ≥\ge. f(n)=Θ(g(n))f(n) = \Theta(g(n)) means both hold: the growth is pinned down exactly up to constants.

The standard growth classes

Common classes, ordered from fastest to slowest growth:

O(1)⊂O(log⁡n)⊂O(n)⊂O(nlog⁡n)⊂O(n2)⊂O(2n).O(1) \subset O(\log n) \subset O(n) \subset O(n \log n) \subset O(n^2) \subset O(2^n).

Here ⊂\subset means "is contained in", so every O(log⁡n)O(\log n) function is also O(n)O(n). The rest of this lesson is about recognising which class a piece of code falls into.

Simplification rules

  1. Drop constants. O(3n)=O(n)O(3n) = O(n).
  2. Keep the dominant term. O(n2+n+7)=O(n2)O(n^2 + n + 7) = O(n^2).
  3. Sequential steps add, then take the maximum. If one part costs O(n)O(n) and the next costs O(n2)O(n^2), the total is O(n2)O(n^2).
  4. Nested loops multiply. A loop of nn steps inside another loop of nn steps costs O(n2)O(n^2).

Worked derivation

Show that f(n)=3n2+5n+2f(n) = 3n^2 + 5n + 2 is O(n2)O(n^2). We need constants cc and n0n_0. Try c=4c = 4. The inequality 3n2+5n+2≤4n23n^2 + 5n + 2 \le 4n^2 is equivalent to n2−5n−2≥0n^2 - 5n - 2 \ge 0. The left side is −2-2 at n=0n = 0, and it becomes non-negative once n≥6n \ge 6 (at n=6n = 6 it equals 36−30−2=436 - 30 - 2 = 4) and keeps growing from there. So c=4c = 4 and n0=6n_0 = 6 work.

Now show that f(n)f(n) is not O(n)O(n). Any bound c nc\, n fails for large nn, because 3n23n^2 eventually exceeds c nc\,n for every constant cc. The growth rate is genuinely quadratic.

Worked examples

Example
Finding the cost of a loop

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
  1. Let n=4n = 4 and items =[3,1,4,1]= [3, 1, 4, 1]. The outer loop runs for i=0,1,2,3i = 0, 1, 2, 3.
  2. The inner loop for i=0i = 0 compares 3 with 1, 4 and 1 and finds no match. For i=1i = 1 it compares 1 with 4, then with the last 1, finds the duplicate on the second comparison and returns True.
  3. In the worst case, with no duplicates, the comparisons are (n−1)+(n−2)+⋯+1=n(n−1)/2(n-1) + (n-2) + \dots + 1 = n(n-1)/2.
  4. For n=4n = 4 that is 66 comparisons. For n=1000n = 1000 it is 499,500499{,}500.
  5. Dropping constants and lower-order terms gives n2−n2→O(n2)\frac{n^2 - n}{2} \to O(n^2).

Interpretation: doubling the list roughly quadruples the worst-case work. A set-based version runs in O(n)O(n) on average, which is why the set version is the standard choice.

Example
Comparing sorting at a realistic size

Compare bubble sort, which takes about n2n^2 comparisons, with merge sort, which takes about nlog⁡2nn \log_2 n. Assume a machine that performs 10910^9 simple comparisons per second and ignore constant factors, which are of similar size in both cases.

  1. For n=106n = 10^6, bubble sort needs about (106)2=1012(10^6)^2 = 10^{12} comparisons.
  2. At 10910^9 per second, that is 1012/109=100010^{12} / 10^9 = 1000 seconds, about 17 minutes.
  3. Merge sort needs about 106×log⁡2(106)10^6 \times \log_2(10^6). Since log⁡2(106)≈19.9\log_2(10^6) \approx 19.9, that is about 2×1072 \times 10^7 comparisons.
  4. At 10910^9 per second, that is 0.020.02 seconds.
  5. The ratio is 1012/(2×107)=50,00010^{12} / (2 \times 10^7) = 50{,}000.

Interpretation: at a million items the choice between O(n2)O(n^2) and O(nlog⁡n)O(n \log n) 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.

Example
Binary search on a sorted list

Each step of binary search halves the remaining range, so after kk steps the range holds about n/2kn / 2^k items. The search ends when that is about 1, which means 2k≈n2^k \approx n, so k≈log⁡2nk \approx \log_2 n.

  1. For n=1,000,000n = 1{,}000{,}000, log⁡2n≈19.9\log_2 n \approx 19.9, so at most about 20 comparisons are needed.
  2. For n=1,000,000,000n = 1{,}000{,}000{,}000, log⁡2n≈30\log_2 n \approx 30, so about 30 comparisons.
  3. 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 O(log⁡n)O(\log n) 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.

SituationWhat goes wrongBetter approach
Small inputsA higher-order method with a small constant may be faster, and the n0n_0 threshold may not have been reachedMeasure with a benchmark at realistic sizes
Worst case versus typical caseQuicksort is O(n2)O(n^2) in the worst case but O(nlog⁡n)O(n \log n) on average; a hash table lookup is O(1)O(1) on average but O(n)O(n) in the worst caseState which case you mean; choose by the input you expect
Memory and cache effectsTwo methods with the same count of steps can differ greatly if one jumps around memory, see [[io-complexityIO complexity]]
Hidden costsA line that looks like O(1)O(1), such as string concatenation in a loop, may copy the whole string each timeCheck what each library call really does
Constants that matterTwo O(n)O(n) methods can differ by a large factor in practiceUse 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 OO 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 Ω\Omega and Θ\Theta notations in a 1976 note, to fix a common ambiguity: OO 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
For large enough inputs, f(n) is at most some fixed constant times g(n). The constant absorbs machine speed and implementation details, and the threshold n_0 excludes small inputs.
QuestionComputation: show that 2n^2 + 10n is O(n^2), giving constants c and n_0.Show answer
Try c = 3. We need 2n^2 + 10n at most 3n^2, which is equivalent to n^2 - 10n at least 0. That holds for n at least 10. So c = 3 and n_0 = 10 work. At n = 10 both sides equal 300, and for larger n the right side pulls ahead.
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
The inner loop runs n-1, n-2, down to 1 times, which sums to n(n-1)/2. Starting at i + 1 halves the work compared with a full n-by-n grid, but the halving is a constant factor. Because the total grows with the square of n, the class stays O(n^2).
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
Every pair gives 100,000×100,000=1010100{,}000 \times 100{,}000 = 10^{10} comparisons, which is O(n2)O(n^2). Building a hash set (or a hash index) from one list and looking up each item of the other costs about O(n)O(n) on average, roughly 2×1052 \times 10^5 operations. Use the hash approach and note that its worst case depends on hash quality.

Sources