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.
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
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.
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.
Chapter 1
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.
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.
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.
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.
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.
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.
Chapter 2
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).
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.
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.
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.
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.
Chapter 3
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.
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.
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.
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.
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.
Chapter 4
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.
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.
| Operation | Actual cost | Charge | Coins after |
|---|---|---|---|
| PUSH | 1 | 2 | one more, on the new plate |
| POP | 1 | 0 | one fewer |
| MULTIPOP(k) | min(k, s) | 0 | min(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.
Chapter 5
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.
c-hat i equals c i, plus phi of D i, minus phi of D i minus one.
Take the actual cost ci. Add how much the potential went up, or subtract how much it went down. The result is ĉi.
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.
Phi equals two times num, minus cap.
Double num and take away cap. A half-full block has Φ = 0. A full block has Φ = cap, exactly what the next copy needs.
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.
Bars are actual costs; the purple line is Φ; blue dots are ĉ. Drag to pick one append. Then try the weaker potential Φ = num.
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.
Chapter 6
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.
c-hat equals t plus one, plus one minus t, which equals two.
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.
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.
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.
Chapter 7
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.
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:
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.
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.
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.
| Step | num, cap after | Actual | Φ after | ĉ |
|---|---|---|---|---|
| 9th insert | 9, 16 | 9 | 2 | 3 |
| delete | 8, 16 | 1 | 0 | −1 |
| delete | 7, 16 | 1 | 1 | 2 |
| 3 more deletes | 4, 16 | 3 | 4 | 2 each |
| delete | 3, 8 | 4 | 1 | 1 |
Chapter 8
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 bound | What it promises | Example |
|---|---|---|
| Worst case per step | every single step is cheap | a red-black tree search, O(log n) |
| Amortized | every sequence is cheap in total, no probability | doubling append, under 3 per step |
| Average case | cheap in expectation over random inputs or random choices | quicksort, 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:
c-hat equals two r minus one, over r minus one.
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.
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.
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.
Chapter 9
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.
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.
| Structure | Costly step | Amortized bound | Potential or charge |
|---|---|---|---|
| Doubling array | copy on full | O(1) per append | 2·num − cap |
| Hash table | rehash on grow | O(1) per insert, from resizing | same as a dynamic table |
| Two-stack queue | move A onto B | O(1) per operation | charge 3 per enqueue |
| Splay tree | a deep access | O(log n) | sum of log(subtree size) |
| Fibonacci heap | consolidate on extract-min | O(1) decrease-key | trees + 2 × marked nodes |
| Union-find | a long find path | O(α(n)), inverse Ackermann | based 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.
Chapter 10
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 number | Meaning |
|---|---|
| amortized cost ĉ | a per-step price whose sum bounds the actual total of every sequence |
| T(n) < 3n | n appends to a doubling array; 64 appends cost 127 |
| F(n) = 2n − (1s in n) | bit flips of n increments; under 2n |
| Σ ĉ ≥ Σ c | the accounting rule, after every step |
| ĉ = c + ΔΦ | the potential method; needs Φ(Dn) ≥ Φ(D0) |
| Φ = 2·num − cap | array potential; ĉ = 3 per append |
| Φ = number of 1s | counter potential; ĉ = 2 per increment |
| 1/4 | shrink 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 |
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
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).
Explain it back with Present or Teach, or go back to the bank and predict when "Grow by half" first runs out of coins.