Amortized analysis
Many data structures have occasionally expensive operations that are cheap in aggregate. Study the aggregate, accounting and potential methods on dynamic arrays, binary counters, multipop stacks and two-stack queues; prove why shrinking requires hysteresis; and use deamortization for worst-case bounds when latency matters.
After this lesson you can
- Apply the aggregate, accounting and potential methods to the same structure and compare their expressive power.
- Design potential functions for new structures and verify their conditions.
- Prove constant amortized cost for a dynamic array that doubles and shrinks at one-quarter occupancy.
- Implement a two-stack queue that maintains the minimum of a sliding window.
- Distinguish amortized from average cost and decide when deamortization is needed.
Before you start
Motivation: the append that sometimes copies millions of elements
The Python time complexity page lists list.append as and warns that this bound relies on the “amortized” part of the worst case: one action can take surprisingly longer. Indeed, a list of ten million pointers occupies about 80 MB, and occasionally a single append must allocate a larger block and move everything already there. That particular call does not cost : it costs . In what sense, then, is it constant?
The answer is that “ amortized” bounds a sequence, not one operation: regardless of how operations are mixed and how badly they align with resizes, consecutive calls cost in total. Spikes exist, but they are so rare and far apart that, spread over the cheap calls before them, they add a constant to each. Probability plays no part: this is a worst-case guarantee on the total.
This pattern appears everywhere:
- Growing arrays and tensors.
list,std::vector, output buffers of a token generator, the KV cache of a language model that adds a row per token. - Hash tables that resize when full (the hashing lesson uses them without proving their cost).
- Counters and clocks: a binary counter usually changes one or two bits and occasionally changes many at once.
- Queues built from stacks, a standard way to obtain the minimum of a sliding window over time-series data.
- Structures whose analysis requires this technique: splay trees, Fibonacci heaps and union by rank with path compression in the union-find lesson.
The goal is twofold. First, learn the three analysis methods (aggregate, accounting and potential) and see that they are three ways of expressing the same thing, with different power to describe complex structures. Second, understand the limit of the guarantee: when an individual operation cannot afford to take (a server with bounded tail latency, a real-time loop), deamortization is needed.
What “amortized” means
A data structure has an initial state and a set of operations. A legal sequence takes it through states ; operation executes on and has actual cost , measured in the cost model of lesson 1 (here, in elementary operations: writing or copying an element, pushing, popping).
Three comments on the definition. First, the inequality must hold for every prefix: the sequence can stop anywhere, so “borrowing” from future operations is invalid. Second, is a tool chosen by the analyst: many functions are valid, and good ones are tight. Third, each operation executes in the state left by previous operations; this differs from analyzing each operation’s worst case in its most unfavorable possible state, which might be unreachable.
Do not confuse it with other forms of averaging from worst, best and average case:
| What is averaged | Probabilistic assumption? | Guarantee for one operation | Guarantee for a sequence of | |
|---|---|---|---|---|
| Worst case | nothing: maximum over states | no | exact maximum time | times the bound (pessimistic) |
| Amortized | sequence costs | no | nothing: may cost | total , always |
| Average case | inputs | yes, over data | only in expectation | only in expectation |
| Expected | algorithm’s random choices | yes, over algorithm | only in expectation | only in expectation |
The amortized row is what matters here. An adversary who knows the implementation may choose the worst possible sequence and the amortized bound still holds; it does not bound the latency of an individual call.
Aggregate method: the multipop stack and binary counter
The aggregate method is the most direct: bound total cost of a sequence of operations and divide by . Every operation gets the same amortized cost, even if they have different types.
The multipop stack. In addition to push(x) and pop(), the stack offers multipop(k), which pops elements, with the current size. Each multipop costs as many pops as it performs, so it costs in the worst case and a naive count gives for operations. But each element is pushed once and popped at most once (by pop or multipop), so total pops cannot exceed pushes, which cannot exceed . Total cost is at most and amortized cost is per operation.
The binary counter. A counter of bits increments with incrementar: starting at the least significant bit, it sets ones to until finding a zero, which it sets to . Cost is the number of bits changed, up to in the worst case (from 0111…1 to 1000…0), and again a naive count gives for increments. The aggregate trick is to count per bit instead of per operation. Bit changes on every increment, bit on every other, bit once every four. In general, bit changes whenever the value reaches a multiple of , exactly times in increments from zero. Summing over bits,
The sum also has an exact value: by Legendre’s formula, where counts the ones in the binary representation of , so . Amortized cost is per increment. Explore this in the figure.
The aggregate method has a clear limit: it treats all operations equally. If a structure mixes cheap and expensive operations at different rates (insert, delete, find minimum) and we want a bound per operation type, the next two methods are more expressive.
Accounting method: coins stored in the structure
The accounting method charges each operation a fixed fee , chosen beforehand and different for each type. If the fee exceeds actual cost, the excess is saved as credit on the particular object in the structure that caused it; if smaller, stored credits pay for the operation. The golden rule: total credit can never be negative, at any time. Then, for every prefix, and the fee is a valid amortized cost.
Multipop stack. Fees: push charges , pop and multipop charge . The push spends one unit on the push and leaves the other as a coin on the element. When that element is popped, whether by pop or within multipop, its coin pays for the pop. There is one coin per element present, so credit equals stack size and is nonnegative. Amortized cost is for push and for the others.
Binary counter. Setting a bit to charges : one unit pays for the flip and the other remains as a coin on that bit. Setting a bit to costs and is paid by the bit’s own coin. An increment sets exactly one bit to , so it costs at most amortized. At all times there is one coin per bit set to , so credit is . The figure above illustrates this: coin count matches the number of ones.
Dynamic array. Below we will see that append charges : one unit writes the element, another saves for its own future copy, and the third saves to copy a companion from the older half of the array.
The accounting method is powerful because it associates the obligation with specific elements, helping us see who pays. Its limitation is that sometimes there is no natural assignment of coins to objects. That is why there is a third method.
Potential method
The potential method condenses all credits into a function of the structure’s entire state. A potential function is a map assigning each state a real number , stored energy that can be spent later. The amortized cost of operation is its actual cost plus the potential change it causes:
A cheap operation that raises potential charges more than it costs (saving); an expensive operation that lowers potential charges less than it costs (spending savings). All that must satisfy is that the final balance is no lower than the initial one:
Proof
Sum the definition of for . Terms form a telescoping sum: each with appears once with sign and once with sign , leaving only and . Therefore . Since , we obtain .
∎The accounting method is the special case where is the sum of stored coins. The advantage of potential is that credit need not be distributed among objects: a state-dependent formula suffices.
Designing a potential. There is no mechanical recipe, but there is a reliable heuristic: should be large just before expensive operations and should fall on each by the amount its cost exceeds the constant. This measures “how much pending work has already been paid for.”
Multipop stack. With (the size), push costs and raises by : . multipop(k) pops elements, costs and lowers by : . And , .
Binary counter. With the number of ones, increment sets to the trailing ones and sets a zero to :
If the counter overflows (from all ones to all zeros), and drops by : . Also, with (a counter starting with ones), the theorem gives : the bound shown in the figure with initial value .
The dynamic array
A dynamic array stores its elements in the prefix of a contiguous block of capacity . append writes at position ; if , it first allocates a larger block, copies the elements and frees the old one. With growth factor , new capacity is (and if the array had no capacity yet). We count per write and per element copied.
Proof
Let be the array capacities when expansion was necessary. Each expansion occurs on receiving an append when the array is full, that is, at append number , so . Each expansion copies elements, and since we have . Summing a geometric series,
Total cost is .
∎The result says more than it seems: regardless of the number of appends, cost per operation is bounded by a constant that depends only on . Observe all three methods at once in the next figure. The top graph shows actual append cost; the dashed line is amortized cost; below is potential , which for is . Just before expansion, with , it equals , the copying cost; just after, it is nearly . Each cheap append raises it by (for , by ), so cheap appends have amortized cost exactly ; on expensive ones the drop in pays for the copy and amortized cost is at most the same value (exactly equal when is an integer, as with ).
Growth factor: memory versus cost
There is a real trade-off. A smaller factor wastes less memory and charges more per operation:
| Factor | Amortized bound | Maximum idle memory | Peak memory during copying (old + new) |
|---|---|---|---|
| 1.125 | 10 | 11 % | |
| 1.25 | 6 | 20 % | |
| 1.5 | 4 | 33 % | |
| 2 | 3 | 50 % | |
| 4 | 2.33 | 75 % |
The amortized bounds are worst case over ; actual average cost is somewhat lower (with , append cost is with and with ). Real implementations choose different values: CPython grows by around (you will measure this below), Java and MSVC use and GCC standard libraries double. A classic argument favors (the golden ratio), provided the allocator coalesces adjacent freed blocks. When requesting a block of size , already freed blocks sum to (block is still in use while copying). That memory can hold the new block only if , that is, if . With the freed blocks always sum to less than the next block and memory fragments behind it.
Growing by an additive constant is a classic mistake. Expansions occur at capacities and copy elements: cost per append is , linear. A typical case is a function like np.append or torch.cat inside a loop: each call copies the entire array (a copy, not a view) and calls cost . Instead accumulate in a Python list and convert once, or reserve the final size.
Shrinking: why hysteresis is needed
Arrays that only grow waste memory if their contents are later removed, so shrinking is useful. The naive policy is symmetric: double when full and halve when half empty. This is disastrous. Suppose capacity with the array full. An push doubles capacity by copying elements and leaves the array just over half full. An pop returns it to exactly half: it shrinks, copying elements, and leaves the array full again. Alternating push and pop at that boundary makes each operation cost . This is thrashing, and amortized analysis exposes the trap: after every resize, the next is just one operation away, leaving no time to save credit for the copy.
The solution is hysteresis: different thresholds for growth and shrinkage. Double when full and halve only when . After any resize, occupancy is , and reaching the next one (becoming full or falling to one quarter) takes operations, which pay for the copy.
The potential proving this is V-shaped, centered on occupancy :
It is when the array is half full, rises with slope to the right (each push saves for future growth) and slope to the left (each pop saves for future shrinking). At the growth threshold it is and at the shrink threshold , exactly the respective copying cost. Case analysis gives, for all operations, for push and for pop. You will do this in the final proof exercise; to check it now, the lab below includes a numerical potential verifier.
Two-stack queue and sliding-window minimum
A FIFO queue can be built from two stacks using only push and pop. This is a common queue implementation in functional languages, where a linked list is essentially a stack. What is interesting is what can be added on top.
The two-stack queue maintains an input stack and an output stack. enqueue(x) pushes onto input. dequeue() pops from output; if output is empty, it first transfers input: pop each element from input and push it onto output, reversing order and leaving the oldest on top.
A single dequeue after transferring elements costs , but each element is transferred only once in its lifetime. For the potential method, with :
enqueue: , , so .dequeuewithout transfer: , , so .dequeuewith a transfer of elements: , , so .
Every operation is amortized, and each element costs at most stack operations in total. In coins: each incoming element saves two to pay for its future transfer.
Aggregates in O(1). The structure can be extended to return any associative aggregate of its contents. Besides its value, each element stores its stack’s aggregate from itself down to the bottom. Input stores prefixes (the aggregate of everything pushed up to the element) and output stores suffixes. The aggregate of the entire queue combines the two tops in the correct order: output (oldest) first, then input, which matters if the operation is not commutative. With transfer is per element, because the minimum stored on an element arriving at output is the lesser of its value and the minimum stored on the element already beneath it.
This solves a time-series problem: given values and a window of size , calculate each window’s minimum in instead of . Subtraction does not work because is not invertible (unlike sums, where a moving average is updated by adding the incoming value and subtracting the outgoing one). Another well-known variant uses a monotonic queue (a deque of indices with increasing values), exploiting total order: an element followed by a newer, smaller one can no longer be the minimum of any future window and is discarded. Each index enters and leaves the deque at most once, and Lemire (2006) refines it to calculate both maximum and minimum using no more than three comparisons per element. The two-stack queue is more general: it works for any associative operation, even if neither commutative nor idempotent, such as matrix or function composition.
Amortized, average and worst case: what each guarantees
Three uses of “constant” should be kept distinct:
- Worst-case : every individual operation takes less than a constant. This is needed by a real-time loop or a request with bounded tail latency (, ).
- Amortized : every sequence of operations takes in total. An individual operation may take .
- Average or expected : the operation’s expectation is constant under a distribution of inputs or internal random choices, as with expected value in hash tables with a random function.
These are three different quantities and the implication runs one way: worst case implies amortized (if each operation costs , cost ), not the reverse. Amortized cost says nothing about an individual operation. This is the difference between “ calls to append cost ” and “no append will take more than a microsecond”: the first is true, the second is not.
Deamortization: spreading the bill
Deamortization turns an amortized bound into a worst-case bound per operation by spreading the expensive operation’s work across earlier operations. The general technique is incremental global rebuilding: instead of rebuilding the structure all at once when it degrades, start constructing the new one well in advance and let each normal operation advance a constant amount of rebuilding, so that at the critical point it is already finished and only a pointer needs changing.
The dynamic array. Let be the number of extra copies each append will perform. When slots remain free, allocate the buffer of capacity and each append, besides writing its element to the old buffer, copies old elements to the new one. The old buffer still accepts more appends. During that time elements are copied, including all those present when it fills, even those added during migration. Thus when the old buffer fills, the new one already contains everything and pointers are swapped in . Worst-case latency: , constant, versus for the all-at-once array.
The price is real. Total work does not decrease: with it is somewhat higher (elements arriving during migration must also be copied, and migration to the next buffer starts immediately), peak memory still holds two buffers at once, code is more complex and each individual operation is somewhat slower: instead of most of the time. A constant cost avoids the spike.
The same idea appears elsewhere. Redis spreads dictionary rehashing across normal operations by keeping two hash tables at once and moving a few buckets on each access, so no request pays for the whole rehash. Hood and Melville’s and Okasaki’s real-time queues obtain worst-case for enqueue and dequeue by reversing the input stack incrementally instead of transferring it at once. Some allocators and garbage collectors spread work using per-operation budgets. When the average suffices, the amortized version is preferred: it is simpler and faster. When tail latency is a requirement, complexity is the price.
Implementation from scratch
First, the smallest possible program: count costs for the first two structures, check aggregate-method bounds and write a numerical potential verifier. Given actual costs and each state’s potential, it computes and checks . It shows the three outcomes from the warning above: a good potential (, maximum amortized cost exactly ), a valid but useless one (, expansion has linear amortized cost), and an invalid one (, which violates the inequality).
import math
def incrementar(bits):
"""Suma 1 a un contador binario (bits[0] es el menos significativo). Devuelve cuántos bits cambian."""
i = 0
while i < len(bits) and bits[i] == 1:
bits[i] = 0
i += 1
if i < len(bits):
bits[i] = 1
i += 1
return i
bits = [0] * 20
n = 1000
costes = [incrementar(bits) for _ in range(n)]
print(f"{n} incrementos: total {sum(costes)} cambios, media {sum(costes) / n:.3f}, máximo de uno solo {max(costes)}")
print(f"2n - (unos de n) = {2 * n - bin(n).count('1')} (Legendre: suma de floor(n/2^i) = 2n - s2(n))")
class PilaMultipop:
def __init__(self):
self.datos = []
self.coste = 0
def push(self, x):
self.datos.append(x)
self.coste += 1
def multipop(self, k):
c = 0
while self.datos and c < k:
self.datos.pop()
c += 1
self.coste += c
import random
random.seed(1)
S = PilaMultipop()
m = 20000
for _ in range(m):
if random.random() < 0.7:
S.push(0)
else:
S.multipop(random.randint(1, 30))
print(f"pila multipop: {m} operaciones, coste total {S.coste} <= 2m = {2 * m}")
# Verificador numérico de potenciales: Σ c_i <= Σ (c_i + Φ_i - Φ_{i-1}) cuando Φ_m >= Φ_0.
def verificar(costes, phis, nombre):
amort = [c + phis[i + 1] - phis[i] for i, c in enumerate(costes)]
ok = sum(costes) <= sum(amort) + 1e-9
print(f"{nombre:28s} amortizado máx {max(amort):8.2f} Σc <= Σĉ: {ok} Φ_min = {min(phis):.0f}")
costes, num, cap = [], 0, 0
estados = [(0, 0)]
for _ in range(2000):
c = 1
if num == cap:
c += num
cap = max(1, 2 * cap)
num += 1
costes.append(c)
estados.append((num, cap))
verificar(costes, [2 * a - b for a, b in estados], "Φ = 2·num - cap")
verificar(costes, [a for a, b in estados], "Φ = num (válido, inútil)")
verificar(costes, [-a for a, b in estados], "Φ = -num (negativo)")The counter makes flips in increments ( has six ones), although the increment from to flips bits at once. The multipop stack costs considerably less than because not everything pushed is eventually popped. The verifier distinguishes all three situations: the first potential satisfies , the second gives (valid but useless), and the third violates the inequality.
Now the dynamic array on a NumPy buffer, counting copies. Each policy runs for appends. The last uses additive growth, producing quadratic behavior. Notice how copias_totales, which visits only resizes, agrees with the full simulation: this shortcut is useful in the numeric exercise.
import math
import numpy as np
class ArrayDinamico:
"""Array dinámico de enteros sobre un buffer de NumPy, con contabilidad de costes."""
def __init__(self, factor=2.0, incremento=None):
self.factor, self.incremento = factor, incremento
self.buf = np.empty(0, dtype=np.int64)
self.n = 0
self.copias = 0 # elementos copiados al redimensionar
self.redim = 0 # número de redimensionados
self.pico = 0 # mayor número de copias en una sola operación
def _nueva_capacidad(self):
cap = len(self.buf)
if self.incremento is not None: # crecimiento aditivo: cap + k
return cap + self.incremento
return max(cap + 1, math.ceil(self.factor * cap)) # multiplicativo: ceil(g * cap)
def append(self, x):
if self.n == len(self.buf):
nuevo = np.empty(self._nueva_capacidad(), dtype=np.int64)
nuevo[:self.n] = self.buf[:self.n] # la copia de n elementos
self.copias += self.n
self.redim += 1
self.pico = max(self.pico, self.n)
self.buf = nuevo
self.buf[self.n] = x
self.n += 1
def copias_totales(N, factor):
"""Copias totales tras N appends, recorriendo solo los redimensionados (sin simular cada append)."""
cap, copias = 0, 0
while cap < N: # se amplía cuando el array lleno (n = cap) recibe el append número cap + 1 <= N
copias += cap
cap = 1 if cap == 0 else max(cap + 1, math.ceil(factor * cap))
return copias
N = 30_000
print(f"{'política':14s} {'copias':>11s} {'copias/n':>9s} {'cota g/(g-1)':>13s} {'redim.':>7s} {'mayor copia':>12s} {'ocioso':>7s}")
for nombre, kw in [("×2", dict(factor=2.0)), ("×1.5", dict(factor=1.5)), ("×1.125", dict(factor=1.125)), ("+16", dict(incremento=16))]:
a = ArrayDinamico(**kw)
for i in range(N):
a.append(i)
assert np.array_equal(a.buf[:a.n], np.arange(N)) # la estructura funciona
cota = f"{a.factor / (a.factor - 1):.2f}" if a.incremento is None else "n/(2k)"
print(f"{nombre:14s} {a.copias:11d} {a.copias / N:9.2f} {cota:>13s} {a.redim:7d} {a.pico:12d} {1 - N / len(a.buf):7.1%}")
if a.incremento is None:
assert a.copias == copias_totales(N, a.factor) # el atajo coincide con la simulación
print("copias_totales(10**6, 1.5) =", copias_totales(10**6, 1.5))Copies per append stay below under all three multiplicative policies (the theorem’s bound for copying cost excluding writes), whereas additive growth explodes: about copies per append with , matching . The final line answers the numeric exercise below if you want to see how to obtain it; check your own calculation first.
To see how a real Python list grows, inspect its size with sys.getsizeof. In CPython, capacity is determined by function list_resize in listobject.c, which uses rounded to a multiple of , an asymptotic factor of . Note: realloc can expand the block without copying if there is space after it, so actual copies may be fewer than in the model; the bound remains an upper bound.
import sys
lista = []
base = sys.getsizeof([])
ptr = sys.getsizeof([None]) - base # bytes por puntero (8 en 64 bits, 4 en WebAssembly)
caps, ultimo = [], -1
for i in range(100_000):
cap = (sys.getsizeof(lista) - base) // ptr
if cap != ultimo:
caps.append((len(lista), cap))
ultimo = cap
lista.append(i)
print("(longitud al crecer, capacidad):", caps[:14])
ratios = [b[1] / a[1] for a, b in zip(caps[:-1], caps[1:]) if a[1] > 0]
print(f"{len(caps) - 1} redimensionados en 100000 appends; cociente de capacidades: primeros {[round(r, 2) for r in ratios[:6]]}, últimos {[round(r, 3) for r in ratios[-3:]]}")
def capacidad_cpython(nuevo_tamano):
"""Fórmula de listobject.c (list_resize): newsize + newsize/8 + 6, redondeada a múltiplo de 4."""
return (nuevo_tamano + (nuevo_tamano >> 3) + 6) & ~3
assert all(c == capacidad_cpython(longitud) for longitud, c in caps[1:])
g = ratios[-1]
print(f"factor asintótico g ≈ {g:.3f} → cota amortizada (2g-1)/(g-1) = {(2 * g - 1) / (g - 1):.1f}")The formula reproduces exactly all observed capacities, and successive ratios start at and converge to . With the amortized bound is : CPython pays for saving memory with more copying, relying on realloc to avoid it often.
Second exercise: sliding-window minimum. Compare the two-stack and monotonic queues against vectorized NumPy brute force and pandas rolling().min(), measuring each one’s elementary operations.
import numpy as np
import pandas as pd
from collections import deque
class ColaMin:
"""Cola FIFO con dos pilas; cada elemento guarda el mínimo de su pila desde él hacia el fondo."""
def __init__(self):
self.ent, self.sal = [], [] # listas de pares (valor, mínimo de la pila hasta aquí)
self.ops = 0 # operaciones elementales sobre pilas (push o pop)
self.mayor = 0 # coste de la operación individual más cara
def __len__(self):
return len(self.ent) + len(self.sal)
def push(self, x):
m = x if not self.ent else min(x, self.ent[-1][1])
self.ent.append((x, m))
self.ops += 1
self.mayor = max(self.mayor, 1)
def pop(self):
coste = 0
if not self.sal: # volcado: cada elemento se mueve una sola vez
while self.ent:
x, _ = self.ent.pop()
m = x if not self.sal else min(x, self.sal[-1][1])
self.sal.append((x, m))
coste += 2
coste += 1
self.ops += coste
self.mayor = max(self.mayor, coste)
return self.sal.pop()[0]
def minimo(self):
return min(p[-1][1] for p in (self.ent, self.sal) if p)
def ventana_min_dos_pilas(x, w):
q, salida = ColaMin(), []
for i, v in enumerate(x):
q.push(v)
if len(q) > w:
q.pop()
if i >= w - 1:
salida.append(q.minimo())
return np.array(salida), q
def ventana_min_deque(x, w):
"""Cola monótona: guarda índices con valores crecientes; el frente es el mínimo de la ventana."""
d, salida, ops = deque(), [], 0
for i, v in enumerate(x):
while d and x[d[-1]] >= v:
d.pop()
ops += 1
d.append(i)
ops += 1
if d[0] <= i - w:
d.popleft()
ops += 1
if i >= w - 1:
salida.append(x[d[0]])
return np.array(salida), ops
rng = np.random.default_rng(0)
x = np.cumsum(rng.normal(size=20_000)) # un paseo aleatorio largo
w = 250
ref = np.lib.stride_tricks.sliding_window_view(x, w).min(axis=1) # fuerza bruta vectorizada
pandas_min = pd.Series(x).rolling(w).min().dropna().to_numpy()
a, q = ventana_min_dos_pilas(x, w)
b, ops_deque = ventana_min_deque(x, w)
print("dos pilas == fuerza bruta:", np.array_equal(a, ref), "| deque == fuerza bruta:", np.array_equal(b, ref), "| pandas == fuerza bruta:", np.array_equal(pandas_min, ref))
n = len(x)
print(f"dos pilas: {q.ops} operaciones elementales = {q.ops / n:.2f} por elemento (cota 4); la más cara de todas: {q.mayor} (= 2(w+1) + 1 = {2 * (w + 1) + 1})")
print(f"deque monótona: {ops_deque} operaciones = {ops_deque / n:.2f} por elemento (cota 2: cada índice entra y sale una vez)")
# secuencia adversaria para una sola operación: llenar la ventana y sacar justo después
q2 = ColaMin()
for v in range(w):
q2.push(float(v))
antes = q2.ops
q2.pop()
print(f"un pop tras {w} push seguidos cuesta {q2.ops - antes} (= 2·{w} + 1), pero los {w - 1} pops siguientes cuestan 1 cada uno")The three results agree, and costs confirm the analysis: the two-stack queue uses about operations per element (analysis bound: on entry, on transfer, on exit), and the monotonic queue practically , its exact bound (each index enters once and exits at most once; the few remaining at the end do not exit). The most expensive individual two-stack operation costs , precisely the transfer of elements present when the oldest leaves. This is amortization in its purest form: one operation costs over times the average cost of , and both statements are true.
The production version
In real code, a dynamic array is rarely written by hand.
- Python
list, C++std::vector, RustVecand Go slices are already dynamic arrays with geometric growth. The rule of thumb is to know their factor and reserve ahead when size is known (vector::reserve,Vec::with_capacity,np.empty(n)), eliminating all resizes. collections.dequeis a doubly linked list of blocks giving worst-case at both ends without copy spikes, at the cost of slower indexed access in the middle. It suits a monotonic queue and any FIFO queue in Python (list.pop(0)costs ).- For window minima and maxima in tabular data use
pandas.Series.rolling(w).min()(ormax()), linear in instead of ; in NumPy usesliding_window_view(x, w).min(axis=1)if fits in memory, as in the lab above. - In PyTorch,
torch.catin a loop repeats the additive mistake: accumulate tensors in a Python list and concatenate once withtorch.cat(lista)ortorch.stack(lista).
Common mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
dequeue(Q) times on the same . What happens?Step 1 of 4. What must be checked about for ?
push and for pop.Step 1 of 5. Where on the V does the array land after any resize?
ColaMax with two Pila stacks (the class is already defined: it counts each push and pop in global variable COSTE). Provide push(x) (enqueue), pop() (dequeue the oldest), max() (largest current element without emptying the queue) and __len__. All in amortized : tests count stack operations and comparisons between values.COSTE = 0 # operaciones elementales sobre pilas
class Pila:
def __init__(self):
self.datos = []
def push(self, x):
global COSTE
COSTE += 1
self.datos.append(x)
def pop(self):
global COSTE
COSTE += 1
return self.datos.pop()
def top(self):
return self.datos[-1]
def __len__(self):
return len(self.datos)
class ColaMax:
"""Cola FIFO con maximo en O(1) amortizado, usando solo dos pilas."""
def __init__(self):
self.ent = Pila()
self.sal = Pila()
def __len__(self):
return 0 # tu código
def push(self, x):
pass # tu código
def pop(self):
return None # tu código
def max(self):
return None # tu códigoSummary
- An amortized bound satisfies for every prefix of every sequence. It is not average case: it assumes no distribution. It is not worst case per operation: one operation may cost .
- Aggregate: bound the total (multipop stack: ; binary counter: ). Accounting: fixed fees and coins attached to objects (never negative). Potential: and if , by telescoping.
- Dynamic array with factor : . Additive growth gives quadratic cost. Shrinking requires hysteresis: half causes thrashing; at one quarter, the V-shaped potential gives and .
- Two-stack queue: gives . Each element stores its stack’s aggregate: a sliding-window minimum (or any associative aggregate) in amortized .
- Deamortization: build the new structure incrementally, steps per operation, for worst-case bound . This costs total work and complexity but avoids latency spikes.
The technique recurs throughout: Fibonacci heaps (potential: trees plus twice the marked nodes), splay trees in the treaps, skip lists and splay lesson (potential: sum of logarithms of subtree sizes), and union by rank with path compression in the union-find lesson use potential analysis. A potential function decreasing at each algorithm step is also related to a Lyapunov function in dynamics: a state quantity that decreases and bounds remaining work.