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 operations; the second takes on the order of . On a machine that executes operations per second, the second finishes in two hundredths of a second and the first in s, almost seventeen minutes. No low-level optimization closes a fifty-thousand-fold gap, and the gap grows with .
An exponential algorithm brings a different kind of contrast. Trying all subsets of a set of one hundred elements takes operations. At per second, that is roughly 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.
Three observations from the figure. First, for a machine one thousand times faster multiplies the boundary by ; for , by ; for it adds only elements. A multiplicative speedup becomes an additive increase in manageable size. Second, the constant matters less than the order. Set the constant for to and leave that of at . The second wins for small , but from onward the first wins (solve ). Third, is even worse than , 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 -bit processor performs these operations in one or a few cycles. The assumption fails when operands grow with . Multiplying two -bit numbers by the schoolbook method requires bit operations, or word operations. Karatsuba reduces this to and Harvey and van der Hoeven’s algorithm (2019) to . None is .
For example, compute , the th Fibonacci number, with the usual loop. In the uniform model there are additions, or . But has bits, so adding the last two numbers costs bit operations and the total is .
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 and the bit cost as . The ratio bits / n^2 approaches . The right model depends on the question. To sort keys of bits, the uniform model is appropriate. For factorization, computing 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 of input size. We want to compare such functions while ignoring multiplicative constants and behavior for small . The notation appeared in calculus as Landau notation. Here we define its use for costs, with all quantifiers explicit.
Notice the order of quantifiers: . The constant and threshold are chosen before and apply simultaneously to all later . If the order were reversed, «for each there exists a », every pair of positive functions would be related, because suffices at each point. Explore this structure in the figure.
Three takeaways. (1) and trade off against one another. For versus , requires , while requires only . (2) A false relationship is refuted by a family of violations escaping every , rather than a single case. (3) can mean that exceeds only beyond an astronomical , beyond the reach of timing experiments.
The practical criterion for deciding most relationships is the ratio.
Proof
Case : given , the definition of a limit with gives such that for , or . This is , and because it suffices to take .
Case : taking gives such that for . This gives both (with ) and (with ).
Case : , which by the first case is , or .
∎The converse is false: is and oscillates without a limit. The criterion is therefore a tool rather than the definition. To compare functions with logarithms and exponents, taking logarithms helps: if is bounded above. These rules are used throughout:
- Constants and sums: and . A polynomial is of its dominant term.
- Transitivity: and imply ; likewise for , , , .
- Logarithms: the base does not matter, ; but for every and for every .
- Polynomials and exponentials: for every and every .
- Exponents: a constant added to an exponent is absorbed, while one that multiplies it is not. , but . Inside a logarithm the reverse happens: the exponent becomes an absorbed factor, so although .
Using these rules, the classes throughout the course are ordered as follows. Each row’s representative is of the next row’s, so each is strictly contained in the next.
| Class | Typical example |
|---|---|
| access an array position | |
| binary search | |
| traverse a list, sum | |
| mergesort, heapsort | |
| insertion sort, all pairs | |
| naive matrix multiplication, Floyd-Warshall | |
| enumerate all subsets | |
| 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 it receives. There are several ways to turn the cost of each input into a function of .
Linear search for a value present in an array of elements illustrates this. comparison is needed if it appears first, if it appears last, and also if it may be absent. If its position is uniform, . 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 .
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 comparisons on average over uniform permutations, but on already sorted input. With a uniformly random pivot, its expected number of comparisons on every input is , where is the harmonic number. The figure matches the average case, with a different interpretation.
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 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 has simply meant «input size». We must define it for a coherent theory.
For lists of fixed-size numbers, elements correspond to bits, so there is no discrepancy. But when the input is a number, the difference is enormous: and are exponentially far apart.
The canonical example is trial-division primality testing. To decide whether is prime, try divisors . This takes steps, which seems small. But the input takes bits, so is exponential in its size.
Proof
By Bertrand’s postulate, there is a prime with , having exactly bits. Since is prime, no divisor divides it, so the algorithm tries all of them and performs divisions. Since , there are at least . An exponential in eventually exceeds any polynomial in .
∎The same happens with 0/1 knapsack with capacity and items. Classical dynamic programming fills a table of cells, using operations, which looks polynomial. But takes bits: every additional capacity bit doubles the work. This is the prototypical pseudopolynomial algorithm, studied in the knapsack lesson.
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 increase in multiplies primality-test steps by , or per bit. Every increase in multiplies knapsack operations by , or 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 -bit numbers performs divisions. Its worst case is two consecutive Fibonacci numbers, with 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.
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 , 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 nested calls and uses space, although its running time matches the loop. Most languages, including Python, do not eliminate tail calls. Python’s default recursion limit is around frames, so recursion of depth raises a runtime error for large . Recursive mergesort, by contrast, has depth but needs an auxiliary buffer of elements, giving time and 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 so that x in s costs instead of .
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 . 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 for sizes in a geometric progression, then fit a power law .
Two essentially equivalent tools follow.
Doubling experiment. If , then is independent of . Repeatedly double , calculate the ratio and take . A ratio near indicates linear growth, near quadratic growth, and near cubic growth. For the ratio is , which approaches very slowly. At it is , an apparent exponent of . This is why linear and near-linear growth can be hard to distinguish in practice.
Log-log fit. Taking logarithms makes a straight line, whose slope is obtained by least squares. Regression also gives a standard error, so the exponent is reported as .
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 always costs , which measurement can contradict.
Three readings of the figure. (1) Summation has a slope near and the nested loop near : the model works there. (2) Sorting is and shows an exponent slightly above , around in this size range. This is the shape of 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 . 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.
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 ; x in conjunto is constant, near ; sorted is above , often more than justifies, whose apparent exponent in this range is only . The excess comes from memory management and browser noise, exactly the kind of discrepancy the experiment reveals. The nested loop is near , with doubling ratios near . 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.
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 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 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.
Observe that for all three deterministic rules the adversarial curve has slope , parallel to and almost coinciding with it for first and middle pivots. Random inputs stay near with slope . «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 and guaranteeing in the worst case without randomness.
Hash flooding. A hash table with chaining takes on average if its hash function distributes keys well. If an attacker knows the function and can choose keys, such as request parameter names, colliding keys make each insertion traverse the entire chain, for 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:
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 comparisons: each insertion compares against every previous key. Doubling 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 on a string of characters followed by .
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 : an exponential base of 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
Step 1 of 4. For (a), what inequality is equivalent to ?
re, which expressions, applied with match to 'a' * n + 'b' or an analogous input forcing failure at the end, can take exponential time in ?More than one answer may be correct.
x in lista once each for and , obtaining µs and µs. They conclude that and search is sublinear. What is wrong?exponente(ns, ts). Given lists of positive sizes ns and times ts, fit by least squares and return (b, se), where se is the standard error of the slope, with over . For fewer than points, se must be float('nan'). The approximate 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