Sub topic 12
Amortized analysis: why dynamic array appends are cheap
This chapter assumes you can read Big O for loops and recursion, and that you know the difference between worst-case and average-case analysis. It also assumes you know what a dynamic array is, such as a Python list or a Java ArrayList. The question here is how an operation that sometimes costs O(n) can still be called O(1).
The puzzle
A dynamic array keeps its elements in a fixed-size block of memory called the capacity. Appending is cheap while there is spare room: write the element and increase the size. When the block is full, the array must allocate a bigger block and copy every existing element into it. That single append costs O(n).
Worst-case analysis says "append is O(n)". That is true for one call, but it misleads you about a loop of n appends. Nearly all of those calls are cheap, and the expensive ones are rare. Amortized analysis bounds the total cost of a sequence of operations and divides by the number of operations.
Amortized cost is not average-case cost
The two ideas are easy to confuse.
| Row | Average-case | Amortized |
|---|---|---|
| Averages over | A probability distribution of inputs | A sequence of operations on one structure |
| Needs assumptions about input | Yes, such as random order | No |
| Guarantee | Expected cost, which a bad input can break | Total cost of any sequence of m operations is at most m times the amortized cost |
| Example | Quicksort's O(n log n) on random input | Dynamic array append is O(1) amortized |
An amortized bound is a worst-case guarantee over a whole sequence. No adversary can build a sequence of n appends that costs more than O(n) in total. Any single append may still cost O(n).
Aggregate analysis for doubling
The simplest method is the aggregate method: bound the total cost of n operations, then divide by n.
Suppose the capacity starts at 1 and doubles whenever the array is full. Resizes happen when the size is 1, 2, 4, 8, and so on. A resize at size s copies s elements. For n appends, the total copy work is at most:
1 + 2 + 4 + ... + 2^k, where 2^k < n
This geometric series sums to 2^(k+1) − 1. Since 2^k < n, that is less than 2n. Each append also does one unit of work to write its element. So the total is under 3n, and the cost per append is O(1) amortized.
The simulation below counts the copies.
def count_copies(appends):
capacity, size, copies = 1, 0, 0
for _ in range(appends):
if size == capacity:
copies += size # resize: copy every existing element
capacity *= 2
size += 1
return copies
for n in (10, 1000, 100000):
print(n, count_copies(n)) # total copies stay below 2 * nOutput:
10 15
1000 1023
100000 131071The copies stay under 2n. The ratio of copies to n does not grow as n grows, and that is what O(1) amortized means.
The accounting method
The accounting method gives each operation a fixed charge, which is its amortized cost. Cheap operations are charged more than they cost, and the surplus is stored as credit. Expensive operations spend that credit.
For doubling, charge each append 3 units:
- One unit pays for writing the new element.
- One unit is saved on that element for its own future copy.
- One unit is saved on an older element, for the copy of an element that has no credit left.
Suppose the array has just resized to capacity 2m with m elements. The next m appends each deposit 2 units of credit, giving 2m units by the time the array is full again. The next resize copies 2m elements, and the stored credit covers it exactly. The balance never goes negative, so 3 units per append is a valid amortized cost.
The potential method
The potential method turns the same idea into a formula. You define a potential function Φ that measures stored work, then write:
amortized cost = actual cost + Φ(after) − Φ(before)
For a dynamic array a standard choice is Φ = 2 · size − capacity. Right after a doubling, size is half of capacity, so Φ is 0. Just before a resize, size equals capacity, so Φ is capacity. A cheap append raises Φ by 2, so its amortized cost is 1 + 2 = 3. A resize append has actual cost size + 1, and Φ drops by about size, so its amortized cost is again a constant. The sum of amortized costs is an upper bound on the sum of actual costs, as long as Φ never falls below its starting value.
The three methods give the same bound. Aggregate is easiest for a single operation type. Accounting and potential handle structures with several operation types.
Why the growth factor matters
Doubling works because capacity grows proportionally. Growing by a fixed amount fails. This code compares the two policies.
def total_copies(appends, grow):
capacity, size, copies = 1, 0, 0
for _ in range(appends):
if size == capacity:
copies += size
capacity = grow(capacity)
size += 1
return copies
for n in (1000, 100000):
doubling = total_copies(n, lambda c: c * 2)
plus_ten = total_copies(n, lambda c: c + 10)
print(n, doubling, plus_ten)Output:
1000 1023 49600
100000 131071 499960000With +10 growth, the number of resizes is proportional to n, and each copies O(n) elements. The total is O(n²), so the amortized cost per append is O(n). Multiplying n by 100 multiplied the doubling cost by about 128 but the fixed-increment cost by about 10,000.
Any constant factor greater than 1 gives O(1) amortized appends. The factor trades speed against memory:
- Doubling wastes up to half the allocated space and copies least often.
- A factor near 1.5 wastes less and reuses freed memory more easily, but copies more often.
- CPython's list over-allocates by roughly 12.5% plus a small constant, so it resizes more often than a doubling array but wastes less memory. The amortized cost is still O(1).
The exact constant in the amortized bound depends on the factor. For growth factor g, the total copies are about n/(g − 1).
Edge cases and failure modes
Shrinking. If you halve the capacity when the array becomes half empty, an adversary can alternate append and remove at the boundary. Each call then triggers a resize, and the cost is O(n) per operation. The usual fix is to shrink only when the array is a quarter full, and to shrink to half the capacity. After any resize the array is then about half full, so at least n/4 cheap operations pass before the next one.
Latency. An amortized bound says nothing about a single call. One append can take O(n) time, which matters in real-time systems, interactive code, and network servers with latency targets. Some systems pre-allocate capacity, resize incrementally in the background, or use structures with worst-case O(1) operations.
Persistent use. Amortization assumes the expensive state is paid for once. If you can keep an old version of the structure and re-run operations on it, as with persistent or immutable data structures, an adversary can repeat the expensive operation from the same saved state. The amortized bound then no longer holds.
Other structures. The same technique applies elsewhere. Hash table insertion is O(1) amortized because of the same doubling argument on rehashing. A queue built from two stacks has O(1) amortized dequeue. A binary counter's increment is O(1) amortized, even though one increment can flip many bits.
Summary of the technique
- Amortized analysis bounds the total cost of any sequence of operations, then divides by the count.
- It needs no probability assumptions, unlike average-case analysis.
- Aggregate, accounting, and potential methods all prove the same bound in different ways.
- Geometric growth makes the resize costs a series that sums to O(n). Fixed-increment growth does not.
- Shrink policies, latency limits, and persistence can all break the intuition.
Exercise
A dynamic array grows by tripling its capacity when full, starting from capacity 1. Use the aggregate method to bound the total copies for n appends, and state the amortized cost per append.
Show answer
Resizes occur at sizes 1, 3, 9, ..., 3^k, where 3^k < n. The copy work is the geometric series 1 + 3 + 9 + ... + 3^k = (3^(k+1) − 1)/2, which is less than 3^(k+1)/2. Since 3^k < n, that is less than 3n/2. The total copy work is under 1.5n, matching the n/(g − 1) estimate with g = 3. Adding one write per append gives a total of O(n), so the amortized cost per append is O(1).
Exercise
A dynamic array doubles when full and halves its capacity as soon as it is less than half full. Describe a sequence of operations that makes each operation cost O(n), and give a shrink policy that fixes it.
Show answer
Fill the array to exactly capacity c and append once so it doubles to 2c with c + 1 elements. Then alternate remove and append. The removal drops the size to c, which is exactly half of 2c, and a further removal at that point drops below half and triggers a halving. Repeating the pattern around the boundary causes a resize on nearly every call, and each resize copies about c elements, so each operation costs O(n). The fix is to halve the capacity only when the array is a quarter full. After the resize it is half full, so at least n/4 operations must occur before the next resize, which restores O(1) amortized cost.
Exercise
Why is "append is O(1) amortized" a stronger statement than "append is O(1) on average"?
Show answer
An average-case bound depends on assumptions about the input distribution and can fail on an unlucky or adversarial input. An amortized bound holds for every sequence of operations, so n appends always cost O(n) in total, whatever the sequence is.