Simple Algorithm
Algorithms & Data Structures · Optimized · 22 min

Amortized Analysis

Why an expensive step now and then still averages out: aggregate, accounting and potential.

Appending to a Python list sometimes copies the whole list, an operation that costs Θ(n)\Theta(n). Yet a million appends take about as long as a million cheap ones. Amortized analysis explains why with a guarantee, not a hope: no sequence of operations, however adversarial, can make the average cost per operation grow.

What you’ll learn

  • Define amortized cost, and distinguish it from average-case and expected cost.
  • Bound the total cost of a sequence by the aggregate method: dynamic arrays, binary counters, multipop stacks.
  • Assign amortized costs with the accounting method and with a potential function, and check the conditions that make them valid.
  • Recognize amortized linear time in monotonic stacks, two pointers and similar loops, and know what amortized bounds do not promise.

Expensive sometimes, cheap on average

A dynamic array keeps its elements in one block of contiguous memory with some spare room, its capacity. An append writes into the spare room in O(1)O(1) time. When the block is full, the array allocates a bigger one and copies every element over: one append then costs Θ(n)\Theta(n).

If the new block is twice as large, copies are rare, and they get rarer as they get bigger. Amortized analysis makes this precise: if every sequence of nn operations costs at most T(n)T(n) in total, each operation has amortized cost T(n)/nT(n)/n, even when single operations cost far more.

python
class DynArray:
    def __init__(self):
        self.cap, self.n, self.data = 0, 0, []
        self.writes = 0                   # element writes, to measure the cost

    def append(self, x):
        if self.n == self.cap:            # full: allocate twice the room, copy everything
            self.cap = max(1, 2 * self.cap)
            new = [None] * self.cap
            for i in range(self.n):
                new[i] = self.data[i]
            self.writes += self.n
            self.data = new
        self.data[self.n] = x
        self.n += 1
        self.writes += 1

We count element writes: one per append, plus one per element copied during a resize. Real libraries grow by different factors (CPython lists by about an eighth plus a constant, Java's ArrayList by half, GCC's std::vector by two), and any constant growth factor above 1 gives the same amortized bound.

Predict before you look

Starting from an empty DynArray (capacity 0, then 1, 2, 4, …), how many element writes do 17 appends make in total?

Show the answer

48

Resizes happen at appends 2, 3, 5, 9 and 17, copying 1+2+4+8+16=311+2+4+8+16=31 elements; with the 17 writes of the new elements that is 48. The 17th append alone writes 17 elements, but the average is under 3, and it stays under 3 for every nn.

The aggregate method

The aggregate method bounds the total cost of nn operations directly and divides by nn. Three classic examples:

DerivationThree totals
  1. total ≤ n+(1+2+4+⋯+2⌊log⁡2(n−1)⌋) < n+2n = 3n\text{total}\ \le\ n+\big(1+2+4+\dots+2^{\lfloor\log_2(n-1)\rfloor}\big)\ <\ n+2n\ =\ 3n

    Dynamic array with doubling. The resizes copy 1,2,4,…1,2,4,\dots elements, each at most the current size, so the copies sum to less than 2n2n; add nn writes of new elements:

  2. ∑i≥0⌊n2i⌋ < n∑i≥02−i = 2n\sum_{i\ge0}\Big\lfloor\frac{n}{2^i}\Big\rfloor\ <\ n\sum_{i\ge0}2^{-i}\ =\ 2n

    Binary counter. Incrementing a counter from 0 flips the trailing 1s to 0 and one 0 to 1. A single increment can flip all kk bits, but bit ii flips only every 2i2^i-th time, ⌊n/2i⌋\lfloor n/2^i\rfloor times in nn increments:

  3. #pops ≤ #pushes ≤ n⟹total ≤ 2n\#\text{pops}\ \le\ \#\text{pushes}\ \le\ n\qquad\Longrightarrow\qquad\text{total}\ \le\ 2n

    Multipop stack. MULTIPOP(k) pops up to kk elements and can cost Θ(n)\Theta(n) once. But each element is popped at most once after being pushed once, so pops never outnumber pushes:

StructureWorst single operationTotal for nn operationsAmortized per operation
dynamic array, doublingΘ(n)\Theta(n) (a resize)<3n<3nO(1)O(1)
binary counter, increments onlyΘ(k)\Theta(k) for kk bits2n−ν(n)<2n2n-\nu(n)<2n flipsO(1)O(1)
stack with multipopΘ(n)\Theta(n)≤2n\le2nO(1)O(1)
ν(n)\nu(n) is the number of 1 bits of nn: 1000 increments flip exactly 2000−6=19942000-6=1994 bits.

The accounting method

The accounting method charges each operation a fixed amortized cost. When the charge exceeds the actual cost, the difference is stored as credit on specific elements of the structure; expensive operations are paid from stored credit. The rule that makes it valid: total credit never goes negative. Then the total charged is at least the total actual cost.

For the dynamic array, charge 3 per append. One unit pays for writing the element; two units are left on it as credit. When a full array of capacity cc doubles, the c/2c/2 elements appended since the last resize hold 2⋅c/2=c2\cdot c/2=c units of credit: exactly enough to copy all cc elements, the old ones included. Credit is back to zero, and the next resize is again paid in advance.

For the binary counter, charge 2 per increment: one unit pays for setting a bit to 1, and the other stays on that bit to pay for resetting it to 0 later. Every 1 bit always carries one unit, and the cascade of resets that an increment triggers is prepaid. For the multipop stack, charge 2 per push and 0 per pop: the extra unit on each element pays for its eventual pop, whichever operation pops it.

Think first Why would charging only 2 per append not work for the doubling array?

With 2 per append, each new element arrives with 1 unit of credit. At the resize from cc to 2c2c, only the c/2c/2 newest elements carry credit, c/2c/2 units in all, but copying costs cc. The old elements spent their credit at the previous resize, so the newcomers must pay for them too: 2 units of credit each, 3 in total per append.

The potential method

DerivationWhy it works: the potentials telescope
  1. ∑i=1nc^i = ∑i=1nci + Φ(Dn)−Φ(D0)\sum_{i=1}^{n}\hat c_i\ =\ \sum_{i=1}^{n}c_i\ +\ \Phi(D_n)-\Phi(D_0)

    Sum the amortized costs over nn operations; every intermediate potential cancels:

  2. Φ(Dn) ≥ Φ(D0) for all n⟹∑i=1nci ≤ ∑i=1nc^i\Phi(D_n)\ \ge\ \Phi(D_0)\ \text{for all }n\qquad\Longrightarrow\qquad\sum_{i=1}^{n}c_i\ \le\ \sum_{i=1}^{n}\hat c_i

    So the amortized costs bound the actual total whenever the final potential is at least the initial one. The usual way to ensure it is Φ(D0)=0\Phi(D_0)=0 and Φ≥0\Phi\ge0 always:

  3. c^ = 1+2 = 3andc^ = (c+1)+(2−c) = 3\hat c\ =\ 1+2\ =\ 3\qquad\text{and}\qquad\hat c\ =\ (c+1)+(2-c)\ =\ 3

    Dynamic array, with Φ=2⋅size−capacity\Phi=2\cdot\text{size}-\text{capacity}, which is 0 for the empty array and never negative afterwards, since a doubling array is always at least half full. An append without a resize costs 1 and raises Φ\Phi by 2. An append into a full array of capacity cc costs c+1c+1, while Φ\Phi falls from 2c−c=c2c-c=c to 2(c+1)−2c=22(c+1)-2c=2:

  4. c^ = (t+1)+(1−t) = 2\hat c\ =\ (t+1)+(1-t)\ =\ 2

    Binary counter, with Φ\Phi = the number of 1 bits. An increment that resets tt trailing 1s and sets one 0 costs t+1t+1 and changes Φ\Phi by 1−t1-t:

The potential method is the accounting method with the credit written as a function of the state rather than of the history. That makes it the tool of choice for complex structures: splay trees, Fibonacci heaps and union–find are all analyzed with clever potentials.

Check your understanding

Which potential shows that push, pop and MULTIPOP(k) all have amortized cost O(1)O(1)?

  1. Φ=0\Phi=0 for every state
  2. Φ=\Phi= the number of operations performed so far
  3. Φ=\Phi= the number of elements on the stack
  4. Φ=2size\Phi=2^{\text{size}}
Show the answer

C. Φ=\Phi= the number of elements on the stack

A push costs 1 and raises Φ\Phi by 1, so c^=2\hat c=2. A pop costs 1 and lowers Φ\Phi by 1, so c^=0\hat c=0. MULTIPOP removing mm elements costs mm and lowers Φ\Phi by mm: c^=0\hat c=0. And Φ\Phi starts at 0 and never goes negative.

What amortized bounds do not promise

Latency. An amortized bound says nothing about one operation. The append that resizes an array of 10810^8 elements copies all of them, a pause of tens to hundreds of milliseconds. That is harmless in a batch job and unacceptable in a game loop, a trading system or a hard real-time controller; the Optimal lessons show how to spread the work out.

Robustness. The analysis assumed the operations given. Add one more, and an adversary may return the structure to an expensive state again and again. A kk-bit counter with decrement as well as increment can alternate between 2k−1−12^{k-1}-1 and 2k−12^{k-1}, flipping all kk bits every time: Θ(nk)\Theta(nk) for nn operations. A dynamic array that halves as soon as it is half full can be pushed back and forth across that boundary.

A third trap is persistence: if old versions of a structure stay usable, an adversary can rerun an expensive operation on the same old version as often as it likes, and the credit paid in advance is spent many times. Amortized bounds assume each state is used once, in sequence.

Recognizing it

Amortization hides in loops whose inner work looks unbounded but is paid for by progress elsewhere. The signals:

  • each element enters and leaves a structure at most once (a stack, a queue, a window);
  • a pointer or a counter only moves one way, so the total of its moves is bounded even if one step moves it far;
  • a structure is rebuilt occasionally, at sizes that grow geometrically.

The classic case is the monotonic stack. To find each element's next greater element, keep a stack of indices still waiting for an answer; a new value pops every smaller value it is the answer for.

python
def next_greater(a):
    """res[i] = the first a[j] > a[i] with j > i, or -1."""
    res = [-1] * len(a)
    stack = []                      # indices still waiting for an answer
    for i, x in enumerate(a):
        while stack and a[stack[-1]] < x:
            res[stack.pop()] = x    # x is the first greater value for that index
        stack.append(i)
    return res

print(next_greater([2, 7, 3, 5, 4, 6, 1, 8]))   # [7, 8, 5, 6, 6, 8, 8, -1]

The while loop can pop many indices at once, so one iteration of the for loop may cost Θ(n)\Theta(n). But every index is pushed once and popped at most once: at most 2n2n stack operations in total, O(n)O(n) time.

Problem (in brief)Why the total is boundedTotal cost
Next greater element; days until a warmer dayeach index is pushed once and popped at most onceO(n)O(n)
Longest substring without a repeated charactertwo pointers: left and right each move forward at most nn timesO(n)O(n)
Maximum of every window of length kkmonotonic deque: each index enters and leaves onceO(n)O(n)
KMP pattern matchingthe matched length rises by at most 1 per text character, so it can fall at most nn times in totalO(n+m)O(n+m)
Hash table with resizingrehash everything when the load factor passes a constant, doubling the tableO(1)O(1) amortized per insert (expected, over the hashing)

Common bugs

  • list.pop(0) or list.insert(0, x) in a Python loop: each shifts the whole list, Θ(n)\Theta(n) per call. Use collections.deque.
  • Building a string with += in a loop in a language with immutable strings (Java, C#): Θ(n2)\Theta(n^2) in total. Use a builder, or collect the pieces and join them once.
  • Resetting a pointer that the analysis assumes only moves forward.
  • Shrinking a buffer as soon as it is half empty, which thrashes.
  • Citing an amortized bound where a per-operation deadline is required.
Check your understanding

For each of n≤2⋅105n\le2\cdot10^5 daily temperatures, find how many days pass until a strictly warmer day. Which approach fits the limits?

  1. For each day, scan forward until a warmer day appears
  2. Sort the temperatures and binary search for each day
  3. Scan once with a stack of days still waiting for a warmer day, popping them when one arrives
  4. Divide and conquer on the two halves of the array
Show the answer

C. Scan once with a stack of days still waiting for a warmer day, popping them when one arrives

This is next greater element with indices: every day is pushed once and popped at most once, so the scan is O(n)O(n) in total even though one day can pop many. The forward scan is Θ(n2)\Theta(n^2) on a decreasing sequence, about 2×10102\times10^{10} steps.

Key takeaways

  • An amortized bound limits the total cost of every sequence of operations; single operations may still be expensive, and no probability is involved.
  • The aggregate method bounds the total directly: nn appends to a doubling array cost under 3n3n writes, nn increments of a binary counter flip under 2n2n bits, and a multipop stack does at most 2n2n work.
  • The accounting method stores credit on elements and the potential method stores it in a function of the state; both are valid when the stored amount never drops below where it started (Φ(Dn)≥Φ(D0)\Phi(D_n)\ge\Phi(D_0)).
  • Amortized bounds promise nothing about one operation's latency, and they can break when an operation lets an adversary revisit expensive states (decrements, shrinking at half, persistence).
  • Look for amortization wherever elements enter and leave once or pointers only move forward: monotonic stacks and queues, two pointers, KMP, resizing hash tables.

Check yourself

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

Question 1

A data structure supports insert in O(1)O(1) amortized time. Which statement is guaranteed?

  1. Every single insert takes O(1)O(1) time
  2. Any sequence of nn inserts, starting from an empty structure, takes O(n)O(n) time in total
  3. Inserts take O(1)O(1) time on average over random inputs
  4. Inserts take O(1)O(1) expected time over the structure's random choices
Show the answer

B. Any sequence of nn inserts, starting from an empty structure, takes O(n)O(n) time in total

Amortized bounds are worst-case bounds on totals. A single insert may still cost Θ(n)\Theta(n), as a dynamic array's resize does, but no sequence of nn inserts can cost more than O(n)O(n).

Question 2

A dynamic array grows by 1000 slots whenever it is full. What is the total cost of nn appends, for large nn?

  1. Θ(n)\Theta(n)
  2. Θ(nlog⁡n)\Theta(n\log n)
  3. Θ(n2)\Theta(n^2)
  4. Θ(1000 n)\Theta(1000\,n)
Show the answer

C. Θ(n2)\Theta(n^2)

Resizes happen every 1000 appends and copy 1000,2000,3000,…1000, 2000, 3000, \dots elements, about n2/2000n^2/2000 copies in all: Θ(n2)\Theta(n^2), only with a small constant. Any additive growth policy is quadratic; a constant factor above 1 is what makes appends amortized O(1)O(1).

Question 3

In the potential method, why must Φ(Dn)≥Φ(D0)\Phi(D_n)\ge\Phi(D_0) hold for every nn?

  1. So that the sum of the amortized costs is an upper bound on the sum of the actual costs
  2. So that every single operation has a nonnegative amortized cost
  3. So that the potential function is unique
  4. So that the actual costs are bounded by a constant
Show the answer

A. So that the sum of the amortized costs is an upper bound on the sum of the actual costs

The sum telescopes: ∑c^i=∑ci+Φ(Dn)−Φ(D0)\sum\hat c_i=\sum c_i+\Phi(D_n)-\Phi(D_0). If the potential could end below where it started, the amortized costs would undercount the work actually done, and the bound would be false.

Question 4

A kk-bit binary counter supports both increment and decrement. In the worst case, what do nn operations cost in bit flips?

  1. O(n)O(n), by the same potential as for increments
  2. O(nlog⁡k)O(n\log k)
  3. Θ(nk)\Theta(nk)
  4. O(n+k)O(n+k)
Show the answer

C. Θ(nk)\Theta(nk)

Alternating between 2k−1−12^{k-1}-1 (a 0 followed by k−1k-1 ones) and 2k−12^{k-1} (a 1 followed by k−1k-1 zeros) flips all kk bits every time. With increments only, each expensive operation lowers the number of 1 bits, and that is what the potential relied on; a decrement undoes that progress.

Question 5

In the monotonic-stack algorithm for next greater elements on nn values, what is the largest possible total number of pops, over the whole run?

  1. n−1n-1
  2. n(n−1)/2n(n-1)/2
  3. nlog⁡2nn\log_2n
  4. 2n2n
Show the answer

A. n−1n-1

Every index is pushed once and popped at most once, and the index of the largest value is never popped. An increasing sequence achieves n−1n-1: each new value pops the previous one. Together with the nn pushes, the stack does fewer than 2n2n operations.

Go deeper

Further reading

  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 16, "Amortized Analysis".
  • R. E. Tarjan, "Amortized computational complexity," SIAM Journal on Algebraic and Discrete Methods 6(2) (1985), 306–318.
  • K. Mehlhorn & P. Sanders, Algorithms and Data Structures: The Basic Toolbox (Springer, 2008), chapter 3.