Complexity and Big-O Notation: Measuring Speed as a Function of Input Size
0. Key points
Section titled “0. Key points”- Complexity is the number of basic operations executed on an input of size ; it is not the running time measured in seconds. This abstraction is what makes comparisons independent of machine, language and compiler.
- The statement asserts that there exist constants and such that for every . Here is a set of functions, and the equality sign is nothing but a customary abbreviation.
- Growth rates form a hierarchy . This is not an intuition but a theorem, provable as a statement about limits.
- Doubling the input size multiplies the cost of a algorithm by , whereas a algorithm gains “all the work it had done so far” again. Making the machine times faster raises the largest tractable for a algorithm by only about .
- For divide-and-conquer recurrences , the master theorem determines the order mechanically.
- The boundary between “solvable in polynomial time” and “only exponential algorithms known” lies at the heart of the P vs NP problem, the central open question of computer science.
1. Motivation: why growth rate rather than seconds
Section titled “1. Motivation: why growth rate rather than seconds”Suppose we want to know which of two programs, A and B, is faster. The naive method is to run them and compare the elapsed seconds. This method has a decisive weakness: what we measured is the speed on that input, on that machine, with that compiler, in that cache state, and nothing guarantees the same ranking tomorrow in a different environment.
Worse, a measurement on small inputs predicts nothing about the behaviour on large ones. Consider two algorithms that sort an array of elements. Insertion sort performs about comparisons in the worst case, while merge sort performs about . For the counts are and , barely distinguishable. For they become and , a ratio of about . On a machine performing basic operations per second, the second finishes in seconds while the first takes over eight minutes.
What matters here is not the quality of the implementation but the structure of how the operation count grows as increases. Better hardware and optimised code buy us, in most cases, a speedup by a constant factor. The choice of algorithm, by contrast, turns into — a difference no constant factor can close.
We therefore regard the operation count as a function of and look only at the growth rate, discarding constant factors and finitely many exceptions. It is exactly this coarseness that makes universal, environment-independent comparison possible. Below we first decide what to count (§2), then make the comparison of growth rates precise (§3), prove the resulting hierarchy (§4), and see what happens at realistic scales (§5).
2. Preliminaries: the machine model and complexity
Section titled “2. Preliminaries: the machine model and complexity”2.1. What counts as one step
Section titled “2.1. What counts as one step”Before counting “basic operations” we must decide what a basic operation is. The standard choice is the uniform-cost RAM model (uniform-cost random access machine).
Definition 2.1(The uniform-cost RAM model)
The machine has a sequence of memory cells indexed by addresses together with finitely many registers. Each of the following operations is called a basic operation and is executed in one unit of time.
- Reading from and writing to a constant, a register, or a memory cell at a specified address
- Addition, subtraction, multiplication, division and comparison of integers and reals
- Conditional and unconditional branching
Moreover, a single memory cell is assumed to hold a word of bits, where is the input size.
The last condition is easy to overlook but essential. Without the restriction to bits per word, one could pack the whole input into a single cell and perform multiple-precision arithmetic in one step, which would license wildly unrealistic algorithms. Under the restriction, on the other hand, the bits needed to index elements fit into exactly one word, so array index computations take one step — a setting close to a real machine.
In the uniform-cost model, multiplying two -digit integers also counts as one step. In cryptography or computer algebra, where huge integers occur, this assumption fails and one uses the logarithmic-cost model, which charges a cost proportional to the number of bits. A complexity claim is meaningless unless the model it is measured in is stated.
2.2. Time and space complexity
Section titled “2.2. Time and space complexity”Definition 2.3(Worst-case time and space complexity)
For an algorithm and an input , write for the number of basic operations executes before halting on , and for the total number of memory cells written to or read from. Define the size of an input to be the number of words needed to represent . Then
are called the worst-case time complexity and the worst-case space complexity of .
Note the maximum. Time complexity refers to the least favourable input of size . Consequently is an upper bound guaranteed for every input, once is fixed.
Time and space are not independent. The next proposition says that space is a “cheaper” resource than time.
Proposition 2.4(Space is bounded by time)
Suppose an algorithm accesses at most memory cells per basic operation (in the model of Definition 2.1 one may always take ). Then for every ,
In particular, if then .
Proof(Proposition 2.4)
Fix an input of size . Every cell accessed by is either one of the cells holding the input or a cell accessed during execution. By hypothesis at most cells are accessed per step, so at most cells are accessed over all steps. Hence , and taking the maximum over gives the first claim.
If then , so taking and in Definition 3.1 yields .
The converse fails. One can build algorithms using space and time at will. The asymmetry “memory can be reused, time cannot” shows itself here.
2.3. Counting in practice
Section titled “2.3. Counting in practice”Example 2.5(Counting the comparisons of insertion sort to the end)
Consider insertion sort, which rearranges an array of length into increasing order.
def insertion_sort(a): for i in range(1, len(a)): key = a[i] j = i - 1 while j >= 0 and a[j] > key: a[j + 1] = a[j] j -= 1 a[j + 1] = key return aLet us count how many times the comparison a[j] > key between elements is evaluated. Fix the outer loop variable ; the inner while runs with decreasing. Because of short-circuit evaluation no comparison is performed once j >= 0 becomes false, so the number of comparisons equals the number of rounds with , that is, at most . This bound is attained exactly when the input is the strictly decreasing sequence . Indeed, then key is always smaller than every element of , so the while runs until , giving comparisons at . Hence the worst-case number of comparisons is
For the same input the number of assignments is , since for each the statement runs times and reading and writing key accounts for more. Including loop control changes the total number of basic operations only by a constant factor, so (the meaning of is given in Definition 3.1).
The storage used, beyond the input array, consists of the three words i, j, key, so the additional space is .
Besides worst-case complexity one can define average-case complexity, obtained by fixing a probability distribution on inputs and taking the expectation, and best-case complexity, attained on the most favourable input. The best case of insertion sort(Example 2.5) occurs on an already sorted input, with comparisons, that is . Quicksort is in the worst case yet on average over random permutations (Theorem 5.5[Sorting Algorithms]), and in practice it is this average that governs. See Sorting algorithms for details. Unless stated otherwise, every complexity in this article is worst-case.
3. The notations O, Ω and Θ
Section titled “3. The notations O, Ω and Θ”3.1. Definitions
Section titled “3.1. Definitions”From now on denote nonnegative real-valued functions defined on .
Definition 3.1(The notations O, Ω and Θ)
For a function , define the sets of functions , , by
Customarily one writes for , read ” is of order at most ”.
The order of the quantifiers is the crux. The constants and are chosen before ; choosing a convenient separately for each is not permitted. If this order is broken, then holds for arbitrary and (with ), and the notation becomes vacuous.
flowchart LR A["choose constants c and n0 first"] --> B["then for every n"] --> C["if n is at least n0 then f(n) is at most c·g(n)"]
The notations and strengthen one quantifier.
Definition 3.2(The notations o and ω)
When we say that is of strictly smaller order than .
Where said “for some ”, says “for every ”. That may be taken arbitrarily small means that tends to . The next proposition makes this precise.
3.2. A limit test and the calculus of O
Section titled “3.2. A limit test and the calculus of O”Proposition 3.3(The limit test)
Assume for all sufficiently large and that the limit exists (possibly ). Then:
- If then .
- If then .
- If then .
- If then and .
Proof(Proposition 3.3)
-
Since , taking in the definition of convergence gives an such that for . Multiplying by yields . Taking and in Definition 3.1 gives .
-
Assume in addition . Taking gives an such that for , that is, . With and we get , which together with part 1 gives .
-
Assume . Given any , take in the definition of convergence: there is an with , that is , for . As was arbitrary, Definition 3.2 gives .
-
Assume . For any , the definition of divergence supplies an with , that is , for . Hence . Rereading the same inequality as and noting that ranges over all positive reals as does, we obtain .
When the limit fails to exist the test is unusable. The notation itself remains meaningful nonetheless (see Exercise 8.4).
Proposition 3.4(Rules of calculation for O notation)
Let be nonnegative real-valued functions. The following hold.
- (Reflexivity) .
- (Transitivity) If and then .
- (Scalar multiples) If and then .
- (Sums) If and then , where denotes the pointwise maximum.
- (Products) If and then .
Proof(Proposition 3.4)
-
With and we have for every .
-
By hypothesis there are with for , and with for . For , substituting the second inequality into the first gives (the direction of the inequality is preserved because ). Take and .
-
If for , multiplying by gives . Replace the constant by .
-
For , using ,
Take the constant to be .
- For , since the two inequalities may be multiplied, giving .
Rule 4 is the tool used most often in practice. The everyday reasoning “an algorithm spending on preprocessing and on the main body costs overall” is nothing but an application of this rule.
Proposition 3.5(The order of a polynomial)
Let be an integer, let be real with , and suppose is nonnegative for all sufficiently large . Then .
Proof(Proposition 3.5)
First the upper bound. Put . For we have for , so
Hence with and .
Now the lower bound. Put (for we have and what follows is trivially true). For ,
where the last inequality uses , valid since . Taking , we have for , whence
With this gives . Combining the two bounds, .
3.3. Pitfalls of the notation
Section titled “3.3. Pitfalls of the notation”The equality sign in is not symmetric. The statement is correct, but one never writes . Read the sign as "" or "", from left to right. An occurrence of in the middle of a formula stands for “some function satisfying that condition”. For instance,
means “the difference between the left-hand side and is a function belonging to ”. This convention was codified by Knuth (reference [2]).
Inside notation the base of a logarithm need not be written. By the change-of-base formula , the functions and differ only by a positive constant factor, so . However, as versus shows, once the logarithm sits in an exponent the difference of base is no longer a constant factor. The base may be dropped inside only when the logarithm appears as a multiplicative factor.
4. The hierarchy of growth rates
Section titled “4. The hierarchy of growth rates”The intuitions ” is far smaller than ” and “an exponential is far larger than a polynomial” are made precise by the following theorem. We first prove the underlying lemma.
Lemma 4.1(Exponentials beat polynomials)
Let and be real. Then, as a limit in the real variable ,
Proof(Lemma 4.1)
We first treat the case in which runs through the natural numbers . Since we may write . Put , so that . By the binomial theorem, for ,
(here we used that each factor is at least the smallest one, ). If moreover , then , so
Since the exponent is negative and the right-hand side tends to as . As , the squeeze theorem gives .
Now the real variable case. For put , so that and . Since and ,
As we have , and by the previous paragraph the right-hand side tends to . Hence .
Theorem 4.2(The hierarchy of growth rates)
Let , , and be arbitrary reals. Then
In particular, taking , and , the functions , , , are of strictly increasing order in this sequence.
Proof(Theorem 4.2)
First claim. Put , so that and as . Then
Since we have , so applying Lemma 4.1 with , and shows that this ratio tends to . By part 3 of Proposition 3.3, .
Second claim. Applying Lemma 4.1 directly with gives , and again part 3 of Proposition 3.3 yields .
Third claim. Put . For we may factor
Since , each factor satisfies , so the product is at most . Hence
and the right-hand side tends to as (here and are constants not depending on ). By the squeeze theorem , that is, .
The first claim says that however small is chosen, eventually exceeds : logarithms grow that slowly. The second says that eventually exceeds : exponentials grow that fast. These two facts are the source of the dramatic differences seen in the next section.
5. Reading the main complexity classes
Section titled “5. Reading the main complexity classes”5.1. The doubling rule
Section titled “5.1. The doubling rule”The handiest way to grasp the character of each class is to ask what happens to the running time when the input size is doubled.
Proposition 5.1(The ratio under doubling of the input)
Let and be constants and real. The following hold.
- If then .
- If then (the difference, not the ratio, is constant).
- If then .
- If then , which tends to as .
- If then .
Proof(Proposition 5.1)
Each case is a direct substitution.
- .
- .
- .
- . As we have , so the ratio tends to .
- .
Claim 5 expresses the horror of exponential time in a single line. Having solved an instance with , moving on to multiplies the time by .
Proposition 5.1 is a statement about functions of exactly those forms; the hypothesis alone does not imply . For a counterexample take . Since we have , yet oscillates between and and does not converge. Because discards constant factors, it does not pin down the limit of the ratio.
5.2. The numbers
Section titled “5.2. The numbers”Example 5.3(Operation counts and running times in practice)
Assume a machine performing basic operations per second. The operation counts are as follows.
| astronomical | |||||
| astronomical | |||||
| astronomical |
Translated into time:
| s | s | |
| s | s | |
| min | years |
Look at the row. Even at the factor is only , so is at most thirty times . Over the range of realistic input sizes, is barely distinguishable from . This is why algorithms such as comparison sorting and the fast Fourier transform are treated as “essentially linear”. The same applies to : as grows a hundred-million-fold from to , the value of grows only ninefold, from to . That is why binary search appears to finish instantly regardless of the number of elements (see Theorem 3.3[探索アルゴリズム] and Search algorithms).
Look at the exponential side as well. Performing operations takes about days, and operations about years, roughly times the age of the universe (about years). Factorials grow even faster: corresponds to about years.
5.3. A faster machine will not save us
Section titled “5.3. A faster machine will not save us”The essential difficulty of exponential time is clearest in the following comparison.
Example 5.4(What if the machine becomes 1000 times faster)
We compare the largest that can be handled within one second on a machine performing operations per second and on one performing .
| ops/s | ops/s | change | |
|---|---|---|---|
| about | |||
| about | |||
Let us verify the last row. Solving gives , so multiplying by increases by , that is, by about . This is a general fact independent of the machine’s speed: for the increase is .
In the row the improvement is a factor , in the row a factor — that is, the reciprocal power of the exponent. In general, for , a machine times faster handles larger by a factor .
The conclusion is unambiguous. For polynomial time, advances in hardware help; for exponential time, they hardly help at all. The only way through the exponential wall is a better algorithm.
Example 5.5(From brute force to dynamic programming)
Given positive integers and a target , decide whether some subset sums to exactly (the subset-sum problem). Brute force enumerates all subsets, examining of them, for a total of . For this is operations, about hours on a machine doing operations per second.
By contrast, dynamic programming that fills a table recording whether the sum is attainable from the first items costs only . For and that is operations, or seconds — a speedup of more than thirty million, obtained not by changing the machine but simply by no longer recomputing the same partial sums over and over (recurrences of this shape and their complexity are treated in Corollary 6.4[動的計画法]; see Dynamic programming).
Note that is not polynomial in the input size. Representing requires bits, so can be exponentially large in the input size. Complexities of this kind are called pseudo-polynomial time.
5.4. The complexity of data structures
Section titled “5.4. The complexity of data structures”The same operation can have different complexity depending on the data structure. Here are the worst-case complexities of the standard structures, with the number of stored elements.
| operation | unsorted array | sorted array | linked list | balanced BST | hash table |
|---|---|---|---|---|---|
| search for a value | avg. / worst | ||||
| insertion | (at the end) | (position known) | avg. | ||
| deletion | (search included) | (position known) | avg. | ||
| retrieval of the minimum |
There is no universally best structure. A sorted array searches quickly but requires shifting everything on insertion, while a linked list inserts quickly but needs time to reach the -th element (Proposition 4.2[Fundamental Data Structures]). One decides what should be fast first, and chooses the structure afterwards. The definitions of these structures and the proofs of these complexities are treated in Fundamental data structures.
The entry ” for appending to an unsorted array” assumes there is spare capacity. When the capacity is exhausted, a new region is allocated and all elements are copied, so that particular operation costs . If, however, the capacity is doubled each time it runs out, then starting from capacity and performing insertions, copying occurs only when the number of elements is with , and the total number of copies is
Since the total cost of insertions is , the average per operation is . Complexity averaged over a whole sequence of operations in this way is called amortised complexity (stated as a theorem, this estimate is Theorem 3.3[Fundamental Data Structures]). It is a different notion from the worst-case complexity of an individual operation, and the two should be kept apart.
6. Divide and conquer: from a recurrence to an order
Section titled “6. Divide and conquer: from a recurrence to an order”The complexity of a recursive algorithm appears as a recurrence. For merge sort, an array of length is split in half, the halves are sorted recursively, and merging takes time, giving (Theorem 4.2[Sorting Algorithms]). Recurrences of this shape are solved at a stroke by the following theorem.
Theorem 6.1(The master theorem)
Let and be real, let be a constant, and let be a positive-valued function defined on the powers of . Suppose the function satisfies
With ranging over the powers of , the following hold.
- If for some , then .
- If , then .
- If for some and, in addition, there is a constant with for all (the regularity condition), then .
Proof(Theorem 6.1)
Let . Unfolding the recurrence times gives
(by induction on : for both sides equal , and if the identity holds for , substituting it into gives it for ). Here
so the first term is . Since , we always have . It remains to estimate the sum .
Case 1. By hypothesis there is a with for all sufficiently large powers of . Then
Since , we have , and the formula for a geometric series gives
(using ). Hence and . The lower bound is the inequality noted above, so together .
Case 2. By hypothesis there are with . Since , every term of the sum lies between and . There are terms, so
As and differ only by a positive constant factor (Remark 3.7), . The first term is absorbed into this, so .
Case 3. From the regularity condition one proves by induction on . Indeed, for this is an equality. Assuming it for and applying the regularity condition at , we have , whence
Therefore, since ,
Moreover, the hypothesis gives a such that for all sufficiently large , so the first term is also . Hence . On the other hand, keeping only the term of the expansion gives , so , and therefore .
In real algorithms need not be an integer, and the recurrence takes the form . It is known that the same conclusions as in Theorem 6.1 hold for this floor-function version; the proof is in Chapter 4 of Cormen et al. (reference [1]). That book also states the regularity condition in the weaker form “for all sufficiently large ”. Even in this weaker form the conclusion is unchanged, since at most terms violate the condition and each of them is . Techniques for recurrences to which the master theorem does not apply are treated in the Appendix.
Example 6.3(Applying the master theorem)
(a) Merge sort. For we have , , . Since , we get , which is case 2. Hence .
(b) Binary search. For we have , , . Since , we get and . Again case 2 applies, so .
(c) Strassen’s matrix multiplication. For we have , , . Since , taking gives , and holds. Thus case 1 applies and , in particular — an order strictly smaller than the of the naive triple loop.
(d) An instance of case 3. For we have , and with we get . The regularity condition holds because with . Hence : the cost of the topmost level of the recursion alone determines the total.
7. The dividing line of polynomial time
Section titled “7. The dividing line of polynomial time”All the classes seen so far — , , , — share the property of being bounded by a polynomial in , whereas and do not. As Example 5.4 showed, this boundary cannot be moved by improving the machine. This motivates the following definition.
Definition 7.1(Polynomial-time algorithm)
An algorithm runs in polynomial time if there is a constant with .
The position that polynomial time is the right definition of “efficient” goes back to Cobham and Edmonds. The definition has the drawback of admitting , but it is strongly justified on two counts. First, the set of polynomials is closed under addition, multiplication and composition, so combining polynomial-time algorithms as building blocks keeps the result polynomial-time. Second, the distinction does not depend on the details of the computational model: complexity differs only polynomially between the RAM model and Turing machines, so the answer to “is it solvable in polynomial time?” does not change when the model does.
Write for the class of decision problems solvable in polynomial time, and for the class of decision problems whose “yes” answers admit a certificate verifiable in polynomial time (Definition 4.1[P≠NP 予想とは何か]). The inclusion is immediate from the definitions, but whether the reverse inclusion holds has been open since the question was posed in 1971. This is the P vs NP problem, and thousands of problems — including subset sum and the travelling salesman problem — are tied to it in the form “if , then this problem has no polynomial-time algorithm”. See What is the P vs NP problem for details.
This is where the point of learning complexity notation lies. The notation is at once a tool for measuring the speed of individual programs and the common language in which one discusses what can and cannot be computed.
8. Exercises
Section titled “8. Exercises”Exercise 8.1Easy
Let . Show that by exhibiting explicit constants and as in Definition 3.1.
Solution
Upper bound. For we have , so . Also for . Hence for ,
so with and .
Lower bound. Since for and , we have for every . Hence with and .
Combining the two, with , , . Incidentally, the inequality (for ) is also guaranteed by , which follows from the first claim of Theorem 4.2; but here it comes directly from for (by induction on : , and if then ).
Exercise 8.2Standard
Show that . Do not use Stirling’s formula.
Solution
Upper bound. Since , taking of both sides (which is increasing) gives
Hence with and .
Lower bound. Let and keep only the larger half of the factors. There are at least indices with , and each such factor is at least , so
Taking ,
For we have , so . Hence
giving with and . Together we obtain .
This estimate is used in proving the lower bound on the worst-case number of comparisons in comparison sorting (Theorem 6.1[Sorting Algorithms]).
Exercise 8.3Standard
Solve the recurrence , (with a power of ). State explicitly which case of Theorem 6.1 applies and whether the regularity condition is satisfied.
Solution
Here , , . First compute .
Which case. Taking gives . For we have , so , and therefore . Thus the first condition of case 3 is met.
Regularity condition. For with ,
We may take , so the regularity condition holds (the inequality follows from ).
Conclusion. By case 3 of Theorem 6.1, . The branching factor loses to the shrinking factor , so the cost of the topmost level alone determines the total.
Exercise 8.4Hard
Construct an explicit pair of nonnegative functions with and , and prove it. This example shows that the hypothesis of Proposition 3.3 — the existence of the limit — is essential.
Solution
Construction. Define functions on by
Both are nonnegative.
Proof that . Suppose . Then there are and such that for every . Choose an even with (such an even number exists). For this we have and , so the inequality reads , that is . But , a contradiction. Hence .
Proof that . Run exactly the same argument with odd numbers in place of even ones. Assuming , take and an odd ; then and , so , a contradiction.
Relation to the limit. The ratio equals for even and for odd , so it oscillates as and has no limit. Since Proposition 3.3 assumes the existence of the limit, it does not apply to this example. The lesson of the exercise is that the ordering by notation is not a total order.
References
Section titled “References”- T. H. Cormen, C. E. Leiserson, R. L. Rivest, C. Stein, Introduction to Algorithms, 4th ed., MIT Press, 2022 — Chapter 3 (asymptotic notation) and Chapter 4 (divide and conquer, recurrences, and the floor-function form of the master theorem).
- D. E. Knuth, “Big Omicron and big Omega and big Theta”, ACM SIGACT News 8 (1976), 18–24. DOI: 10.1145/1008328.1008329 — the paper that systematised the use of , and for computer science.
- D. E. Knuth, The Art of Computer Programming, Volume 1: Fundamental Algorithms, 3rd ed., Addison-Wesley, 1997 — Section 1.2.11 (asymptotic representations).
- R. L. Graham, D. E. Knuth, O. Patashnik, Concrete Mathematics, 2nd ed., Addison-Wesley, 1994 — Chapter 9 (Asymptotics), with a detailed treatment of the techniques of asymptotic expansion.
- J. Kleinberg, É. Tardos, Algorithm Design, Addison-Wesley, 2005 — Chapter 2 (the basics of algorithm analysis and the standard complexity classes).
- M. R. Garey, D. S. Johnson, Computers and Intractability: A Guide to the Theory of NP-Completeness, W. H. Freeman, 1979 — Chapter 1, which contains a table contrasting polynomial and exponential time against improvements in machine speed.
Appendix: When the master theorem does not apply
Section titled “Appendix: When the master theorem does not apply”Theorem 6.1 was stated for a power of . Actual recurrences involve floor functions, and the shape of the splitting sometimes falls outside the scope of the master theorem. In such cases the substitution method — guess the answer and verify it by induction — is available. We illustrate it on the exact recurrence for merge sort.
Define and for (real merge sort splits into and ; we use this simplified form in order to exhibit the technique).
Upper bound. We show for all by strong induction on .
- : and , so holds.
- : and , so the bound holds.
- : here and , so the induction hypothesis applies and gives . Using and the monotonicity of ,
the last inequality following from .
Hence . The essential point is the leftover : the induction went through precisely because of that slack. Had we tried to prove with , the remainder would not have been at most and the induction would not have closed.
Lower bound. We first show that is nondecreasing, proving for by strong induction on . For we have . For we have , so the induction hypothesis (monotonicity of at arguments below ) gives . Hence
(for the right-hand side is precisely the defining recurrence for , and the same holds for ).
Next we compute the value at a power of two, . From and , induction on gives . Indeed, for we have , and if the formula holds for then
For general put , so that and . By monotonicity,
(using ). Hence , and together with the upper bound, .
The key to the substitution method is to fix the exact form to be proved before starting the induction. Assuming only an order such as and inducting leads to the classic error in which the constant grows at every step and diverges. Write the bound out with its constants, as in , and check that the induction step preserves the same constant.
Report an error in this article ・Operated by: Mugen Giken LLC ・Pricing ・Terms ・Legal notice
© 2026 夢現技研合同会社 ・Feeding the text to an LLM is welcome. Code samples are MIT licensed.