Simple Algorithm
Algorithms & Data Structures · Optimized · 22 min

Big-O Notation & Running Time

Counting steps, comparing growth rates, and knowing what fits in a second.

n100n^{100} is O(1.01n)O(1.01^n). That is true, and strange: the exponential overtakes the polynomial only once nn passes about 117,000. Asymptotic notation is exact about what happens eventually and silent about when, and using it well means knowing both. This lesson makes the notation precise, turns loops into sums, and turns a problem's constraints into the running time you must hit.

What you’ll learn

  • State the definitions of OO, Ω\Omega, Θ\Theta, oo and ω\omega, and prove bounds with explicit constants cc and n0n_0.
  • Keep two axes apart: which cost function (worst, best, average, expected, amortized) and which bound (OO, Ω\Omega, Θ\Theta).
  • Count the steps of nested, dependent, halving, harmonic and doubling loops with sums.
  • Measure input size correctly, in bits for numbers, and account for space as well as time.
  • Estimate the complexity of a code snippet and match it against a problem's constraints.

O, Ω and Θ, exactly

A running time is a function from input sizes to step counts, and asymptotic notation compares such functions while ignoring two things on purpose: constant factors, and small inputs. Throughout, ff and gg are nonnegative functions of nn.

DerivationProving 3n² + 5n + 7 = Θ(n²)
  1. 3n2+5n+7≤3n2+5n2+7n2=15n2(c=15, n0=1)3n^2 + 5n + 7 \le 3n^2 + 5n^2 + 7n^2 = 15n^2 \qquad (c = 15,\ n_0 = 1)

    An upper bound, with generous constants. For n≥1n \ge 1, 5n≤5n25n \le 5n^2 and 7≤7n27 \le 7n^2:

  2. 3n2+5n+7≤4n2(c=4, n0=7)3n^2 + 5n + 7 \le 4n^2 \qquad (c = 4,\ n_0 = 7)

    The same bound, with a tighter constant. 3n2+5n+7≤4n23n^2 + 5n + 7 \le 4n^2 exactly when n2−5n−7≥0n^2 - 5n - 7 \ge 0, which first holds at n=7n = 7 (49−35−7=749 - 35 - 7 = 7) and then for every larger nn:

  3. 3n2+5n+7≥3n2(c=3, n0=1)⟹3n2+5n+7=Θ(n2)3n^2 + 5n + 7 \ge 3n^2 \quad (c = 3,\ n_0 = 1)\qquad\Longrightarrow\qquad 3n^2 + 5n + 7 = \Theta(n^2)

    A lower bound. Every term is nonnegative, so

  4. 3n2+5n+7n=3n+5+7n→  n→∞  ∞\frac{3n^2 + 5n + 7}{n} = 3n + 5 + \frac{7}{n} \xrightarrow[\;n \to \infty\;]{} \infty

    It is not O(n)O(n). If 3n2+5n+7≤c n3n^2 + 5n + 7 \le c\,n held for all n≥n0n \ge n_0, dividing by nn would give 3n+5+7/n≤c3n + 5 + 7/n \le c for all large nn, which no constant satisfies:

The constants are not unique, and they are not the point: the definition asks only that some pair (c,n0)(c, n_0) works. Three reading rules prevent most mistakes:

  • The "=" is a one-way membership claim. n=O(n2)n = O(n^2) is true, because an upper bound need not be tight, but "O(n2)=nO(n^2) = n" means nothing. Say Θ\Theta when you mean a tight bound.
  • Limits settle most comparisons. If f(n)/g(n)→Lf(n)/g(n) \to L with 0<L<∞0 < L < \infty, then f=Θ(g)f = \Theta(g); if L=0L = 0, then f=o(g)f = o(g); if L=∞L = \infty, then f=ω(g)f = \omega(g). The converse fails: n(2+sin⁡n)=Θ(n)n(2 + \sin n) = \Theta(n), although its ratio to nn oscillates forever.
  • The base of a logarithm is a constant factor, log⁡an=log⁡bn/log⁡ba\log_a n = \log_b n / \log_b a, so O(log⁡n)O(\log n) needs no base. In an exponent, constants are not harmless: 4n=22n4^n = 2^{2n} is not O(2n)O(2^n).
Check your understanding

Which of these statements is true?

  1. 22n=O(2n)2^{2n} = O(2^n)
  2. nlog⁡n=Ω(n2)n \log n = \Omega(n^2)
  3. n100=O(1.01n)n^{100} = O(1.01^n)
  4. log⁡2(n!)=Θ(n)\log_2(n!) = \Theta(n)
Show the answer

C. n100=O(1.01n)n^{100} = O(1.01^n)

n100/1.01n→0n^{100} / 1.01^n \to 0: every exponential with base above 1 eventually outgrows every polynomial. "Eventually" is doing heavy lifting here: n100n^{100} is the larger one for every nn from 2 to 117,308, and 1.01n1.01^n takes over only from n=117,309n = 117{,}309 on.

Which running time? Worst, best, average

An algorithm has one running time per input, not per input size. To get a function of nn you must say how the inputs of size nn are combined, and that choice is a separate axis from OO, Ω\Omega and Θ\Theta.

Cost functionDefined asInsertion sort, nn distinct keys (comparisons)
Worst casethe maximum over inputs of size nnn(n−1)/2n(n-1)/2, on reversed input
Best casethe minimum over inputs of size nnn−1n - 1, on sorted input
Average casethe mean over a distribution of inputsn2+3n4−Hn≈n2/4\tfrac{n^2 + 3n}{4} - H_n \approx n^2/4, over random orders
Expectedfor each input, the mean over the algorithm's own random choices; then the worst inputnot randomized
Amortizedthe worst total over sequences of operations, divided by their numbernot a sequence of operations
Hn=1+12+⋯+1nH_n = 1 + \tfrac12 + \dots + \tfrac1n. Quicksort with random pivots is the standard example of an expected bound, and appending to a dynamic array of an amortized one.

Now combine the two axes. "Insertion sort is O(n2)O(n^2)" is true of every input. "Insertion sort is Θ(n2)\Theta(n^2)" is false as a claim about every input: on sorted input it makes n−1n - 1 comparisons. The precise statements are "its worst-case running time is Θ(n2)\Theta(n^2)" and "its best-case running time is Θ(n)\Theta(n)".

A lower bound on the worst case, such as "worst case Ω(n2)\Omega(n^2)", says that some inputs of each large size are that slow, not that all of them are.

Think first Quicksort with a uniformly random pivot makes about 1.39 nlog⁡2n1.39\,n\log_2 n comparisons on average, for every input. Is that an average-case bound?

No, it is an expected bound. The average is over the algorithm's own coin flips, and it holds for each fixed input, sorted and adversarial ones included. An average-case bound averages over inputs drawn from a distribution, and says nothing about the inputs that distribution rarely produces. The exact expectation is 2(n+1)Hn−4n2(n+1)H_n - 4n comparisons.

Counting loops

The running time of a loop is the sum, over its iterations, of the work done in each. So analysis turns code into sums, and sums into closed forms. Five shapes cover most of what you will meet:

python
def count_ops(n):
    ops = [0] * 5
    for i in range(n):                  # 1. independent nested loops
        for j in range(n):
            ops[0] += 1
    for i in range(n):                  # 2. dependent: j < i
        for j in range(i):
            ops[1] += 1
    k = n                               # 3. halving
    while k > 1:
        k //= 2
        ops[2] += 1
    for d in range(1, n + 1):           # 4. the multiples of d up to n
        for m in range(d, n + 1, d):
            ops[3] += 1
    i = 1                               # 5. doubling outer, inner up to i
    while i <= n:
        for j in range(i):
            ops[4] += 1
        i *= 2
    return ops

print(count_ops(1000))   # [1000000, 499500, 9, 7069, 1023]

Loop 4 is the shape of "for every dd, visit its multiples", as in listing the divisors of every number up to nn. Loop 5 is the shape of anything built by doubling.

DerivationFive sums
  1. ∑i=0n−1∑j=0n−11=n2\sum_{i=0}^{n-1}\sum_{j=0}^{n-1} 1 = n^2

    Independent loops multiply:

  2. ∑i=0n−1i=n(n−1)2=Θ(n2)\sum_{i=0}^{n-1} i = \frac{n(n-1)}{2} = \Theta(n^2)

    Dependent loops give an arithmetic series: half of loop 1, and still quadratic.

  3. #rounds=⌊log⁡2n⌋=Θ(log⁡n)(9 for n=1000)\#\text{rounds} = \lfloor \log_2 n \rfloor = \Theta(\log n) \qquad (9 \text{ for } n = 1000)

    Halving reaches 1 after ⌊log⁡2n⌋\lfloor \log_2 n \rfloor rounds, because after tt rounds k=⌊n/2t⌋k = \lfloor n / 2^t \rfloor:

  4. nHn−n  <  ∑d=1n⌊nd⌋  ≤  nHn  ≤  n(1+ln⁡n)⟹Θ(nlog⁡n)nH_n - n \;<\; \sum_{d=1}^{n} \Big\lfloor \frac{n}{d} \Big\rfloor \;\le\; nH_n \;\le\; n(1 + \ln n) \qquad\Longrightarrow\qquad \Theta(n \log n)

    Harmonic loops: the inner loop runs ⌊n/d⌋\lfloor n/d \rfloor times, with n/d−1<⌊n/d⌋≤n/dn/d - 1 < \lfloor n/d \rfloor \le n/d, and ln⁡(n+1)≤Hn≤1+ln⁡n\ln(n+1) \le H_n \le 1 + \ln n:

  5. ∑t=0⌊log⁡2n⌋2t=2⌊log⁡2n⌋+1−1<2n=Θ(n)(1023 for n=1000)\sum_{t=0}^{\lfloor \log_2 n \rfloor} 2^t = 2^{\lfloor \log_2 n \rfloor + 1} - 1 < 2n = \Theta(n) \qquad (1023 \text{ for } n = 1000)

    Geometric loops: when the work doubles every round, the last round dominates.

Predict before you look

Loop 4 runs its body ⌊n/d⌋\lfloor n/d \rfloor times for each dd. For n=1000n = 1000, about how many times does it run in total? (Loop 1 runs a million times.)

Show the answer

7069

Exactly ∑d≤1000⌊1000/d⌋=7069\sum_{d \le 1000} \lfloor 1000/d \rfloor = 7069, between nln⁡n≈6908n \ln n \approx 6908 and nHn≈7485nH_n \approx 7485. Two nested loops, yet Θ(nlog⁡n)\Theta(n\log n): the inner loop shrinks like n/dn/d. Counting how deeply loops are nested is not enough; count the iterations.

Growth rates, constants and the time limit

For constants a>0a > 0, ε>0\varepsilon > 0 and b>1b > 1, every power of a logarithm is o(nε)o(n^{\varepsilon}), every polynomial is o(bn)o(b^n), and every exponential is o(n!)o(n!). Limits of ratios, with l'Hôpital's rule where needed, prove each link of the chain:

1≺log⁡log⁡n≺log⁡n≺n≺n≺nlog⁡n≺n2≺n3≺2n≺n!≺nn1 \prec \log\log n \prec \log n \prec \sqrt{n} \prec n \prec n\log n \prec n^2 \prec n^3 \prec 2^n \prec n! \prec n^n
f≺gf \prec g means f=o(g)f = o(g). Any fixed power of log⁡n\log n, however large, still sits left of n\sqrt n.

Asymptotics speak only about large nn. For small inputs the constants decide: an algorithm that costs 20 nlog⁡2n20\,n\log_2 n steps loses to one that costs n2n^2 until n≈143n \approx 143. That is why library sorts finish small subarrays with insertion sort.

Contest and interview problems state nn and a time limit, usually 1–2 seconds. With the rule of thumb of about 10810^8 simple operations per second in a compiled language, the two together are a complexity budget:

nn up to aboutBudgetTypical algorithms
10–11O(n!)O(n!)all permutations
20–25O(2n⋅n)O(2^n \cdot n)all subsets, bitmask DP
40O(2n/2)O(2^{n/2})meet in the middle
500O(n3)O(n^3)Floyd–Warshall, interval DP
5,000O(n2)O(n^2)all pairs, quadratic DP
10610^6O(nlog⁡n)O(n\log n)sorting, heaps, binary search, segment trees
10810^8O(n)O(n)one pass, two pointers, prefix sums
largerO(log⁡n)O(\log n) or O(1)O(1)fast exponentiation, binary search on the answer, a formula
A rule of thumb, always. The widget's pure operation counts put the n2n^2 limit at 10,000 per second; the table says 5,000 to leave room for constant factors. Python is often 10–100 times slower per simple operation.

Space, and the size of a number

Space complexity counts memory the way time complexity counts steps, and usually what matters is the auxiliary space, the memory beyond the input itself: merge sort needs Θ(n)\Theta(n) extra cells, heapsort O(1)O(1). Recursion costs space as well, one stack frame per pending call. Quicksort's recursion can be nn calls deep, unless it recurses into the smaller part and loops on the larger, which caps the depth at log⁡2n\log_2 n.

Both are measured against the input size in bits. For most problems that is the number of items, up to the size of a word. When the input is a single number NN, though, the input is the b≈log⁡2Nb \approx \log_2 N bits that write it down, and that changes everything:

python
def is_prime(N):                # trial division: about sqrt(N) divisions
    if N < 2:
        return False
    d = 2
    while d * d <= N:
        if N % d == 0:
            return False
        d += 1
    return True

For the prime N=231−1N = 2^{31} - 1 the loop makes 46,339 divisions; for the prime 261−12^{61} - 1, about 1.5×1091.5 \times 10^9. Every 2 extra bits double the work: N=2b/2\sqrt N = 2^{b/2} is polynomial in the value but exponential in the length.

Algorithms that are polynomial in the numeric values of the input but not in its length are called pseudo-polynomial. The O(nW)O(nW) table for the knapsack problem is the famous one, and the Dynamic Programming topic returns to it. Primality itself can be decided in time polynomial in bb (Agrawal, Kayal & Saxena, 2002), and in practice software uses the randomized Miller–Rabin test.

Think first A loop runs NN times on the input number NN. Is that linear time?

It is linear in the value NN, but the input has only b≈log⁡2Nb \approx \log_2 N bits, so N≈2bN \approx 2^b steps is exponential in the input size. Summing 1+2+⋯+N1 + 2 + \dots + N with a loop takes exponential time; the formula N(N+1)/2N(N+1)/2 takes a few multiplications of bb-bit numbers, which is polynomial.

Recognizing it

Two skills make up this lesson's "recognize it": reading code to get its complexity, and reading constraints to get the complexity you need. For code, find what each loop variable does (counts up by one, halves, doubles, or only moves forward) and sum the iterations. Watch for the two classic illusions: nested loops that are linear, and single loops that are quadratic.

Code shapeIterationsComplexity
for i in range(n): for j in range(i + 1, n):n(n−1)/2n(n-1)/2 pairsΘ(n2)\Theta(n^2)
while lo < hi: halving the range [lo, hi)about log⁡2n\log_2 nΘ(log⁡n)\Theta(\log n)
i = 1; while i < n: i *= 3⌈log⁡3n⌉\lceil \log_3 n \rceilΘ(log⁡n)\Theta(\log n)
for d in range(1, n + 1): for m in range(d, n + 1, d):about nln⁡nn \ln nΘ(nlog⁡n)\Theta(n\log n)
j = 0, then for i in range(n): while j < n and ok(i, j): j += 1at most 2n2n: j never moves backΘ(n)\Theta(n), though nested
for x in queries: if x in lst: with a list of nn itemsq⋅nq \cdot n, hidden in inΘ(qn)\Theta(qn), though single
The last two rows are the illusions. The pointer j is shared by all values of i and only moves forward, so the inner loop runs at most nn times in total: the two-pointer pattern. And in on a list scans it, so one innocent line hides a loop; a set makes each test O(1)O(1) expected.

Common mistakes

  • Counting loops instead of iterations: nested does not mean quadratic, and a single loop does not mean linear.
  • Forgetting hidden costs: list.pop(0), list.insert(0, x), x in list, slicing, string concatenation in a loop, and arithmetic on huge integers all cost more than one step.
  • Treating expected bounds as worst case: a hash map is O(1)O(1) per operation in expectation, and adversarial keys can make it linear.
  • Using the value of a number as its size, so that a loop up to NN looks linear.
  • Ignoring space: an n×nn \times n table for n=105n = 10^5 has 101010^{10} cells, far beyond any memory limit.
Check your understanding

Which of these runs in Θ(n)\Theta(n) time in total?

  1. for i in range(n): for j in range(i): ...
  2. A pointer j starts at 0 and, inside for i in range(n), only ever moves forward, at most up to n
  3. for i in range(n): if a[i] in b: ..., where b is a list of nn items
  4. for i in range(1, n): k = i; while k > 1: k //= 2
Show the answer

B. A pointer j starts at 0 and, inside for i in range(n), only ever moves forward, at most up to n

The shared pointer moves forward at most nn times over the whole run, and the outer loop runs nn times, so the total is at most 2n2n steps, whatever the nesting looks like. This is the two-pointer pattern; the Optimized lesson Amortized Analysis makes the "total, not per iteration" argument formal.

Key takeaways

  • f=O(g)f = O(g), Ω(g)\Omega(g), Θ(g)\Theta(g) mean f≤cgf \le cg, f≥cgf \ge cg, or both, for all n≥n0n \ge n_0; oo and ω\omega are the strict versions, and the limit of f/gf/g settles most comparisons.
  • Worst, best, average, expected and amortized cost form a separate axis from OO, Ω\Omega, Θ\Theta: always say which cost function a bound is about.
  • Turn loops into sums: dependent loops give n(n−1)/2n(n-1)/2, halving gives ⌊log⁡2n⌋\lfloor\log_2 n\rfloor, harmonic loops Θ(nlog⁡n)\Theta(n\log n), doubling loops Θ(n)\Theta(n). Count iterations, not nesting.
  • Measure input size in bits: an O(N)O(\sqrt N) loop over a number NN is exponential in its log⁡2N\log_2 N bits, and O(nW)O(nW) knapsack is pseudo-polynomial.
  • At about 10810^8 simple operations per second, constraints become a budget: about n≤5000n \le 5000 for O(n2)O(n^2) and 10610^6 for O(nlog⁡n)O(n\log n); constants, caches and hidden costs decide the rest.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Which is the most precise true statement about f(n)=5nlog⁡2n+100n+7f(n) = 5n\log_2 n + 100n + 7?

  1. f(n)=O(n2)f(n) = O(n^2)
  2. f(n)=Θ(n)f(n) = \Theta(n)
  3. f(n)=Θ(nlog⁡n)f(n) = \Theta(n\log n)
  4. f(n)=Ω(n2)f(n) = \Omega(n^2)
Show the answer

C. f(n)=Θ(nlog⁡n)f(n) = \Theta(n\log n)

The 5nlog⁡2n5n\log_2 n term dominates, since 100n/(nlog⁡2n)→0100n / (n\log_2 n) \to 0. So f=Θ(nlog⁡n)f = \Theta(n\log n), which says both O(nlog⁡n)O(n\log n) and Ω(nlog⁡n)\Omega(n\log n). The bound O(n2)O(n^2) is true but loose.

Question 2

How many times does i = 1; while i < n: i *= 3 run its body?

  1. About n/3n/3
  2. ⌈log⁡3n⌉\lceil \log_3 n \rceil, which is Θ(log⁡n)\Theta(\log n)
  3. About n\sqrt n
  4. Three times
Show the answer

B. ⌈log⁡3n⌉\lceil \log_3 n \rceil, which is Θ(log⁡n)\Theta(\log n)

After tt rounds i=3ti = 3^t, and the loop stops at the first tt with 3t≥n3^t \ge n: t=⌈log⁡3n⌉t = \lceil \log_3 n \rceil, which is 7 for n=1000n = 1000 and 13 for n=106n = 10^6. The base only changes a constant factor: log⁡3n=log⁡2n/log⁡23\log_3 n = \log_2 n / \log_2 3.

Question 3

An algorithm's worst-case running time is Θ(n2)\Theta(n^2). What follows?

  1. Every input of size nn takes about n2n^2 steps
  2. Its average-case running time is Θ(n2)\Theta(n^2)
  3. Its best-case running time is Ω(n2)\Omega(n^2)
  4. No input of size nn takes more than Cn2Cn^2 steps, and for every large nn some input takes at least cn2cn^2
Show the answer

D. No input of size nn takes more than Cn2Cn^2 steps, and for every large nn some input takes at least cn2cn^2

A Θ\Theta bound on the maximum over inputs bounds every input from above, and says that the maximum itself grows like n2n^2. It says nothing about typical or easy inputs: insertion sort's worst case is Θ(n2)\Theta(n^2) and its best case Θ(n)\Theta(n).

Question 4

What is the total running time of i = 1; while i <= n: (do i steps of work); i *= 2?

  1. Θ(nlog⁡n)\Theta(n\log n): about log⁡n\log n rounds of up to nn work
  2. Θ(n)\Theta(n)
  3. Θ(log⁡n)\Theta(\log n)
  4. Θ(n2)\Theta(n^2)
Show the answer

B. Θ(n)\Theta(n)

The work is 1+2+4+⋯+2⌊log⁡2n⌋<2n1 + 2 + 4 + \dots + 2^{\lfloor \log_2 n \rfloor} < 2n: a geometric series is dominated by its last term. Bounding every round by the largest one overestimates by a log factor.

Question 5

Trial division tests whether NN is prime with O(N)O(\sqrt N) arithmetic operations. Why is it not a polynomial-time algorithm?

  1. Because N\sqrt N is not a polynomial
  2. Because division is slower than addition
  3. Because the input is the b≈log⁡2Nb \approx \log_2 N bits of NN, and N≈2b/2\sqrt N \approx 2^{b/2} is exponential in bb
  4. It is polynomial: O(N)O(\sqrt N) beats O(N)O(N)
Show the answer

C. Because the input is the b≈log⁡2Nb \approx \log_2 N bits of NN, and N≈2b/2\sqrt N \approx 2^{b/2} is exponential in bb

Complexity is measured against the length of the input. A 61-bit number needs over a billion trial divisions, and every 2 extra bits double that. Polynomial-time primality tests run in time polynomial in bb.

Go deeper

Further reading

  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 3, "Characterizing Running Times".
  • D. E. Knuth, "Big Omicron and Big Omega and Big Theta," ACM SIGACT News 8(2) (1976), 18–24.
  • R. L. Graham, D. E. Knuth & O. Patashnik, Concrete Mathematics, 2nd ed. (Addison-Wesley, 1994), chapters 2, "Sums", and 9, "Asymptotics".
  • R. Sedgewick & K. Wayne, Algorithms, 4th ed. (Addison-Wesley, 2011), §1.4, "Analysis of Algorithms".