Module contents
Lesson 1 of 33Review 80 min

Cost models and asymptotic analysis of algorithms

A detailed review of efficient algorithms, including RAM and word-RAM models, input size in bits, worst and average cases, and space complexity. Apply O, Ω and Θ to cost functions, compare theory with doubling experiments and log-log plots, and examine algorithmic complexity attacks where worst cases can cause denial of service.

After this lesson you can

  • Count operations in the RAM model and justify when constant cost per operation is reasonable.
  • Classify cost functions with O, Ω and Θ and prove relationships using their definitions.
  • Distinguish polynomial from pseudopolynomial algorithms by measuring input size in bits.
  • Estimate an implementation's growth exponent empirically and identify discrepancies from the analysis.
  • Identify points in real code exposed to algorithmic complexity attacks.

Before you start

Motivation: the same problem in seconds or centuries

You have a million numbers to sort. Two programmers write two correct algorithms. The first compares every pair and takes on the order of n2=1012n^2 = 10^{12} operations; the second takes on the order of nlog⁡2n≈2⋅107n\log_2 n \approx 2\cdot 10^7. On a machine that executes 10910^9 operations per second, the second finishes in two hundredths of a second and the first in 10001000 s, almost seventeen minutes. No low-level optimization closes a fifty-thousand-fold gap, and the gap grows with nn.

An exponential algorithm brings a different kind of contrast. Trying all 21002^{100} subsets of a set of one hundred elements takes 1.3⋅10301.3\cdot 10^{30} operations. At 10910^9 per second, that is roughly 4⋅10134\cdot 10^{13} years, or three thousand times the age of the universe. The difficulty lies in the shape of the function.

Algorithm analysis therefore focuses on the order of growth of cost, initially setting constants aside. To make that meaningful, we must specify what we count (a cost model), when one function grows like another (asymptotic notation), and how theory compares with measured time, because models simplify reality and sometimes break down. This lesson reviews those three ingredients and what happens when an attacker chooses the worst case. Everything that follows in the module, including sorting, divide and conquer, data structures, graphs and NP-completeness, builds on them. We also add cost analysis to the loop invariants from program logic used to prove correctness.

InteractiveThe growth race
log⁡n\log n
nn
100 nlog⁡n100\,n\log n
n2n^2
2n2^n
n!n!
110³10⁶10⁹10¹²10¹⁵10¹⁸over 10¹⁸n ≈ 8.6×10¹³n ≈ 2.5×10¹⁰n ≈ 9.3×10⁶n ≈ 46n ≈ 16
Axis: nn on a logarithmic scale from 1 to 101810^{18}. Available time: 1 day; 8.6×10¹³ operations.
Time budget
10^9.0
Multiplicative constant
×100
Functions
Operations within budget8.6×10¹³
n2n^2 exceeds nlog⁡nn\log n fromn = 997
n2n^2 with ×1000n ×31.6
2n2^n with ×1000n + 10.0
Even though nlog⁡nn\log n costs ×100 per step, from n=997n = 997 it beats n2n^2 by a growing margin.
Each track shows input size nn on a logarithmic scale. The bar reaches the largest nn that fits within the chosen time budget. Change machine speed and constants, and activate “Machine ×1000”: polynomial classes multiply their boundary, while exponential classes move it only slightly.

Three observations from the figure. First, for n2n^2 a machine one thousand times faster multiplies the boundary by 1000≈31.6\sqrt{1000} \approx 31.6; for n3n^3, by 1010; for 2n2^n it adds only log⁡21000≈10\log_2 1000 \approx 10 elements. A multiplicative speedup becomes an additive increase in manageable size. Second, the constant matters less than the order. Set the constant for nlog⁡nn\log n to 100100 and leave that of n2n^2 at 11. The second wins for small nn, but from n=997n = 997 onward the first wins (solve 100log⁡2n=n100\log_2 n = n). Third, n!n! is even worse than 2n2^n, yet sometimes remains the only known approach, as in brute-force traveling salesman.

The RAM model: the cost of an operation

To count operations, we must specify what an operation is. A real language has thousands of instructions whose costs depend on hardware, so classical analysis uses an abstract machine.

The uniform model is reasonable as long as the numbers fit in a word: indices, counters, lengths, comparisons of fixed-size keys and hashes. A 6464-bit processor performs these operations in one or a few cycles. The assumption fails when operands grow with nn. Multiplying two nn-bit numbers by the schoolbook method requires Θ(n2)\Theta(n^2) bit operations, or Θ((n/w)2)\Theta((n/w)^2) word operations. Karatsuba reduces this to O(nlog⁡23)≈O(n1.585)O(n^{\log_2 3}) \approx O(n^{1.585}) and Harvey and van der Hoeven’s algorithm (2019) to O(nlog⁡n)O(n\log n). None is O(1)O(1).

For example, compute FnF_n, the nnth Fibonacci number, with the usual loop. In the uniform model there are nn additions, or Θ(n)\Theta(n). But Fn≈φn/5F_n \approx \varphi^n/\sqrt 5 has nlog⁡2φ≈0.694 nn\log_2\varphi \approx 0.694\,n bits, so adding the last two numbers costs Θ(n)\Theta(n) bit operations and the total is Θ(n2)\Theta(n^2).

[ ]Fibonacci: uniform cost versus bit costBrowser
import math

def fib_coste(n):
    a, b = 0, 1
    sumas = bits = 0
    for _ in range(n):
        bits += max(a.bit_length(), b.bit_length(), 1)   # coste de a + b contado en bits
        a, b = b, a + b
        sumas += 1
    return a, sumas, bits

print(f"{'n':>6} {'sumas':>6} {'bits de F_n':>12} {'coste en bits':>14} {'bits / n^2':>11}")
for n in (100, 200, 400, 800, 1600, 3200):
    f, sumas, bits = fib_coste(n)
    print(f"{n:6d} {sumas:6d} {f.bit_length():12d} {bits:14d} {bits / n**2:11.3f}")
print("límite teórico:", math.log2((1 + 5**0.5) / 2) / 2)

The number of additions grows as nn and the bit cost as n2n^2. The ratio bits / n^2 approaches 12log⁡2φ≈0.347\tfrac12\log_2\varphi \approx 0.347. The right model depends on the question. To sort nn keys of 6464 bits, the uniform model is appropriate. For factorization, computing 22k2^{2^k} or arbitrary-precision arithmetic, we must count bits. Other models answer other questions. The comparison model counts only comparisons, forming the basis for lower bounds in the next lesson. The external-memory model charges for moving blocks between memory levels (the I/O model). At the end of this lesson, a memory-hierarchy example will show where the RAM model breaks down.

Asymptotic notation for costs

Once a model is fixed, cost is a function T:N→R≥0T:\N \to \R_{\ge 0} of input size. We want to compare such functions while ignoring multiplicative constants and behavior for small nn. The notation OO appeared in calculus as Landau notation. Here we define its use for costs, with all quantifiers explicit.

Notice the order of quantifiers: ∃c ∃n0 ∀n≥n0\exists c\ \exists n_0\ \forall n \ge n_0. The constant and threshold are chosen before nn and apply simultaneously to all later nn. If the order were reversed, «for each nn there exists a cc», every pair of positive functions would be related, because c=f(n)/g(n)c = f(n)/g(n) suffices at each point. Explore this structure in the figure.

InteractiveWitnesses for the big-O definition
f(n)=3n2+10nf(n) = 3n^2 + 10n versus c g(n)=4.00 (n2)c\,g(n) = 4.00\,(n^2)
Ratio f(n)/g(n)f(n)/g(n) versus height cc: it must stay below from n0n_0 onward
c = 4.00
  • f(n)f(n)
  • c g(n)c\,g(n) and height cc
  • f(n)/g(n)f(n)/g(n)
  • first n≥n0n \ge n_0 that fails
  • region n≥n0n \ge n_0
4.00
3
f(n)f(n)3n2+10n3n^2 + 10n
g(n)g(n)n2n^2
Is f=O(g)f = O(g)?to discover
Minimum cc for this n0n_06.33
The inequality fails at n=3n = 3: f(3)=57f(3) = 57 and c g(3)=36c\,g(3) = 36. Increase cc or n0n_0.
Choose a pair f,gf, g. Set cc and n0n_0 with the sliders, or drag n0n_0 along the axis, until f/gf/g stays below height cc from n0n_0 onward. If the relation is false, the interactive shows an nn that breaks your choice, and there will always be a larger one. Try nlog⁡nn\log n versus 100 n100\,n: the relation is false, but fails so late that no measurement would detect it.

Three takeaways. (1) cc and n0n_0 trade off against one another. For 100 n100\,n versus n2n^2, c=1c = 1 requires n0=100n_0 = 100, while c=10c = 10 requires only n0=10n_0 = 10. (2) A false relationship is refuted by a family of violations escaping every cc, rather than a single case. (3) f∉O(g)f \notin O(g) can mean that ff exceeds gg only beyond an astronomical nn, beyond the reach of timing experiments.

The practical criterion for deciding most relationships is the ratio.

Proof

Case L=0L = 0: given c>0c > 0, the definition of a limit with ε=c\varepsilon = c gives n0n_0 such that f(n)/g(n)<cf(n)/g(n) < c for n≥n0n \ge n_0, or f(n)<c g(n)f(n) < c\,g(n). This is f∈o(g)f \in o(g), and o(g)⊆O(g)o(g) \subseteq O(g) because it suffices to take c=1c = 1.

Case 0<L<∞0 < L < \infty: taking ε=L/2\varepsilon = L/2 gives n0n_0 such that L/2≤f(n)/g(n)≤3L/2L/2 \le f(n)/g(n) \le 3L/2 for n≥n0n \ge n_0. This gives both f∈O(g)f \in O(g) (with c=3L/2c = 3L/2) and f∈Ω(g)f \in \Omega(g) (with c=L/2c = L/2).

Case L=∞L = \infty: g(n)/f(n)→0g(n)/f(n) \to 0, which by the first case is g∈o(f)g \in o(f), or f∈ω(g)f \in \omega(g).

∎

The converse is false: f(n)=(2+sin⁡n) nf(n) = (2 + \sin n)\,n is Θ(n)\Theta(n) and f(n)/nf(n)/n oscillates without a limit. The criterion is therefore a tool rather than the definition. To compare functions with logarithms and exponents, taking logarithms helps: f∈O(g)f \in O(g) if ln⁡f−ln⁡g\ln f - \ln g is bounded above. These rules are used throughout:

  • Constants and sums: c f∈Θ(f)c\,f \in \Theta(f) and f1+f2∈Θ(max⁡{f1,f2})f_1 + f_2 \in \Theta(\max\{f_1, f_2\}). A polynomial is Θ\Theta of its dominant term.
  • Transitivity: f∈O(g)f \in O(g) and g∈O(h)g \in O(h) imply f∈O(h)f \in O(h); likewise for Ω\Omega, Θ\Theta, oo, ω\omega.
  • Logarithms: the base does not matter, log⁡an=Θ(log⁡bn)\log_a n = \Theta(\log_b n); but log⁡n∈o(nε)\log n \in o(n^\varepsilon) for every ε>0\varepsilon > 0 and log⁡kn∈o(nε)\log^k n \in o(n^\varepsilon) for every kk.
  • Polynomials and exponentials: nk∈o(bn)n^k \in o(b^n) for every kk and every b>1b > 1.
  • Exponents: a constant added to an exponent is absorbed, while one that multiplies it is not. 2n+1=2⋅2n∈Θ(2n)2^{n+1} = 2\cdot 2^n \in \Theta(2^n), but 22n=(2n)2∉O(2n)2^{2n} = (2^n)^2 \notin O(2^n). Inside a logarithm the reverse happens: the exponent becomes an absorbed factor, so log⁡(n2)=2log⁡n∈Θ(log⁡n)\log(n^2) = 2\log n \in \Theta(\log n) although n2∉Θ(n)n^2 \notin \Theta(n).

Using these rules, the classes throughout the course are ordered as follows. Each row’s representative is oo of the next row’s, so each O(⋅)O(\cdot) is strictly contained in the next.

ClassTypical example
Θ(1)\Theta(1)access an array position
Θ(log⁡n)\Theta(\log n)binary search
Θ(n)\Theta(n)traverse a list, sum
Θ(nlog⁡n)\Theta(n\log n)mergesort, heapsort
Θ(n2)\Theta(n^2)insertion sort, all pairs
Θ(n3)\Theta(n^3)naive matrix multiplication, Floyd-Warshall
Θ(2n)\Theta(2^n)enumerate all subsets
Θ(n!)\Theta(n!)enumerate all permutations

Worst, best and average case

Even with a model and notation, a question remains. An algorithm’s cost depends on which input of size nn it receives. There are several ways to turn the cost of each input into a function of nn.

Linear search for a value present in an array of nn elements illustrates this. Tmin⁡=1T_{\min} = 1 comparison is needed if it appears first, Tmax⁡=nT_{\max} = n if it appears last, and also nn if it may be absent. If its position is uniform, Tmed=(n+1)/2T_{\text{med}} = (n+1)/2. The average case is not a property of the algorithm alone: it depends on the distribution. If sought values almost always appear near the start, the average is nearly 11.

The most frequent and dangerous confusion is between average-case cost and the expected cost of a randomized algorithm:

  • Average case: randomness lies in the input, whose distribution is assumed. The algorithm is deterministic. If the assumption fails, the guarantee disappears.
  • Randomized expected cost: randomness lies in the algorithm, which tosses coins. The guarantee applies to each input without assumptions about its distribution.

Quicksort is a useful case study, developed in the randomized quicksort lesson. With the first element as pivot, it makes ≈2nln⁡n\approx 2n\ln n comparisons on average over uniform permutations, but n(n−1)/2n(n-1)/2 on already sorted input. With a uniformly random pivot, its expected number of comparisons on every input is 2(n+1)Hn−4n2(n+1)H_n - 4n, where Hn=∑k≤n1/kH_n = \sum_{k \le n} 1/k is the harmonic number. The figure matches the average case, with a different interpretation.

[ ]Three different quantities for the same algorithmBrowser
import math, random

def busqueda_lineal(a, x):
    comps = 0
    for v in a:
        comps += 1
        if v == x:
            break
    return comps

n = 1000
a = list(range(n))
print("búsqueda lineal: peor", busqueda_lineal(a, -1), " mejor", busqueda_lineal(a, 0),
      " medio (posición uniforme)", sum(busqueda_lineal(a, x) for x in a) / n, " (n+1)/2 =", (n + 1) / 2)

def quicksort_comps(v, regla, rng):
    """Comparaciones de un quicksort con partición de Lomuto; el pivote es el primero o uno al azar."""
    v = list(v)
    comps = 0
    pila = [(0, len(v) - 1)]
    while pila:
        lo, hi = pila.pop()
        if lo >= hi:
            continue
        p = lo if regla == "primero" else rng.randint(lo, hi)
        v[p], v[hi] = v[hi], v[p]
        piv, i = v[hi], lo
        for j in range(lo, hi):
            comps += 1
            if v[j] < piv:
                v[i], v[j] = v[j], v[i]
                i += 1
        v[i], v[hi] = v[hi], v[i]
        pila += [(lo, i - 1), (i + 1, hi)]
    return comps

rng = random.Random(1)
print(f"{'n':>5} {'primero, aleatoria':>19} {'primero, ordenada':>18} {'aleatorio, ordenada':>20} {'2(n+1)H_n-4n':>13}")
for n in (250, 500, 1000):
    perm = list(range(n))
    medio = []
    for _ in range(20):
        rng.shuffle(perm)
        medio.append(quicksort_comps(perm, "primero", rng))
    orden = list(range(n))
    c_ord = quicksort_comps(orden, "primero", rng)
    c_alea = sum(quicksort_comps(orden, "aleatorio", rng) for _ in range(20)) / 20
    H = sum(1 / k for k in range(1, n + 1))
    print(f"{n:5d} {sum(medio) / 20:19.0f} {c_ord:18d} {c_alea:20.0f} {2 * (n + 1) * H - 4 * n:13.0f}")

Look at the «aleatorio, ordenada» column: with a random pivot, sorted input is no longer bad, and the result follows the formula in the last column. The «primero, ordenada» column is exactly n(n−1)/2n(n-1)/2 because sorted input remains a bad input for a fixed pivot. An attacker can exploit this distinction, which we revisit later.

Input size is measured in bits

So far nn has simply meant «input size». We must define it for a coherent theory.

For lists of fixed-size numbers, nn elements correspond to Θ(n)\Theta(n) bits, so there is no discrepancy. But when the input is a number, the difference is enormous: NN and log⁡2N\log_2 N are exponentially far apart.

The canonical example is trial-division primality testing. To decide whether NN is prime, try divisors d=2,3,…,⌊N⌋d = 2, 3, \dots, \lfloor \sqrt N \rfloor. This takes N\sqrt N steps, which seems small. But the input takes b≈log⁡2Nb \approx \log_2 N bits, so N=2b/2\sqrt N = 2^{b/2} is exponential in its size.

Proof

By Bertrand’s postulate, there is a prime pp with 2b−1<p<2b2^{b-1} < p < 2^b, having exactly bb bits. Since pp is prime, no divisor d≤⌊p⌋d \le \lfloor\sqrt p\rfloor divides it, so the algorithm tries all of them and performs ⌊p⌋−1\lfloor\sqrt p\rfloor - 1 divisions. Since p>2(b−1)/2\sqrt p > 2^{(b-1)/2}, there are at least 2(b−1)/2−22^{(b-1)/2} - 2. An exponential in bb eventually exceeds any polynomial in bb.

∎

The same happens with 0/1 knapsack with capacity WW and nn items. Classical dynamic programming fills a table of n×Wn \times W cells, using O(nW)O(nW) operations, which looks polynomial. But WW takes log⁡2W\log_2 W bits: every additional capacity bit doubles the work. This is the prototypical pseudopolynomial algorithm, studied in the knapsack lesson.

[ ]Steps versus the number of bitsBrowser
import math, random, time

def division_por_prueba(N):
    pasos, d = 0, 2
    while d * d <= N:
        pasos += 1
        if N % d == 0:
            return False, pasos
        d += 1
    return True, pasos

def primo_anterior(N):
    while not division_por_prueba(N)[0]:
        N -= 1
    return N

print("Primalidad por divisiones sobre primos de b bits")
print(f"{'b':>3} {'primo':>11} {'pasos':>7} {'2^(b/2)':>8}")
for b in range(10, 29, 4):
    p = primo_anterior(2**b - 1)
    _, pasos = division_por_prueba(p)
    print(f"{b:3d} {p:11d} {pasos:7d} {2 ** (b / 2):8.0f}")

def mochila(pesos, valores, W):
    mejor, ops = [0] * (W + 1), 0
    for w, v in zip(pesos, valores):
        for c in range(W, w - 1, -1):
            ops += 1
            mejor[c] = max(mejor[c], mejor[c - w] + v)
    return mejor[W], ops

print("\nMochila 0/1 con n = 30 objetos y capacidad W de b bits")
rr = random.Random(7)
for b in (8, 10, 12, 14, 16):
    W = 2**b
    pesos = [rr.randint(W // 20, W // 5) for _ in range(30)]
    valores = [rr.randint(1, 100) for _ in range(30)]
    _, ops = mochila(pesos, valores, W)
    print(f"b = {b:2d}  W = {W:6d}  operaciones = {ops:8d}  ({ops / (30 * W):.2f} n·W)")
print("Con b = 64 serían", f"{30 * 2**64:.2e}", "operaciones.")

Every +4+4 increase in bb multiplies primality-test steps by 44, or 2\sqrt 2 per bit. Every +2+2 increase in bb multiplies knapsack operations by 44, or 22 per bit. Both grow exponentially in the number of bits. A pseudopolynomial algorithm does not make its problem polynomial. This distinguishes knapsack, which is weakly NP-complete, from strongly NP-complete problems (NP-completeness). Primality is in P, via AKS (2002), but not because of trial division; a much faster randomized test is used in practice.

By contrast, Euclid’s greatest-common-divisor algorithm (Bézout’s identity) on two bb-bit numbers performs O(b)O(b) divisions. Its worst case is two consecutive Fibonacci numbers, with log⁡φN≈1.44 b\log_\varphi N \approx 1.44\,b steps. It is polynomial in input size. These arithmetic algorithms have similar-looking inputs but fall on opposite sides of the boundary, which is why size is measured in bits.

[ ]Euclid: linear in the number of bitsBrowser
import math

def euclides(a, b):
    pasos = 0
    while b:
        a, b = b, a % b
        pasos += 1
    return a, pasos

fibs = [1, 1]
while len(fibs) < 1500:
    fibs.append(fibs[-1] + fibs[-2])
print(f"{'bits de a':>9} {'pasos':>7} {'pasos / bits':>13}")
for k in (20, 40, 80, 160, 320, 640, 1280):
    a, b = fibs[k + 1], fibs[k]          # el peor caso: Fibonacci consecutivos
    _, pasos = euclides(a, b)
    print(f"{a.bit_length():9d} {pasos:7d} {pasos / a.bit_length():13.3f}")
print("1 / log2(phi) =", 1 / math.log2((1 + 5**0.5) / 2))

Space: auxiliary memory and stack

Time is one resource. An algorithm needing more memory than is available cannot finish, however fast it is.

A general relationship is S(n)=O(T(n))S(n) = O(T(n)), because each step touches at most one new cell. Space cannot exceed time, but can be much smaller. An exponential-time algorithm can use polynomial space, as when enumerating every circuit assignment while reusing memory.

Two stack examples. Summing a list recursively, as the first element plus the sum of the rest, creates nn nested calls and uses Θ(n)\Theta(n) space, although its running time matches the loop. Most languages, including Python, do not eliminate tail calls. Python’s default recursion limit is around 10001000 frames, so recursion of depth nn raises a runtime error for large nn. Recursive mergesort, by contrast, has depth Θ(log⁡n)\Theta(\log n) but needs an auxiliary buffer of nn elements, giving Θ(nlog⁡n)\Theta(n\log n) time and Θ(n)\Theta(n) space. Heapsort sorts in place. Compare algorithms in both dimensions, since they can often be traded off. A Python set uses extra memory proportional to nn so that x in s costs O(1)O(1) instead of O(n)O(n).

[ ]The recursion stack and auxiliary bufferBrowser
import math, random

def suma_rec(a, i, est):
    est["prof"] = max(est["prof"], est["act"])
    if i == len(a):
        return 0
    est["act"] += 1
    r = a[i] + suma_rec(a, i + 1, est)
    est["act"] -= 1
    return r

def mergesort(a):
    """Mergesort descendente con un único buffer auxiliar. Devuelve (profundidad de la pila, tamaño del buffer)."""
    n = len(a)
    buf = [0] * n
    est = {"prof": 0}
    def rec(lo, hi, prof):
        est["prof"] = max(est["prof"], prof)
        if hi - lo <= 1:
            return
        mid = (lo + hi) // 2
        rec(lo, mid, prof + 1)
        rec(mid, hi, prof + 1)
        i, j, k = lo, mid, lo
        while i < mid and j < hi:
            if a[i] <= a[j]:
                buf[k] = a[i]; i += 1
            else:
                buf[k] = a[j]; j += 1
            k += 1
        while i < mid:
            buf[k] = a[i]; i += 1; k += 1
        while j < hi:
            buf[k] = a[j]; j += 1; k += 1
        a[lo:hi] = buf[lo:hi]
    rec(0, n, 1)
    return est["prof"], n

for n in (100, 400, 900):
    est = {"prof": 0, "act": 0}
    suma_rec(list(range(n)), 0, est)
    arr = [random.random() for _ in range(n)]
    prof, aux = mergesort(arr)
    assert arr == sorted(arr)
    print(f"n = {n:4d}   suma recursiva: pila {est['prof']:4d}   mergesort: pila {prof:2d} "
          f"(⌈log2 n⌉ + 1 = {math.ceil(math.log2(n)) + 1}), buffer {aux}")

Measurement: doubling experiments and log-log fitting

Theory says an algorithm is Θ(n2)\Theta(n^2). Does your implementation behave that way? A hidden constant, a cost absent from the model or a simple mistake can change the result. Empirical growth analysis provides the experimental counterpart: measure time T(n)T(n) for sizes nn in a geometric progression, then fit a power law T(n)≈a nbT(n) \approx a\, n^b.

Two essentially equivalent tools follow.

Doubling experiment. If T(n)=anbT(n) = a n^b, then T(2n)/T(n)=2bT(2n)/T(n) = 2^b is independent of nn. Repeatedly double nn, calculate the ratio and take b=log⁡2(T(2n)/T(n))b = \log_2(T(2n)/T(n)). A ratio near 22 indicates linear growth, near 44 quadratic growth, and near 88 cubic growth. For nlog⁡nn\log n the ratio is 2 (1+1/log⁡2n)2\,(1 + 1/\log_2 n), which approaches 22 very slowly. At n=220n = 2^{20} it is 2.12.1, an apparent exponent of 1.071.07. This is why linear and near-linear growth can be hard to distinguish in practice.

Log-log fit. Taking logarithms makes log⁡T=log⁡a+b log⁡n\log T = \log a + b\,\log n a straight line, whose slope is obtained by least squares. Regression also gives a standard error, so the exponent is reported as b±2 eeb \pm 2\,\mathrm{ee}.

On a log-log scale a power law is a line, while phenomena outside the model appear as bends and steps. The memory hierarchy is the most important example. A modern processor has cache levels of increasing size and latency, on the order of a nanosecond for first-level cache and a hundred for main memory. While data fits in a level, access costs that level’s latency; when it overflows, access reaches the next. The RAM model assumes that access to M[i]M[i] always costs 11, which measurement can contradict.

InteractiveLog-log fit of real measurements
Measuring...
Task to analyze
none
RAM model predictsn log n, b slightly above 1
Fitted exponent bb...
Doubling ratio T(2n)/T(n)T(2n)/T(n)...
Points in fit0
These measurements run in your browser now. Each point is the minimum of three repeated series. Compare slopes with the reference lines b=1b = 1 and b=2b = 2. The local slope in the lower plot reveals steps: try random access, where the RAM model predicts a horizontal line.

Three readings of the figure. (1) Summation has a slope near 11 and the nested loop near 22: the model works there. (2) Sorting is Θ(nlog⁡n)\Theta(n\log n) and shows an exponent slightly above 11, around 1.11.1 in this size range. This is the shape of nlog⁡nn\log n on a finite interval. (3) Random access always performs the same number of reads, so the RAM model predicts constant time. In practice, time per call increases as the array outgrows each cache level, and the local slope shows steps instead of 00. Exact results depend on your machine and its current load, a reason to repeat measurements and take minima. The memory hierarchy is studied in the numerical methods module, and algorithms designed for it appear as cache-oblivious algorithms.

Measurement practice matters as much as theory, as detailed in the benchmarking methodology. Warm up before timing, repeat and keep the minimum because noise adds time, measure for durations long relative to clock resolution, and use geometrically spaced sizes. The following utility does so from scratch.

[ ]Empirical scaling benchmarkBrowser
import time, math, random

def medir(f, preparar, n, repeticiones=5, minimo=0.008):
    """Tiempo por llamada de f(datos): mínimo de varias series, cada una de al menos `minimo` segundos."""
    datos = preparar(n)
    f(datos)                                   # calentamiento
    k = 1
    while True:                                # calibra cuántas llamadas hacen falta para superar el ruido del reloj
        t0 = time.perf_counter()
        for _ in range(k):
            f(datos)
        dt = time.perf_counter() - t0
        if dt >= minimo or k >= 1 << 20:
            break
        k *= 2
    mejor = float("inf")
    for _ in range(repeticiones):
        t0 = time.perf_counter()
        for _ in range(k):
            f(datos)
        mejor = min(mejor, (time.perf_counter() - t0) / k)
    return mejor

def ajuste_loglog(ns, ts):
    """Mínimos cuadrados de log t sobre log n: devuelve (exponente, error estándar)."""
    x = [math.log(n) for n in ns]
    y = [math.log(t) for t in ts]
    m = len(x)
    mx, my = sum(x) / m, sum(y) / m
    sxx = sum((a - mx) ** 2 for a in x)
    b = sum((a - mx) * (c - my) for a, c in zip(x, y)) / sxx
    a0 = my - b * mx
    rss = sum((c - a0 - b * a) ** 2 for a, c in zip(x, y))
    se = math.sqrt(rss / (m - 2) / sxx) if m > 2 else float("nan")
    return b, se

def razones_duplicacion(ts):
    """T(2n) / T(n) para tamaños consecutivos en progresión de razón 2."""
    return [t2 / t1 for t1, t2 in zip(ts, ts[1:])]

rr = random.Random(3)
tareas = {
    "x in lista (ausente)": (lambda d: -1 in d, lambda n: list(range(n)), [2**k for k in range(10, 15)]),
    "x in conjunto": (lambda d: -1 in d, lambda n: set(range(n)), [2**k for k in range(10, 15)]),
    "sorted(lista)": (lambda d: sorted(d), lambda n: [rr.random() for _ in range(n)], [2**k for k in range(9, 14)]),
    "doble bucle": (lambda d: sum(1 for i in range(len(d)) for j in range(i) if d[i] + d[j] == -1), lambda n: list(range(n)), [2**k for k in range(5, 9)]),
}
medidas = {}
for nombre, (f, prep, ns) in tareas.items():
    ts = [medir(f, prep, n) for n in ns]
    medidas[nombre] = (ns, ts)
    b, se = ajuste_loglog(ns, ts)
    r = razones_duplicacion(ts)
    print(f"{nombre:22s} b = {b:5.2f} ± {2 * se:4.2f}   T(2n)/T(n) = {', '.join(f'{x:.2f}' for x in r)}")

The results agree with the analysis, subject to browser noise. x in lista is linear, with exponent near 11; x in conjunto is constant, near 00; sorted is above 11, often more than nlog⁡nn\log n justifies, whose apparent exponent in this range is only 1.081.08. The excess comes from memory management and browser noise, exactly the kind of discrepancy the experiment reveals. The nested loop is near 22, with doubling ratios near 44. Individual ratios fluctuate, sometimes considerably, so fit all points and report the standard error. Measuring once without warmup or repetition and inferring an exponent from two points, the error in An exponent from two points, can produce almost any result.

With libraries, timeit calibrates medir for you, while NumPy and SciPy give the same fit and its uncertainty.

[ ]The version using librariesBrowser
import timeit
import numpy as np
from scipy import stats

# Calibración automática: autorange busca cuántas repeticiones hacen falta para durar al menos 0.2 s
t = timeit.Timer("-1 in d", setup="d = list(range(2000))")
k, dt = t.autorange()
print(f"autorange: {k} llamadas en {dt:.2f} s, {dt / k * 1e6:.2f} µs por llamada")

ns, ts = medidas["x in lista (ausente)"]
x, y = np.log(ns), np.log(ts)
(b_np, a_np), cov = np.polyfit(x, y, 1, cov=True)
res = stats.linregress(x, y)
print("a mano       :", ajuste_loglog(ns, ts))
print("np.polyfit   :", (b_np, float(np.sqrt(cov[0, 0]))))
print("scipy        :", (res.slope, res.stderr))

All three agree up to rounding error. Understanding the fit tells you its assumptions, including homoscedastic errors on the logarithmic scale, and when to distrust it.

When the worst case is an attack

So far the worst case has been a pessimistic bound that is seldom reached in practice. Security changes the perspective. If an application processes attacker-controlled data, such as HTTP requests, file names, regular expressions or documents, the worst case becomes the input the attacker chooses. An algorithmic complexity attack sends small, inexpensive inputs that force a server into its worst case and deny service to other users. This weakness is cataloged as CWE-407 for inefficient algorithmic complexity and CWE-1333 for regular expressions. Crosby and Wallach’s foundational 2003 work demonstrated it with hash tables.

Three recurring examples:

Quicksort with a deterministic pivot. If a fixed rule chooses the pivot, such as the first, middle or median-of-three element, sorted or specially constructed input causes n2/2n^2/2 comparisons. McIlroy (1999) proved a stronger result: an adversary who only sees comparison results, without seeing the code, can construct inputs on which any deterministic quicksort of that style performs Θ(n2)\Theta(n^2) comparisons. The adversary grows a list of «gas» elements whose values are still undecided. When comparing two forces a decision, the pivot candidate is fixed as smaller. Each pivot then falls at an extreme and partitioning fails to split the data.

InteractiveMcIlroy's adversary against quicksort
Comparisons versus input size (both axes logarithmic)
  • n log₂ n
  • n²/2
  • random input
  • sorted
  • organ-pipe
  • adversarial
Pivot rule
1024
Comparisons, random input10.9 k
Comparisons, sorted input524 k
Comparisons, adversary524 k
Adversary versus nlog⁡2nn\log_2 n×51.1
At n=1024n = 1024 the adversary causes 524 k comparisons, 100% of n2/2n^2/2 (524 k): quadratic growth. A request like this occupies the server 48 times longer than random input.
Choose the pivot rule and compare comparison counts on random, sorted and organ-pipe inputs and the adversary's input (red curve), on a log-log scale. With a random pivot, the adversary cannot cause the same damage unless it knows the computer's seed.

Observe that for all three deterministic rules the adversarial curve has slope 22, parallel to n2/2n^2/2 and almost coinciding with it for first and middle pivots. Random inputs stay near nlog⁡2nn\log_2 n with slope ≈1.1\approx 1.1. «Natural» inputs can also be bad: sorted input defeats the first-element rule and organ-pipe input defeats the middle-element rule without anyone inspecting the code. With a random pivot, no fixed input has this effect, including one constructed against other random choices. Activate “The adversary knows the seed”: if an attacker predicts the pseudorandom sequence, the pivot is no longer unpredictable and the attack works again. Defensive randomness must be unpredictable to the adversary. Industrial libraries also use introsort (Musser, 1997), switching to heapsort when recursion depth exceeds 2log⁡2n2\log_2 n and guaranteeing O(nlog⁡n)O(n\log n) in the worst case without randomness.

Hash flooding. A hash table with chaining takes O(1)O(1) on average if its hash function distributes keys well. If an attacker knows the function and can choose keys, such as request parameter names, nn colliding keys make each insertion traverse the entire chain, for Θ(n2)\Theta(n^2) total work. This was demonstrated against several web languages in 2011. Defenses include secret-key hash functions such as SipHash or universal families (hash flooding and keyed hashing). Python has randomized string hashes since version 3.3. This harmless demonstration uses our own class with a hash that always returns the same value:

[ ]Hash flooding in miniatureBrowser
class ClaveMala:
    llamadas = 0
    def __init__(self, k):
        self.k = k
    def __hash__(self):
        return 7                               # todas colisionan
    def __eq__(self, otra):
        ClaveMala.llamadas += 1
        return self.k == otra.k

print(f"{'n':>5} {'comparaciones de claves':>24} {'n (n-1) / 2':>12}")
for n in (200, 400, 800):
    ClaveMala.llamadas = 0
    d = {}
    for i in range(n):
        d[ClaveMala(i)] = i
    print(f"{n:5d} {ClaveMala.llamadas:24d} {n * (n - 1) // 2:12d}")

With total collisions, Python’s dictionary makes exactly n(n−1)/2n(n-1)/2 comparisons: each insertion compares against every previous key. Doubling nn quadruples the work.

ReDoS (regular-expression denial of service). Regular-expression engines using backtracking, such as Python’s re module and most Java, JavaScript or PCRE engines, may take exponential time on small inputs when the expression is ambiguous. The same characters can be divided among parts in many ways and, when the end fails, the engine tries them all. Real outages have affected large services, including Stack Overflow in 2016, where quadratic backtracking over about twenty thousand spaces sufficed, and Cloudflare in 2019. The textbook pattern is (a+)+(a+)+ on a string of nn aa characters followed by bb.

[ ]Reproduce and fix a ReDoSBrowser
import re, time

malo = re.compile(r"^(a+)+$")                  # ambigua: n letras se reparten de 2^(n-1) maneras
bueno = re.compile(r"^a+$")                    # la misma lengua, sin ambigüedad

def tiempo_patron(p, s):
    t0 = time.perf_counter()
    p.match(s)
    return time.perf_counter() - t0

print(f"{'n':>3} {'(a+)+':>12} {'a+':>10} {'razón':>7}")
prev = None
medidas_redos = []
for n in range(12, 23, 2):
    s = "a" * n + "b"                          # entrada que obliga a probar todas las formas
    tm, tb = tiempo_patron(malo, s), tiempo_patron(bueno, s)
    medidas_redos.append((n, tm))
    razon = "" if prev is None else f"{tm / prev:.1f}"
    print(f"{n:3d} {tm * 1000:9.2f} ms {tb * 1e6:7.1f} us {razon:>7}")
    prev = tm

n, tm = medidas_redos[-1]
for objetivo in (40, 64):
    seg = tm * 2 ** (objetivo - n)             # cada letra más duplica el tiempo
    print(f"extrapolación a n = {objetivo}: {seg:.1e} s = {seg / 31557600:.1e} años")

Every two additional letters multiply time by about 44: an exponential base of 22 per letter. The ^a+$ version is linear. Three defense families, from strongest to weakest, are (1) use an engine that guarantees linear time by compiling to an automaton, as RE2, Rust’s regex and Go’s regexp do at the cost of excluding backreferences; (2) write unambiguous expressions or use atomic groups and possessive quantifiers where supported, including Python 3.11 onward; (3) limit input length and set a timeout for each match. Never compile a user-provided pattern. Engine design is covered in backtracking versus automata.

The lesson has two sides. Algorithm designers need to know the worst case and avoid it for hostile input, using unpredictable randomization, secret keys, non-backtracking engines and limits. Code reviewers should identify where third-party input determines work, then ask what the worst input is and what it costs.

Common mistakes

Exercises

ProofSubpolynomial and exponential growth from the definition
Prove: Use the definition to prove (a) nlog⁡2n∈O(n1+ε)n\log_2 n \in O(n^{1+\varepsilon}) for every ε>0\varepsilon > 0, and (b) 2n+1∈O(2n)2^{n+1} \in O(2^n) but 22n∉O(2n)2^{2n} \notin O(2^n).
0
For (a), fix ε>0\varepsilon > 0 and find explicit cc and n0n_0 (they may depend on ε\varepsilon). For (b), prove the second part by contradiction using the definition.

Step 1 of 4. For (a), what inequality is equivalent to nlog⁡2n≤c n1+εn\log_2 n \le c\, n^{1+\varepsilon}?

QuizOrdering growth with logarithms
What is the correct asymptotic order, from smallest to largest, of nlog⁡2nn^{\log_2 n}, (log⁡2n)n(\log_2 n)^n, 2log⁡2n2^{\sqrt{\log_2 n}}, n1.01n^{1.01}, nlog⁡22nn\log_2^2 n and 1.01n1.01^n?
NumericThe exponent from two measurements
An algorithm takes 22 s at n=106n = 10^6 and 8.18.1 s at n=2⋅106n = 2\cdot 10^6. Assuming T(n)≈a nbT(n) \approx a\, n^b, what is bb to three decimal places?
NumericExtrapolate the running time
Using the previous exponent and T(106)=2T(10^6) = 2 s, how many seconds does the fit predict for n=107n = 10^7? Round to one decimal place.
NumericFibonacci in the logarithmic-cost model
Compute FnF_n for n=106n = 10^6 using the addition loop. Given that FnF_n has ⌊nlog⁡2φ−12log⁡25⌋+1\lfloor n\log_2\varphi - \tfrac12\log_2 5\rfloor + 1 bits with φ=(1+5)/2\varphi = (1+\sqrt5)/2, how many $64$-bit words does F106F_{10^6} occupy? This is the word-operation cost of the last addition.
QuizIs trial-division primality testing polynomial?
The algorithm tries divisors d=2,…,⌊N⌋d = 2, \dots, \lfloor \sqrt N \rfloor of NN. Is it polynomial in input size?
QuizExpected cost of a randomized algorithm
Quicksort with a uniformly random pivot makes 2(n+1)Hn−4n2(n+1)H_n - 4n comparisons in expectation for each fixed input. What exactly does this guarantee?
QuizWhich expressions are vulnerable to ReDoS?
With a backtracking engine such as Python's re, which expressions, applied with match to 'a' * n + 'b' or an analogous input forcing failure at the end, can take exponential time in nn?

More than one answer may be correct.

QuizAn exponent from two points
A colleague measures x in lista once each for n=1000n = 1000 and n=2000n = 2000, obtaining 3.13.1 µs and 5.25.2 µs. They conclude that b=log⁡2(5.2/3.1)≈0.75b = \log_2(5.2/3.1) \approx 0.75 and search is sublinear. What is wrong?
CodeExponent with uncertainty
Implement exponente(ns, ts). Given lists of positive sizes ns and times ts, fit log⁡t=log⁡a+b log⁡n\log t = \log a + b\,\log n by least squares and return (b, se), where se is the standard error of the slope, RSS/(m−2) / Sxx\sqrt{\mathrm{RSS}/(m-2)\,/\,S_{xx}} with Sxx=∑(xi−xˉ)2S_{xx} = \sum (x_i - \bar x)^2 over xi=log⁡nix_i = \log n_i. For fewer than 33 points, se must be float('nan'). The approximate 95 %95\,\% interval is b ± 2*se. Do not use scipy or np.polyfit.
import math

def exponente(ns, ts):
  """Devuelve (b, se): exponente de la ley de potencias t ~ a n^b y su error estándar."""
  x = [math.log(n) for n in ns]
  y = [math.log(t) for t in ts]
  # tu código: pendiente por mínimos cuadrados, residuos y error estándar
  return 0.0, 0.0
Shift+Enter to run

Summary

Key idea
An algorithm’s cost is a function of input size, measured in bits, under an explicit cost model such as RAM, word-RAM or bit cost. Summarize it with OO, Ω\Omega and Θ\Theta using the quantifier order ∃c ∃n0 ∀n≥n0\exists c\ \exists n_0\ \forall n \ge n_0. Always state which case is meant, whether worst case, average case with its distribution, or randomized expected cost, and which resource is measured, time or space. Compare theory with doubling experiments and log-log fits with uncertainty, which also reveal effects the model misses, such as the memory hierarchy. When an adversary controls input, the worst case can become a denial-of-service vector.