What one append costs
A dynamic table is an array that can grow. append(x) writes x into the next free slot. When every slot is full, it makes a new array twice as big and copies each item across. Cost rule: each item written into a slot costs 1.
Append 1 makes one slot and writes: cost 1. Append 2 finds it full, doubles to 2 slots and copies 1 item: cost 2. Append 3 doubles to 4 slots and copies 2: cost 3.
Append 4 has a free slot: cost 1. Append 5 finds all 4 slots full, doubles to 8 and copies all 4 items: cost 5. A single append can cost as much as n, so its worst case is O(n).
Appends 6, 7 and 8 cost 1 each. Eight appends cost 15 in total, not eight worst cases of 8. The copies add up to 1 + 2 + 4 = 7, less than n. Aggregate method: 15 ÷ 8 is under 3 per append.
The accounting method
Accounting method: charge every append 3 coins, whatever it really costs. Each item written spends 1 coin; the rest waits in the bank. Replay from empty: after appends 1, 2 and 3 the bank holds 2, 3, then 3 coins.
Append 4 is cheap: the bank grows to 5. Append 5 brings 3 more coins, then spends 4 on copies and 1 on its write: 3 left. The bank never goes below zero, so 3 coins cover every cost.
Appends 6, 7 and 8 each spend 1 coin and save 2: the bank climbs to 9. Cheap appends prepay the next doubling. So 3 coins per append is the amortised cost: O(1), although one append can cost O(n).
The potential method
Potential method: no coins to track, just a score for the table, Φ = 2n − cap. Here n = 8 and cap = 8, so Φ = 8: two units for each item past the half-way mark. Φ never drops below 0.
Amortised cost = actual cost + change in Φ. Append 9 copies 8 items and writes 1: actual 9. With 16 slots, Φ falls from 8 to 2. Amortised: 9 + (2 − 8) = 3. A cheap append: 1 + 2 = 3.
Both methods give at most 3 per append, so any n appends from empty cost at most 3n: amortised O(1). Here 9 appends cost 24, under 27. Amortised is a promise about every sequence, not an average over lucky inputs.
What happens
;; step 1/10 · table cost model: 1 unit per item written into a slot 1 def append(t, x): 2 if t.n == t.cap: 3 t.cap = max(1, 2 * t.cap) 4 new = [None] * t.cap 5 for i in range(t.n): 6 new[i] = t.a[i] 1 per run 7 t.a = new 8 t.a[t.n] = x 1 per run 9 t.n += 1 n = items stored, cap = slots in the array the table starts empty: n = 0, cap = 0
Cost model: 1 unit for each item written into a slot, either a copy or the new item. Making the empty new array is not counted; counting it changes the constants, not the O(1) result. The very first append costs 1 and is charged 3, so the bank always holds one coin more than Φ. Its amortised cost under the potential method is 2: 1 + (1 − 0).