Module contents
Lesson 5 of 33Core 90 min

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 O(1)\bigO(1) 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 O(1)\bigO(1): it costs O(n)\bigO(n). In what sense, then, is it constant?

The answer is that “O(1)\bigO(1) amortized” bounds a sequence, not one operation: regardless of how operations are mixed and how badly they align with resizes, mm consecutive calls cost O(m)\bigO(m) 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 O(n)\bigO(n) (a server with bounded tail latency, a real-time loop), deamortization is needed.

What “amortized” means

A data structure has an initial state D0D_0 and a set of operations. A legal sequence o1,…,omo_1, \dots, o_m takes it through states D0,D1,…,DmD_0, D_1, \dots, D_m; operation oio_i executes on Di−1D_{i-1} and has actual cost cic_i, 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, c^\hat c 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 averagedProbabilistic assumption?Guarantee for one operationGuarantee for a sequence of mm
Worst casenothing: maximum over statesnoexact maximum timemm times the bound (pessimistic)
Amortizedsequence costsnonothing: may cost Θ(m)\Theta(m)total ≤m⋅c^\le m \cdot \hat c, always
Average caseinputsyes, over dataonly in expectationonly in expectation
Expectedalgorithm’s random choicesyes, over algorithmonly in expectationonly 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 mm operations and divide by mm. 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 min⁡(k,s)\min(k, s) elements, with ss the current size. Each multipop costs as many pops as it performs, so it costs O(n)\bigO(n) in the worst case and a naive count gives O(n2)\bigO(n^2) for nn 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 nn. Total cost is at most n+n=2nn + n = 2n and amortized cost is 22 per operation.

The binary counter. A counter of kk bits increments with incrementar: starting at the least significant bit, it sets ones to 00 until finding a zero, which it sets to 11. Cost is the number of bits changed, up to kk in the worst case (from 0111…1 to 1000…0), and again a naive count gives O(nk)\bigO(nk) for nn increments. The aggregate trick is to count per bit instead of per operation. Bit 00 changes on every increment, bit 11 on every other, bit 22 once every four. In general, bit ii changes whenever the value reaches a multiple of 2i2^i, exactly ⌊n/2i⌋\lfloor n/2^i \rfloor times in nn increments from zero. Summing over bits,

T(n)  =  ∑i=0k−1⌊n2i⌋  <  n∑i=0∞12i  =  2n.T(n) \;=\; \sum_{i=0}^{k-1} \left\lfloor \frac{n}{2^i} \right\rfloor \;<\; n \sum_{i=0}^{\infty} \frac{1}{2^i} \;=\; 2n .

The sum also has an exact value: by Legendre’s formula, ∑i≥1⌊n/2i⌋=n−s2(n)\sum_{i \ge 1} \lfloor n/2^i \rfloor = n - s_2(n) where s2(n)s_2(n) counts the ones in the binary representation of nn, so T(n)=2n−s2(n)T(n) = 2n - s_2(n). Amortized cost is 22 per increment. Explore this in the figure.

InteractiveBit flips in a counter
Counter: 0000 0000 0110 01000010011000000000Flips per bit (diamond: prediction)1005025126310123456789101112131415Cost of the last 64 increments7Total flips versus bound 2m + Φ₀ (initial ones)total 197bound 200
Starting value
Increments mm100
Value100
Total flips197
Mean per increment1.970
Exact: 2m−Δ(ones)2m - \Delta(\text{ones})197
Coins = ones = Φ\Phi3
Increment 100: 2 bits change from 1 to 0 and one bit changes from 0 to 1. Actual cost 3. The 2 changes to 0 are paid with the coins stored by those bits; changing to 1 costs 1 and leaves 1 coin. Charged: 2.
Press «+1» several times and then «+100». Each bar counts how often that bit has changed and the diamond is the theoretical prediction: bit ii changes ⌊m/2i⌋\lfloor m/2^i \rfloor times. Below is the cost of each increment: most cost 1 or 2, with an occasional spike. With coins enabled, each 1 bit stores one; check that their count always matches the number of ones. Try initial value 255: the first increment flips 9 bits; what is the average after 100 increments? Why can it exceed 2?

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 c^i\hat c_i, 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, ∑ci≤∑c^i\sum c_i \le \sum \hat c_i and the fee is a valid amortized cost.

Multipop stack. Fees: push charges 22, pop and multipop charge 00. 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 22 for push and 00 for the others.

Binary counter. Setting a bit to 11 charges 22: one unit pays for the flip and the other remains as a coin on that bit. Setting a bit to 00 costs 11 and is paid by the bit’s own coin. An increment sets exactly one bit to 11, so it costs at most 22 amortized. At all times there is one coin per bit set to 11, so credit is s2(valor)≥0s_2(\text{valor})\ge 0. The figure above illustrates this: coin count matches the number of ones.

Dynamic array. Below we will see that append charges 33: 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 Φ\Phi assigning each state DD a real number Φ(D)\Phi(D), stored energy that can be spent later. The amortized cost of operation ii is its actual cost plus the potential change it causes:

c^i=ci+Φ(Di)−Φ(Di−1).\hat c_i = c_i + \Phi(D_i) - \Phi(D_{i-1}).

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 Φ\Phi must satisfy is that the final balance is no lower than the initial one:

Proof

Sum the definition of c^i\hat c_i for i=1,…,mi = 1, \dots, m. Terms Φ(Di)−Φ(Di−1)\Phi(D_i) - \Phi(D_{i-1}) form a telescoping sum: each Φ(Di)\Phi(D_i) with 1≤i≤m−11 \le i \le m-1 appears once with sign ++ and once with sign −-, leaving only Φ(Dm)\Phi(D_m) and −Φ(D0)-\Phi(D_0). Therefore ∑c^i=∑ci+Φ(Dm)−Φ(D0)\sum \hat c_i = \sum c_i + \Phi(D_m) - \Phi(D_0). Since Φ(Dm)−Φ(D0)≥0\Phi(D_m) - \Phi(D_0) \ge 0, we obtain ∑ci≤∑c^i\sum c_i \le \sum \hat c_i. ■\blacksquare

∎

The accounting method is the special case where Φ(D)\Phi(D) 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: Φ\Phi 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 Φ=s\Phi = s (the size), push costs 11 and raises Φ\Phi by 11: c^=2\hat c = 2. multipop(k) pops k′=min⁡(k,s)k' = \min(k, s) elements, costs k′k' and lowers Φ\Phi by k′k': c^=0\hat c = 0. And Φ(D0)=0\Phi(D_0) = 0, Φ≥0\Phi \ge 0.

Binary counter. With Φ=\Phi = the number of ones, increment ii sets to 00 the trailing tit_i ones and sets a zero to 11:

ci=ti+1c_i = t_i + 1
The t trailing ones and the zero that becomes one change.
1/3

If the counter overflows (from all ones to all zeros), c=kc = k and Φ\Phi drops by kk: c^=0≤2\hat c = 0 \le 2. Also, with Φ(D0)=b0≠0\Phi(D_0) = b_0 \ne 0 (a counter starting with b0b_0 ones), the theorem gives T(m)≤2m+b0−Φ(Dm)≤2m+b0T(m) \le 2m + b_0 - \Phi(D_m) \le 2m + b_0: the bound shown in the figure with initial value 255255.

The dynamic array

A dynamic array stores its nn elements in the prefix of a contiguous block of capacity cap\mathrm{cap}. append writes at position nn; if n=capn = \mathrm{cap}, it first allocates a larger block, copies the nn elements and frees the old one. With growth factor g>1g > 1, new capacity is ⌈g⋅cap⌉\lceil g \cdot \mathrm{cap} \rceil (and 11 if the array had no capacity yet). We count 11 per write and 11 per element copied.

Proof

Let c1<c2<⋯<crc_1 < c_2 < \dots < c_r 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 cj+1≤nc_j + 1 \le n, so cr≤n−1<nc_r \le n - 1 < n. Each expansion copies cjc_j elements, and since cj+1≥g cjc_{j+1} \ge g\,c_j we have cj≤cr/g r−jc_j \le c_r / g^{\,r-j}. Summing a geometric series,

copias=∑j=1rcj≤cr∑i≥0g−i=cr gg−1<n gg−1.\begin{aligned} \text{copias} &= \sum_{j=1}^r c_j \le c_r \sum_{i \ge 0} g^{-i} \\ &= c_r\,\frac{g}{g-1} < n\,\frac{g}{g-1}. \end{aligned}

Total cost is T(n)=n+copias<n(1+gg−1)=n 2g−1g−1T(n) = n + \text{copias} < n\bigl(1 + \tfrac{g}{g-1}\bigr) = n\,\tfrac{2g-1}{g-1}. ■\blacksquare

∎

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 gg. 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 Φ=g num−capg−1\Phi = \frac{g\,\mathrm{num} - \mathrm{cap}}{g - 1}, which for g=2g = 2 is 2 num−cap2\,\mathrm{num} - \mathrm{cap}. Just before expansion, with num=cap\mathrm{num} = \mathrm{cap}, it equals cap\mathrm{cap}, the copying cost; just after, it is nearly 00. Each cheap append raises it by gg−1\frac{g}{g-1} (for g=2g=2, by 22), so cheap appends have amortized cost exactly 1+gg−11 + \frac{g}{g-1}; on expensive ones the drop in Φ\Phi pays for the copy and amortized cost is at most the same value (exactly equal when g capg\,\mathrm{cap} is an integer, as with g=2g = 2).

InteractiveThe potential bank account
Array now (40 of 64)Cost of each append 020amortized cost ≤ 3.00Potential Φ: coins saved for the next copy020110203040
Append 40 of 40
  • actual cost (orange: copy)
  • amortized bound
  • cumulative mean
  • potential Φ
Growth policy
2.00
40
Actual cost cic_i1
Amortized cost3.00
Bound (2g−1)/(g−1)(2g-1)/(g-1)3.00
Potential Φ\Phi16.0
Total T(n)T(n) and mean T/nT/n103 · 2.58
Size and capacity40 of 64
Unused memory38 %
Append 40 costs 1. Φ rises by 2.00 (the credit saved for the next copy), and amortized cost is 3.00.
Press ▶ and watch Φ\Phi fill a little on each append and empty just as it pays for copying: amortized cost (dashed line) stays flat while actual cost spikes. Lower gg toward 1.1: less memory is idle, but the bound (2g−1)/(g−1)(2g-1)/(g-1) rises. Then select «Sumar +k+k»: without a multiplicative factor, cumulative average cost grows without bound and no potential can remedy it. Enable logarithmic scale with more operations to see the spikes and flat line together.

Growth factor: memory versus cost

There is a real trade-off. A smaller factor wastes less memory and charges more per operation:

Factor ggAmortized bound 2g−1g−1\frac{2g-1}{g-1}Maximum idle memory 1−1/g1 - 1/gPeak memory during copying (old + new)
1.1251011 %2.125 n2.125\,n
1.25620 %2.25 n2.25\,n
1.5433 %2.5 n2.5\,n
2350 %3 n3\,n
42.3375 %5 n5\,n

The amortized bounds are worst case over nn; actual average cost is somewhat lower (with n=105n = 10^5, append cost is 2.312.31 with g=2g = 2 and 3.763.76 with g=1.5g = 1.5). Real implementations choose different values: CPython grows by around 1.1251.125 (you will measure this below), Java and MSVC use 1.51.5 and GCC standard libraries double. A classic argument favors g<φ≈1.618g < \varphi \approx 1.618 (the golden ratio), provided the allocator coalesces adjacent freed blocks. When requesting a block of size gr+1g^{r+1}, already freed blocks sum to 1+g+⋯+gr−1≈gr/(g−1)1 + g + \dots + g^{r-1} \approx g^r/(g-1) (block grg^r is still in use while copying). That memory can hold the new block only if gr/(g−1)≥gr+1g^r/(g-1) \ge g^{r+1}, that is, if g2−g≤1g^2 - g \le 1. With g=2g = 2 the freed blocks always sum to less than the next block and memory fragments behind it.

Growing by an additive constant +k+k is a classic mistake. Expansions occur at capacities k,2k,3k,…k, 2k, 3k, \dots and copy k+2k+⋯+(n/k−1)k≈n2/(2k)k + 2k + \dots + (n/k - 1)k \approx n^2/(2k) elements: cost per append is Θ(n/k)\Theta(n/k), 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 nn calls cost Θ(n2)\Theta(n^2). 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 cap\mathrm{cap} with the array full. An push doubles capacity by copying cap\mathrm{cap} elements and leaves the array just over half full. An pop returns it to exactly half: it shrinks, copying cap\mathrm{cap} elements, and leaves the array full again. Alternating push and pop at that boundary makes each operation cost Θ(cap)\Theta(\mathrm{cap}). 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 n≤cap/4n \le \mathrm{cap}/4. After any resize, occupancy is ≈1/2\approx 1/2, and reaching the next one (becoming full or falling to one quarter) takes Ω(cap)\Omega(\mathrm{cap}) operations, which pay for the copy.

InteractiveShrink thrashing
Shrink at half full (n ≤ cap/2)16 of 16 · shrinksShrink at quarter full (n ≤ cap/4)16 of 32
Cumulative cost of the same operations
  • shrink at half
  • shrink at quarter
Potential of the ¼ policy by occupancy n/capn/\mathrm{cap}
0¼ shrink½ after resize1 growthe ½ policy shrinks at Φ = 0Φ/cap
Circle: current occupancy of the ¼ array. Red triangle: the ½ array. The ½ policy shrinks where Φ is 0, exactly where it lands after growing.
Initial capacity (full)
Operations20
Total cost, ½ policy340
Total cost, ¼ policy36
Per operation (½ and ¼)17.0 and 1.80
Costliest operation (½ and ¼)17 and 17
After 20 operations, the half-full policy costs 340 (17.0 per operation) and the quarter-full policy costs 36 (1.80 per operation). Steep red segments show a grow followed by a shrink on the next pop.
The same operations feed two arrays differing only in their shrink threshold. Press «Oscilar ×20» (alternate push and pop on a full array): the half-threshold array copies on almost every operation and its cumulative cost rises steeply; the quarter-threshold array stays almost flat. Then try «Subir ×20» and «Bajar ×20»: with trends, both policies behave similarly. Below is the quarter-threshold policy's V-shaped potential: just after resizing, the array lands at the vertex (Φ nearly 0), and reaching another copy cost requires traveling far along the V.

The potential proving this is V-shaped, centered on occupancy 1/21/2:

Φ(num,cap)={2 num−capsi num≥cap/2,cap/2−numsi num<cap/2.\Phi(\mathrm{num}, \mathrm{cap}) = \begin{cases} 2\,\mathrm{num} - \mathrm{cap} & \text{si } \mathrm{num} \ge \mathrm{cap}/2, \\[2pt] \mathrm{cap}/2 - \mathrm{num} & \text{si } \mathrm{num} < \mathrm{cap}/2. \end{cases}

It is 00 when the array is half full, rises with slope 22 to the right (each push saves 22 for future growth) and slope 11 to the left (each pop saves 11 for future shrinking). At the growth threshold it is cap\mathrm{cap} and at the shrink threshold cap/4\mathrm{cap}/4, exactly the respective copying cost. Case analysis gives, for all operations, c^≤3\hat c \le 3 for push and c^≤2\hat c \le 2 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 nn elements costs 2n+12n + 1, but each element is transferred only once in its lifetime. For the potential method, with Φ=2 ∣entrada∣\Phi = 2\,\lvert\text{entrada}\rvert:

  • enqueue: c=1c = 1, ΔΦ=+2\Delta\Phi = +2, so c^=3\hat c = 3.
  • dequeue without transfer: c=1c = 1, ΔΦ=0\Delta\Phi = 0, so c^=1\hat c = 1.
  • dequeue with a transfer of kk elements: c=2k+1c = 2k + 1, ΔΦ=−2k\Delta\Phi = -2k, so c^=1\hat c = 1.

Every operation is O(1)\bigO(1) amortized, and each element costs at most 1+2+1=41 + 2 + 1 = 4 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 min⁡\min transfer is O(1)\bigO(1) per element, because the minimum stored on an element arriving at output is the lesser of its value xx and the minimum stored on the element already beneath it.

This solves a time-series problem: given nn values and a window of size ww, calculate each window’s minimum in Θ(n)\Theta(n) instead of Θ(nw)\Theta(nw). Subtraction does not work because min⁡\min 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.

InteractiveThe two-stack queue
Series (current window in blue) and window minima (diamonds)Output stack (oldest on top)Input stack (newest on top)
Start
Series
4
Window minimum·
Cumulative cost0
Elements enqueued0
Cost per element·
Potential Φ=2 ∣input∣\Phi = 2\,\lvert\text{input}\rvert0
Costliest dequeue11 = 2·5 + 1
Against brute forcematches
Window of size 4 over 28 values. Each player step is an elementary operation: push, transfer (pop plus push), or pop.
Step through. Above is the series with the current window in blue and each computed window minimum (diamonds). Below are the two stacks: each element has its value and its stack's minimum from itself to the bottom, and the yellow coins beside the input stack are the two each element pays for its future transfer. Watch the transfer: one operation processes every element, then output supplies ww cheap pops. For an increasing series, the window minimum is always the oldest element; for a decreasing series, the newest. Increase the window: what happens to the most expensive operation and to cost per element?

Amortized, average and worst case: what each guarantees

Three uses of “constant” should be kept distinct:

  • Worst-case O(1)\bigO(1): every individual operation takes less than a constant. This is needed by a real-time loop or a request with bounded tail latency (p99p99, p99.9p99.9).
  • Amortized O(1)\bigO(1): every sequence of mm operations takes O(m)\bigO(m) in total. An individual operation may take Θ(m)\Theta(m).
  • Average or expected O(1)\bigO(1): 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 ≤c\le c, mm cost ≤cm\le cm), not the reverse. Amortized cost says nothing about an individual operation. This is the difference between “mm calls to append cost O(m)\bigO(m)” 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 k≥2k \ge 2 be the number of extra copies each append will perform. When R=⌈cap/k⌉R = \lceil \mathrm{cap}/k \rceil slots remain free, allocate the buffer of capacity 2 cap2\,\mathrm{cap} and each append, besides writing its element to the old buffer, copies kk old elements to the new one. The old buffer still accepts RR more appends. During that time kR≥capkR \ge \mathrm{cap} 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 O(1)\bigO(1). Worst-case latency: 1+k1 + k, constant, versus 1+n1 + n for the all-at-once array.

The price is real. Total work does not decrease: with k=2k = 2 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: 1+k1 + k instead of 11 most of the time. A constant cost avoids the spike.

InteractiveSpreading the bill
Old buffer: 70 of 128New buffer (256): 12 copiedLatency per append: copy all at once050Latency per append: incremental migration, k = 2050worst-case bound 1 + k = 3
Append 70 of 70
  • all at once
  • incremental
  • old buffer
2
70
Maximum latency, all at once65
Maximum latency, incremental3
Total work, all at once196
Total work, incremental208 (1.06×)
Cost per operation (mean)2.80 and 2.97
Append 70: all at once, 1; incremental, 3 (1 write and 2 element copies).
Press ▶. Above are the incremental array's buffers: the old one fills and the new one receives kk copied elements per append. Below is each append's latency on the same vertical scale: beneath each spike of the all-at-once array (red), the incremental one (aquamarine) stays flat below 1+k1 + k. Increase kk: migration starts later and maximum latency grows. Compare their total work: what does spreading the bill really cost?

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 O(1)\bigO(1) 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 c^i\hat c_i and checks ∑c≤∑c^\sum c \le \sum \hat c. It shows the three outcomes from the warning above: a good potential (Φ=2 num−cap\Phi = 2\,\mathrm{num} - \mathrm{cap}, maximum amortized cost exactly 33), a valid but useless one (Φ=num\Phi = \mathrm{num}, expansion has linear amortized cost), and an invalid one (Φ=−num\Phi = -\mathrm{num}, which violates the inequality).

[ ]Counter, multipop stack and potential verifierBrowser
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 1994=2⋅1000−61994 = 2\cdot 1000 - 6 flips in 10001000 increments (1000=111110100021000 = 1111101000_2 has six ones), although the increment from 511511 to 512512 flips 1010 bits at once. The multipop stack costs considerably less than 2m2m because not everything pushed is eventually popped. The verifier distinguishes all three situations: the first potential satisfies max⁡c^=3\max \hat c = 3, the second gives max⁡c^=1026\max \hat c = 1026 (valid but useless), and the third violates the inequality.

Now the dynamic array on a NumPy buffer, counting copies. Each policy runs for 30 00030\,000 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.

[ ]Instrumented dynamic arrayBrowser
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 g/(g−1)g/(g-1) under all three multiplicative policies (the theorem’s bound for copying cost excluding writes), whereas additive growth explodes: about 937937 copies per append with k=16k = 16, matching n/(2k)=30000/32n/(2k) = 30000/32. 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 newsize+newsize/8+6\mathrm{newsize} + \mathrm{newsize}/8 + 6 rounded to a multiple of 44, an asymptotic factor of 1.1251.125. 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.

[ ]How list.append grows in CPythonBrowser
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 2,2,1.5,1.33…2, 2, 1.5, 1.33\dots and converge to 1.1251.125. With g=1.125g = 1.125 the amortized bound is 1010: 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.

[ ]Sliding-window minimum in amortized O(1)Browser
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 44 operations per element (analysis bound: 11 on entry, 22 on transfer, 11 on exit), and the monotonic queue practically 22, 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 503503, precisely the transfer of w+1=251w + 1 = 251 elements present when the oldest leaves. This is amortization in its purest form: one operation costs over 100100 times the average cost of 44, and both statements are true.

The production version

In real code, a dynamic array is rarely written by hand.

  • Python list, C++ std::vector, Rust Vec and 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.deque is a doubly linked list of blocks giving worst-case O(1)\bigO(1) 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 O(n)\bigO(n)).
  • For window minima and maxima in tabular data use pandas.Series.rolling(w).min() (or max()), linear in nn instead of Θ(nw)\Theta(nw); in NumPy use sliding_window_view(x, w).min(axis=1) if nwnw fits in memory, as in the lab above.
  • In PyTorch, torch.cat in a loop repeats the additive mistake: accumulate tensors in a Python list and concatenate once with torch.cat(lista) or torch.stack(lista).

Common mistakes

Exercises

NumericBit flips in a thousand increments
Start with a binary counter with all bits zero and increment it 10001000 times. Each bit flip costs 11. What is the exact total cost?
NumericCopies with factor 1.5
A dynamic array starts empty with capacity 11 and, on receiving an append when full, grows to capacity ⌈1.5 cap⌉\lceil 1.5\,\mathrm{cap}\rceil, copying all elements. Insert 10610^6 elements. How many elements are copied in total (excluding writes)?
NumericThe cost of thrashing
An array has capacity 10241024 and 10241024 elements. It doubles when full and, after a pop, halves if n≤cap/2n \le \mathrm{cap}/2, copying the nn remaining elements. Each write, deletion or copy costs 11. Execute 500500 push–pop pairs (1000 operations). What is the total cost?
NumericPops until shrinking
Under the quarter policy (halve when, after a pop, n≤cap/4n \le \mathrm{cap}/4), an array has just grown from 10241024 to 20482048 with n=1025n = 1025 elements. What is the fewest consecutive pops that triggers a shrink?
QuizWhat amortized cost guarantees
A structure has amortized O(1)\bigO(1) cost for all operations. Which statements are true?

More than one answer may be correct.

QuizWhich potentials work for the stack?
For the multipop stack, let ss be its size. Which functions allow the potential method to show that push, pop and multipop cost amortized O(1)\bigO(1)?

More than one answer may be correct.

QuizTwo-stack queue and old versions
A functional (immutable) two-stack queue returns a new queue on each operation and retains previous versions. Build queue QQ with nn elements on the input stack and empty output, then execute dequeue(Q) nn times on the same QQ. What happens?
ProofAppend with potential 2·num − cap
Prove: A dynamic array starts empty with capacity 0. On an append with num = cap, it allocates capacity max(1, 2·cap) and copies num elements. Writing or copying an element costs 1. With potential Φ=2 num−cap\Phi = 2\,\mathrm{num} - \mathrm{cap}, each append has amortized cost c^i≤3\hat c_i \le 3.
0
Let cic_i be the actual cost of the ii-th append and c^i=ci+Φi−Φi−1\hat c_i = c_i + \Phi_i - \Phi_{i-1}, with Φ0=0\Phi_0 = 0.

Step 1 of 4. What must be checked about Φ\Phi for ∑ci≤∑c^i\sum c_i \le \sum \hat c_i?

ProofThe V-shaped shrink potential
Prove: A dynamic array with power-of-two capacities doubles when full and, after a pop, halves if n≤cap/4n \le \mathrm{cap}/4 (with cap≥4\mathrm{cap} \ge 4; small capacities are checked by hand). Writing, deleting or copying an element costs 1. With potential Φ=2n−cap\Phi = 2n - \mathrm{cap} if n≥cap/2n \ge \mathrm{cap}/2 and Φ=cap/2−n\Phi = \mathrm{cap}/2 - n otherwise, amortized cost is c^≤3\hat c \le 3 for push and c^≤2\hat c \le 2 for pop.
0
Since Φ0=0\Phi_0 = 0 and Φ≥0\Phi \ge 0 always, it suffices to bound c^=c+ΔΦ\hat c = c + \Delta\Phi in each case. The preceding exercise showed c^=3\hat c = 3 for expansion.

Step 1 of 5. Where on the V does the array land after any resize?

CodeQueue with maximum in amortized O(1)
Implement 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 O(1)\bigO(1): 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ódigo
Shift+Enter to run

Summary

Key idea
Amortized cost is a worst-case guarantee on the total of a sequence, without probability: prove it using stored coins or a state potential function. It says nothing about an individual operation; when needed, spread the work to deamortize.
  • An amortized bound c^\hat c satisfies ∑ci≤∑c^i\sum c_i \le \sum \hat c_i 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 Θ(m)\Theta(m).
  • Aggregate: bound the total (multipop stack: ≤2n\le 2n; binary counter: T(n)=2n−s2(n)T(n) = 2n - s_2(n)). Accounting: fixed fees and coins attached to objects (never negative). Potential: c^i=ci+Φ(Di)−Φ(Di−1)\hat c_i = c_i + \Phi(D_i) - \Phi(D_{i-1}) and ∑c≤∑c^\sum c \le \sum \hat c if Φ(Dm)≥Φ(D0)\Phi(D_m) \ge \Phi(D_0), by telescoping.
  • Dynamic array with factor gg: T(n)<n(2g−1)/(g−1)T(n) < n(2g-1)/(g-1). Additive growth gives quadratic cost. Shrinking requires hysteresis: half causes thrashing; at one quarter, the V-shaped potential gives c^≤3\hat c \le 3 and c^≤2\hat c \le 2.
  • Two-stack queue: Φ=2 ∣entrada∣\Phi = 2\,\lvert\text{entrada}\rvert gives c^≤3\hat c \le 3. Each element stores its stack’s aggregate: a sliding-window minimum (or any associative aggregate) in amortized O(1)\bigO(1).
  • Deamortization: build the new structure incrementally, kk steps per operation, for worst-case bound 1+k1 + k. 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.