Amortized Analysis

One append to a full array can cost 33. Yet 64 appends to a doubling array cost 127 in total, under 3 each, every time. Charge 3 per append and the savings always cover the next copy.

Pick a growth rule and press Run 64. Watch the bank of saved coins under the spikes. Then we build, piece by piece, the three ways to prove such a bound and the tables that grow and shrink.

You need Big-O and a Python list. We build the rest from zero.

Based on Chapter 17 of Introduction to Algorithms, third edition, by Cormen, Leiserson, Rivest and Stein (CLRS). Before: Greedy Algorithms. Next: B-Trees.

Charge 3 per append

Illustrative cost model from CLRS: writing one element costs 1, copying one element costs 1. The array starts with 1 slot. "Grow by half" rounds the new size up.

Chapter 0

One Append Costs Nine

See why the worst single step gives the wrong total

A Python list keeps its elements in one block of memory with a fixed number of slots. When every slot is full, the next append must get a bigger block, copy every element across, and then write the new one.

Count the cost in steps: writing one element is 1, copying one element is 1. A normal append costs 1. An append into a full block of 8 costs 8 + 1 = 9.

Append and watch the copies

Filled slots are teal, empty slots grey. Press Append. When the block is full, the orange arrows show each copy into the new block.

The block starts with 1 slot and doubles when full. Costs follow the model above.

A worst-case thinker says: one append can cost about n, so n appends cost about n2. The count says otherwise. The first 16 appends cost 1, 2, 3, 1, 5, 1, 1, 1, 9 and then seven 1s. That is 31 in total, under 2 per append.

The amortized cost of an operation is a cost per operation that, added up, bounds the total actual cost of every sequence from the start. It is a promise about sequences, with no probability in it.

The failure: billing every operation at its worst case. Symptom: your estimate for a loop of appends says quadratic, but the timer grows in a straight line. Measure: time n and 2n appends; the ratio is about 2. Fix: bound the whole sequence, not the worst step.

The road

  1. Aggregate analysis: add the whole bill, then divide by n.
  2. The binary counter: count the flips one bit at a time.
  3. The accounting method: charge 3, bank the change (the hero's coins).
  4. Charge the element: the multipop stack and its coins.
  5. The potential method: one number of stored energy.
  6. The counter, by potential: and how DECREMENT breaks it.
  7. Dynamic tables: grow at full, shrink at a quarter.
  8. Amortized is not average: the spikes stay (the hero's growth rules).
  9. Where it shows up: deques, queues, heaps and trees.
  10. The field guide: numbers, code and links.
An array starts with 1 slot and doubles when full. How many appends out of the first 1,024 trigger a copy?

Chapter 1

Add It All Up, Then Divide

Bound the total bill of n appends and split it evenly

Aggregate analysis finds the total actual cost of n operations in the worst case, then gives each operation an equal share. It is the most direct of the three methods.

Split the bill of n appends in two. Every append writes once: that part is n. The copies happen only when the block is full, at 1, 2, 4, 8 elements, so the copy bills are powers of two. Call the total cost of n appends T(n), and the largest power of two below n 2k.

Say it aloud

T of n equals n, plus one plus two plus four and so on up to two to the k, and that is less than three n.

T(n)
T of n the total actual cost of n appends, starting from 1 slot.
n
n the number of appends; each one writes one element for a cost of 1.
1 + 2 + … + 2k
one plus two up to two to the k the copy bills. 2k is the largest power of two below n.
< 3n
less than three n the bound. Each doubling sum is one less than twice its last term, and 2k < n, so the copies stay under 2n.
In plain words

Add n for the writes. Add the copy bills, which double each time and stop below n. Their sum is under 2n, so T(n) is under 3n and each append gets a share under 3.

With numbers

n = 33: 2k = 32. T(33) = 33 + (1 + 2 + 4 + 8 + 16 + 32) = 33 + 63 = 96, under 3n = 99. The share is 96/33 = 2.91.

Stack the copy bills

The teal bar is the n writes. Each orange block is one copy bill. Drag n, then switch to adding 4 slots and watch the bill pass 3n.

33

Exact counts from the cost model. The array starts with 1 slot.

Why doubling matters: if the block grows by a fixed 4 slots, the copy bills are 1, 5, 9, 13 and so on. They add up to about n2/8, so the share per append grows with n. At n = 64 the total is 560, or 8.75 per append.

The failure: growing by a fixed amount. Symptom: appends slow down as the list grows. Measure: the time per append at n and at 10n; it rises about 10 times. Fix: grow by a factor, as Chapter 8 shows.

What does aggregate analysis give each operation?

Chapter 2

Count the Flips One Bit at a Time

Sum a binary counter's cost by column, not by step

A binary counter holds a number as a row of bits, starting at zero. INCREMENT adds 1: it turns the trailing 1s into 0s, then turns the next 0 into a 1. The cost is the number of bits that flip. Going from 0111 to 1000 flips 4 bits.

One increment can flip every bit. Do not count by step. Count by column: bit 0 flips on every increment, bit 1 on every second, bit 2 on every fourth. Call the total flips of n increments F(n).

Increment and count each column

The top row is the counter, bit 0 on the right. The bars count each bit's flips. Each bar is about half the one to its right.

The counter has 6 bits, so it wraps after 63. Counts are exact.

Say it aloud

F of n equals the sum over j of the floor of n over two to the j, and that is less than two n.

F(n)
F of n the total bit flips of n increments, starting from zero.
Σj
the sum over j add one term for each bit position j = 0, 1, 2 and up.
⌊n / 2j⌋
the floor of n over two to the j how many times bit j flips: once every 2j increments, rounded down.
< 2n
less than two n n + n/2 + n/4 + … never reaches 2n.
In plain words

For each bit j, divide n by 2 j times and round down. Add the results. The total F(n) stays under 2n, so each increment costs under 2 flips.

With numbers

n = 16: F(16) = 16 + 8 + 4 + 2 + 1 = 31, under 32. The share is 31/16 = 1.94 flips per increment.

An exact form also exists: F(n) = 2n minus the number of 1s in n. For n = 12 (binary 1100) that is 24 − 2 = 22. For n = 256 it is 512 − 1 = 511.

The failure: a counter that can also go down. Symptom: the flip count per step stays high. Measure: alternate +1 and −1 at 0111; every step flips 4 bits. Fix: the bound holds only for INCREMENT alone, as Chapter 6 shows.

After 16 increments from zero, how many times has bit 2 flipped?

Chapter 3

Charge Three, Bank the Change

Overcharge the cheap steps so the credit pays for the copies

The accounting method charges each operation a fixed price, its amortized cost. If the price is more than the actual cost, the change is credit, stored as coins on elements of the structure. A costly operation pays with stored coins. The one rule: the credit never goes below zero.

Call the actual cost of operation i ci and its charge ĉi. The rule says the charges cover the actual costs after every prefix of the sequence.

Say it aloud

The sum over i from one to n of c-hat i is at least the sum over i from one to n of c i, for every n.

Σi=1..n
the sum over i from one to n add the first n operations.
ĉi
c-hat i the charge of operation i, its amortized cost. Here 3 for every append.
≥
is at least the charges never fall behind the bill.
ci
c i the actual cost of operation i: 1, or 1 plus the copies.
for every n
for every n the rule must hold after each step, not only at the end. The difference is the bank.
In plain words

After each step, add up the charges ĉi and the actual costs ci so far. The charges must never be smaller. Their difference is the credit in the bank.

With numbers

After 8 appends at 3 each: charges 24, actual 1 + 2 + 3 + 1 + 5 + 1 + 1 + 1 = 15, bank 9. Append 9 copies 8 and costs 9: bank 9 + 3 − 9 = 3.

Put coins on the slots

Each append pays the charge. One coin pays its write, and the rest sit on its slot. A copy takes one coin per element moved. Try a charge of 2.

Exact ledger from the cost model; the array starts with 1 slot. A copy spends coins from the newest slots first.

Why 3 is enough: just before the block of size m fills, the m/2 elements that arrived since the last copy each hold 2 coins. That is m coins, one per element to copy. A charge of 2 leaves 1 coin each, and the bank is short at append 5.

The failure: a charge that is too low. Symptom: the bank goes negative, so the bound is false. Measure: run the ledger; with charge 2 the bank reads −2 after append 5 and −6 after append 9. Fix: raise the charge, or put the coins where the next bill lands.

You charge 3 per append. After 8 appends from 1 slot, how much credit is in the bank?

Chapter 4

Charge the Element, Not the Step

Put one coin on each pushed plate to pay for its pop

A stack of plates has three operations. PUSH adds one plate for a cost of 1. POP removes one for a cost of 1. MULTIPOP(k) removes k plates, or all of them if fewer are left, for a cost of 1 per plate. One MULTIPOP can cost n.

Follow the plates, not the operations. You push a plate once and pop it at most once. So the pops of a whole sequence, by POP or MULTIPOP, can never outnumber the pushes. With n operations the total cost is at most 2n.

Push plates, then pop them in bulk

Each push pays 2: one for the push, one coin left on the plate. A pop of any size spends the coins of the plates it removes.

Charges: PUSH 2, POP 0, MULTIPOP 0. Actual cost: 1 per plate pushed or popped. The stack holds at most 12 plates here.

With numbers: push 100 plates, then MULTIPOP(100). That is 101 operations. The actual cost is 100 + 100 = 200, and the charges total 2 × 100 = 200. The bank ends at zero, never below. Per operation: 200/101 = 1.98.

The same trick bounds a queue built from two stacks. ENQUEUE pushes on stack A. DEQUEUE pops stack B; if B is empty, it first moves all of A onto B. Each element gets one push, one move and one pop: charge 3 per ENQUEUE and 0 per DEQUEUE.

OperationActual costChargeCoins after
PUSH12one more, on the new plate
POP10one fewer
MULTIPOP(k)min(k, s)0min(k, s) fewer

The failure: an operation that adds work without adding elements, such as a "peek all" that reads every plate. Symptom: the coin count stops matching the plates. Measure: give it its own cost. Fix: charge it its full cost, or prove a new bound.

Why can the pops of a sequence never cost more than the pushes?

Chapter 5

Store the Credit as Energy

Replace the coins with one number that rises before a copy and falls during it

The potential method keeps no coins on elements. It measures the whole structure with one number, the potential Φ (say "phi"): energy that cheap steps store and costly steps release. Call the state after operation i Di.

Say it aloud

c-hat i equals c i, plus phi of D i, minus phi of D i minus one.

ĉi
c-hat i the amortized cost of operation i.
ci
c i its actual cost.
Φ(Di)
phi of D i the potential of the structure just after operation i.
Φ(Di−1)
phi of D i minus one the potential just before it.
In plain words

Take the actual cost ci. Add how much the potential went up, or subtract how much it went down. The result is ĉi.

With numbers

Append 9 on a full block of 8: c9 = 9, and the potential falls from 8 to 2. ĉ9 = 9 + 2 − 8 = 3.

Add this over n operations and the middle terms cancel in pairs:

Σ ĉi = Σ ci + Φ(Dn) − Φ(D0)

Here D0 is the starting state and Dn the final one. If Φ(Dn) never drops below Φ(D0), the amortized total is at least the actual total. That is the whole proof obligation.

For the array, store energy as the block fills. Call the number of elements num and the number of slots cap.

Say it aloud

Phi equals two times num, minus cap.

Φ
phi the potential of the array.
2
two each element adds 2: one to copy itself, one to copy an older element.
num
num the number of elements stored.
cap
cap the number of slots in the block.
In plain words

Double num and take away cap. A half-full block has Φ = 0. A full block has Φ = cap, exactly what the next copy needs.

With numbers

A plain append raises num by 1: c = 1, Φ rises by 2, ĉ = 3. Append 9: before, num = 8 and cap = 8, so Φ = 8. After, num = 9 and cap = 16, so Φ = 2. ĉ = 9 + 2 − 8 = 3.

Watch the potential pay the copy

Bars are actual costs; the purple line is Φ; blue dots are ĉ. Drag to pick one append. Then try the weaker potential Φ = num.

9

Exact values; the array starts with 1 slot, so Φ(D0) = 2·0 − 1 = −1, and Φ is 0 or more after every append.

The failure: a potential that does not fall far enough. With Φ = num, append 9 costs 9 and the potential rises by 1, so ĉ = 10. Symptom: ĉ spikes with each copy. Measure: compute ĉ for a cheap and a costly step. Fix: make Φ equal the coming bill at the moment it arrives.

An append into a block that is not full: what are c, the change in Φ = 2·num − cap, and ĉ?

Chapter 6

The Counter, by Potential

Let the count of 1-bits absorb the carry, then break it with DECREMENT

For the binary counter, the energy is the 1-bits waiting to carry. Set Φ to the number of 1s in the counter. It starts at 0 and can never go negative.

Call the number of trailing 1s that an increment turns into 0s t. The increment flips those t bits and one more bit from 0 to 1. So the actual cost is t + 1, and the count of 1s changes by 1 − t.

Say it aloud

c-hat equals t plus one, plus one minus t, which equals two.

ĉ
c-hat the amortized cost of one INCREMENT.
t + 1
t plus one the actual cost: t trailing 1s cleared and one 0 set.
1 − t
one minus t the change in Φ: one new 1, t old 1s gone.
2
two the t terms cancel, whatever t is.
In plain words

Count the trailing 1s, t. The increment costs t + 1. The potential drops by t − 1. Add them: the t cancels, and ĉ is always 2.

With numbers

15 to 16 is 01111 to 10000, so t = 4. Actual cost 5, Φ goes from 4 to 1, a change of −3. ĉ = 5 − 3 = 2.

Increment, then try going back

Bars show each step's actual cost; the blue dot is its ĉ. Increments always land on 2. Then load 011111 and alternate.

Six bits; an increment at 63 wraps to 0. DECREMENT turns trailing 0s into 1s and the next 1 into a 0. Counts are exact.

Now allow DECREMENT. From 011111, an increment gives 100000 and flips 6 bits. A decrement gives 011111 back and flips 6 bits again. Alternate, and every step costs k flips for a k-bit counter. No potential can fix this: the actual total is k per step.

The failure: adding an operation and keeping the old bound. Symptom: a counter that was cheap gets slow under mixed traffic. Measure: log flips per step; it sits at k. Fix: prove the bound again for the full set of operations.

The counter holds 0111. You increment. What are the actual cost, the change in Φ, and ĉ?

Chapter 7

Grow at Full, Shrink at a Quarter

Add deletes to the table and keep every operation cheap on the books

A dynamic table grows and also shrinks, so a hash table does not hold memory it no longer needs. Its load factor α (say "alpha") is num/cap, the share of slots in use. An INSERT into a full table doubles it. A DELETE that drops α below a threshold halves it. Each resize copies every element.

The obvious threshold is 1/2. It fails. Fill a table of 8, then insert: it doubles to 16 and holds 9. Delete twice: 7 is under half of 16, so it halves to 8. Insert twice: full again, so it doubles. Each four steps cost 8 + 1 + 1 + 9. That is thrashing: about n/2 per step.

Insert, delete, and try to thrash it

Top: the slots. Middle: Φ against α, a V with its low point at 1/2. Bottom: the cost of each step. Press "Fill to 8, then wiggle" under each rule.

CLRS rules: an empty table has no slots; the first insert makes 1. A delete that empties the table frees it. Costs: 1 per write or delete, 1 per element copied.

CLRS shrinks when α drops below 1/4. Right after any resize α is near 1/2, so about cap/2 cheap steps must pass before the next resize. Those steps store the energy to pay for it. The potential is a V around α = 1/2:

Say it aloud

Phi equals two num minus cap if alpha is at least one half, and cap over two minus num if alpha is less than one half.

Φ
phi the potential of the table; 0 for an empty table.
α
alpha the load factor num/cap, the share of slots in use.
2·num − cap
two num minus cap energy for the coming double. It reaches cap when the table is full.
cap/2 − num
cap over two minus num energy for the coming halve. It reaches cap/4 when α reaches 1/4.
In plain words

Measure how far num is from half of cap. Above half, count each extra element twice. Below half, count each missing element once. Both pieces are 0 at α = 1/2.

With numbers

cap = 16, num = 4, so α = 1/4 and Φ = 8 − 4 = 4. Delete one: 3 is below a quarter, so the table halves to 8 and copies 3. Actual cost 4; new Φ = 4 − 3 = 1. ĉ = 4 + 1 − 4 = 1.

Every case comes out small. An INSERT has ĉ at most 3. A DELETE has ĉ at most 2. A check of all cases, and of random sequences of 300 steps, gives no value above 3.

Stepnum, cap afterActualΦ afterĉ
9th insert9, 16923
delete8, 1610−1
delete7, 16112
3 more deletes4, 16342 each
delete3, 8411
Why does CLRS shrink the table at α < 1/4 and not at α < 1/2?

Chapter 8

Amortized Is Not Average

Choose the growth factor, and see that the spikes stay unless you spread them

An amortized bound is a worst-case bound on a total. It does not promise anything about one step. A doubling array still has an append that copies a million elements. If each step has a deadline, that one step misses it.

Kind of boundWhat it promisesExample
Worst case per stepevery single step is cheapa red-black tree search, O(log n)
Amortizedevery sequence is cheap in total, no probabilitydoubling append, under 3 per step
Average casecheap in expectation over random inputs or random choicesquicksort, O(n log n) expected

The growth factor sets the price. Call it r: a full block of size m grows to r·m. The copy bills form a sum that grows by r each time, under n·r/(r − 1). Add n writes:

Say it aloud

c-hat equals two r minus one, over r minus one.

ĉ
c-hat the amortized cost per append that always covers the bill.
2r − 1
two r minus one the writes (r − 1 of them) plus the copies (r) per r − 1 appends.
r − 1
r minus one the share of new room each resize adds. As r nears 1 it nears 0 and the price blows up.
In plain words

Double r and take 1. Divide by r minus 1. A bigger r means a lower ĉ but more empty slots: just after a resize, (r − 1) times num slots are empty.

With numbers

r = 2: ĉ = 3/1 = 3, and up to 100% extra slots. r = 1.5: ĉ = 2/0.5 = 4, up to 50% extra. r = 1.25: ĉ = 6.

Compare the spikes

Each bar is one append. The blue line is the running average; the dashed line marks the largest single step. "Spread the copy" moves 2 old elements on every append.

Illustrative cost model. "Spread the copy" starts a block twice as large when the old one is half full. Then it copies 2 elements per append. The first block has 2 slots.

De-amortization spreads the expensive work over the cheap steps. When the block is half full, start a block twice as large. Each append writes its element and copies 2 old ones. When the old block fills, the copy ends. Every append costs at most 3: the amortized price, paid on time.

The failure: a resize spike inside a deadline. Symptom: rare slow requests on a server that is fast on average. Measure: the slowest step, not the mean. Fix: reserve the size in advance, use a de-amortized structure, or use a structure with worst-case bounds.

Each request must finish in 10 ms. One option has amortized O(1) steps with rare O(n) spikes; the other has O(log n) steps in the worst case. Which fits the deadline?

Chapter 9

Where It Shows Up

Spot the "each element in once, out once" pattern in real code

The plate argument hides inside many loops. Take the sliding window maximum: report the largest value in every window of k neighbours. Keep a deque of indices whose values fall from front to back. For each new value, pop smaller values off the back, pop the front if it has left the window, then push the new index.

Step the window

The bracket is the window of 3. The row below is the deque, front on the left. One inner loop can pop many, but count the total.

The first array, 1 3 −1 −3 5 3 6 7 with k = 3, is the worked example. New numbers are random, n = 12.

With numbers: on 1, 3, −1, −3, 5, 3, 6, 7 the maxima are 3, 3, 5, 5, 6, 7. The deque does 8 pushes and 7 pops, 15 operations, under 2n = 16. Each index enters once and leaves at most once.

StructureCostly stepAmortized boundPotential or charge
Doubling arraycopy on fullO(1) per append2·num − cap
Hash tablerehash on growO(1) per insert, from resizingsame as a dynamic table
Two-stack queuemove A onto BO(1) per operationcharge 3 per enqueue
Splay treea deep accessO(log n)sum of log(subtree size)
Fibonacci heapconsolidate on extract-minO(1) decrease-keytrees + 2 × marked nodes
Union-finda long find pathO(α(n)), inverse Ackermannbased on ranks

The Fibonacci heap matters for Dijkstra's algorithm, which can call decrease-key once per edge. With O(1) amortized decrease-key, Dijkstra runs in O(E + V log V) instead of O((V + E) log V) with a binary heap.

The failure: summing amortized bounds of two structures that share state. Symptom: the combined proof has a gap. Measure: look for an operation of one that raises the other's potential. Fix: one potential for the whole system.

The sliding window loop has a while-loop inside a for-loop over n values. Why is the total work O(n)?

Chapter 10

The Field Guide

Keep the methods, the numbers and the code in one place

Amortized analysis bounds the total cost of any sequence and shares it out. Aggregate adds the bill. Accounting banks coins on elements. Potential stores the same credit as one number of the whole structure.

Term or numberMeaning
amortized cost ĉa per-step price whose sum bounds the actual total of every sequence
T(n) < 3nn appends to a doubling array; 64 appends cost 127
F(n) = 2n − (1s in n)bit flips of n increments; under 2n
Σ ĉ ≥ Σ cthe accounting rule, after every step
ĉ = c + ΔΦthe potential method; needs Φ(Dn) ≥ Φ(D0)
Φ = 2·num − caparray potential; ĉ = 3 per append
Φ = number of 1scounter potential; ĉ = 2 per increment
1/4shrink trigger for a dynamic table; insert ĉ ≤ 3, delete ĉ ≤ 2
(2r − 1)/(r − 1)price per append with growth factor r: 3 at r = 2, 4 at r = 1.5

Before you claim amortized O(1)

  1. Name the costly step and what builds up before it.
  2. Pick a method: aggregate if all steps are alike, accounting or potential if they differ.
  3. Check the rule after every step, not only at the end.
  4. List every operation. One new operation can break the bound.
  5. Ask if any single step has a deadline. If so, amortized is not enough.

The core

pythonclass Table:                                    # CLRS dynamic table: double at full, halve below 1/4
    def __init__(self):
        self.num, self.cap = 0, 0

    def phi(self):                               # the V-shaped potential
        if self.cap == 0: return 0
        if 2 * self.num >= self.cap: return 2 * self.num - self.cap
        return self.cap / 2 - self.num

    def insert(self):                            # returns (actual, amortized)
        before, cost = self.phi(), 1
        if self.cap == 0: self.cap = 1
        elif self.num == self.cap: cost += self.num; self.cap *= 2   # copy all, double
        self.num += 1
        return cost, cost + self.phi() - before      # never above 3

    def delete(self):
        before, cost = self.phi(), 1
        self.num -= 1
        if self.num == 0: self.cap = 0                 # free the empty table
        elif 4 * self.num < self.cap: cost += self.num; self.cap //= 2   # copy all, halve
        return cost, cost + self.phi() - before      # never above 2

Keep going

Credit: this lesson follows Chapter 17, Amortized Analysis, of Introduction to Algorithms, third edition, by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein (MIT Press). The potential method is from Robert E. Tarjan, "Amortized Computational Complexity" (1985). Splay trees are from Sleator and Tarjan (1985); Fibonacci heaps from Fredman and Tarjan (1987).

The takeaway. Do not bill each step at its worst. Bill the sequence, and show the savings from cheap steps always cover the costly one.

Explain it back with Present or Teach, or go back to the bank and predict when "Grow by half" first runs out of coins.

Amortized Analysis, CLRS Chapter 17
Back to Gleams