Sub topic 3
Aggregate method: totalling the cost of n appends
This chapter assumes you know Big-O notation, how fixed-size arrays are allocated and indexed, and how to read short Python programs. It builds on the previous chapter's description of a dynamic array, which grows by allocating a bigger array and copying the old elements into it.
What the aggregate method does
The aggregate method is the simplest way to do amortised analysis. It has three steps:
- Choose a sequence of n operations. The sequence must be arbitrary, because you may not assume anything about the input.
- Find an upper bound T(n) on the total cost of the whole sequence.
- Divide by n. The result, T(n) / n, is the amortised cost per operation.
The method never asks what a single operation costs. It only asks what all of them cost together. Every operation in the sequence gets the same amortised cost, whether it was cheap or expensive.
A bound on the total that holds for every sequence of n operations is a worst-case guarantee on the total. That is why an amortised bound differs from an average-case bound. No probability is involved.
The cost model
We analyse appends to a doubling dynamic array. The array starts with capacity 1. When an append finds the array full, it allocates a new array of twice the capacity and copies every element across. Then it writes the new element.
We count two kinds of unit-cost work:
- Writing one element into a slot costs 1.
- Copying one existing element during a resize costs 1.
Allocating the new array also takes time, because the runtime usually has to initialise the slots. That cost is proportional to the new capacity. It is bounded by the same geometric sum we compute below, so it only changes the constant. We ignore it to keep the arithmetic clean.
The cost of one append is therefore:
- 1, if there is room.
- 1 + s, if the array is full and holds s elements. The s is the copying work.
Watching the costs
Run this program to see the cost of each append for n = 10.
def append_costs(n):
"""Cost of each of n appends: 1 per write plus 1 per element copied."""
size, capacity = 0, 1
costs = []
for _ in range(n):
cost = 1
if size == capacity:
cost += size # copy every element into the new array
capacity *= 2
size += 1
costs.append(cost)
return costs
costs = append_costs(10)
print(costs)
print(sum(costs), sum(costs) / 10)The output is:
[1, 2, 3, 1, 5, 1, 1, 1, 9, 1]
25 2.5The expensive appends are numbers 2, 3, 5 and 9. They happen when the size is 1, 2, 4 and 8, which are the powers of two. Between them are runs of cheap appends, and the runs get longer as the array grows.
The worst single append in a sequence of n costs about n. If you only quoted the worst case per operation, you would say appends cost O(n). The aggregate method shows that this is far too pessimistic as a statement about the whole sequence.
The proof
Let n ≥ 1 be the number of appends, starting from an empty array of capacity 1.
Writes. Every append writes exactly one element, so the writes cost n in total.
Copies. A resize happens when an append arrives and size equals capacity. Capacity is always a power of two, so a resize occurs when the size is 2^j for some j ≥ 0. At that moment the resize copies 2^j elements.
The append that triggers the resize at size 2^j is append number 2^j + 1. That append must be part of the sequence, so 2^j + 1 ≤ n, which gives 2^j < n.
Let k be the largest j with 2^j < n. The total copying is the geometric sum
1 + 2 + 4 + ... + 2^k = 2^(k+1) - 1Since 2^k ≤ n − 1, we have 2^(k+1) ≤ 2(n − 1), so the copies total less than 2n. If n = 1 there are no resizes and no copies.
Total.
T(n) = n + (copies) < n + 2n = 3nSo the amortised cost per append is T(n) / n < 3, which is O(1).
The key fact is that the sum of a geometric series is dominated by its last term. The last resize copies at most n − 1 elements. Everything before it copies at most that many again, because 1 + 2 + ... + 2^(k−1) < 2^k.
Checking the bound in code
You can confirm the algebra by counting copies in a real implementation. This is the dynamic array from the plan for this tutorial, with a counter added.
class DynamicArray:
def __init__(self):
self._capacity = 1
self._size = 0
self._data = [None] * self._capacity
self.copies = 0 # element copies caused by resizing
def append(self, value):
if self._size == self._capacity:
self._resize(2 * self._capacity)
self._data[self._size] = value
self._size += 1
def _resize(self, new_capacity):
new_data = [None] * new_capacity
for i in range(self._size):
new_data[i] = self._data[i]
self.copies += 1
self._data = new_data
self._capacity = new_capacity
for n in (10, 100, 1000, 10000):
arr = DynamicArray()
for i in range(n):
arr.append(i)
assert arr.copies < 2 * n
print(n, arr.copies, arr.copies / n)The output is:
10 15 1.5
100 127 1.27
1000 1023 1.023
10000 16383 1.6383The ratio of copies to n is not constant. It depends on how far n is past the last power of two. The ratio is near 1 just after a resize has been paid for, as at n = 1000. It is closer to 2 when n is just above a power of two, as at n = 10000. This is why the proof is an inequality. The total is always below 3n, but it is not exactly 3n.
Edge cases and common mistakes
- Off-by-one in the resize count. The resize that copies 2^j elements is triggered by append 2^j + 1, not append 2^j. Getting this wrong makes the last term of the sum look like it belongs to the sequence when it may not.
- Treating n as a power of two. The proof above needs no such assumption. The bound holds for every n, as the n = 10 and n = 10000 runs show.
- Quoting the average of the expensive appends. The bound is over the whole sequence, including the cheap appends. You cannot apply T(n) / n to a subsequence. A short run that contains a resize can easily average more than 3.
- Confusing amortised with expected. Nothing here is random. The bound would hold if an adversary chose the values appended. The word "expected" is a different guarantee, which a later chapter covers.
- Forgetting that the bound is for a sequence starting from empty. If the array already has a large size and an unlucky capacity, a short sequence can begin with a resize. The total is still bounded in terms of the starting size plus n. The aggregate method works for any starting state, but you must account for the elements already present.
Other growth factors
Doubling is not special. Suppose the capacity is multiplied by a constant g > 1 on each resize, with g large enough that capacity actually increases. The resize sizes then form a geometric series with ratio g. The copies are bounded by
copies ≤ n / (g − 1) · g (roughly)For g = 2 this recovers the bound of about 2n. For g = 1.5 the copies reach about 3n, so the amortised cost is about 4 per append. For g = 3 the copies are about 1.5n.
A larger g lowers the copying per append but wastes more memory, since up to (g − 1)/g of the array can sit unused. The next chapters cover this trade-off, and why additive growth, such as adding 16 slots each time, breaks the O(1) bound.
Where the aggregate method stops being enough
The aggregate method has two limits.
- It gives every operation the same amortised cost. If the sequence mixes different operations, such as appends and removals, you often want to say that each type has its own cost. The method only reports one average over the whole sequence.
- It needs a clean closed form for the total. For appends the geometric series is easy. When an array can both grow and shrink, the sequence of resizes depends on the order of operations, and totalling them directly is much harder.
The accounting method and the potential method address these problems. They assign a charge to each operation type and prove the bound with an invariant instead of a global sum. Both are covered in the following chapters, and both give the same answer for appends as the aggregate method does here.
Exercises
Exercise
A doubling array starts with capacity 1. How many element copies happen in total across 20 appends, and what is the aggregate amortised cost per append, counting 1 per write and 1 per copy?
Show answer
Resizes happen when the size is 1, 2, 4, 8 and 16 (append 17 triggers the last one). The copies are 1 + 2 + 4 + 8 + 16 = 31. Writes cost 20, so the total is 51 and the amortised cost is 51 / 20 = 2.55, which is below 3.
Exercise
Suppose the array grows by tripling its capacity instead of doubling it, starting at capacity 1. Show that the total number of copies over n appends is less than 1.5n.
Show answer
Resizes occur at sizes 1, 3, 9, ..., 3^k, where 3^k < n. The copies total (3^(k+1) − 1) / 2. Since 3^k ≤ n − 1, we get 3^(k+1) ≤ 3(n − 1), so the copies are at most (3(n − 1) − 1) / 2 < 1.5n. The total cost is then below 2.5n, so the amortised cost per append is below 2.5.
Exercise
A classmate says: "Appends 1 to 8 cost 1, 2, 3, 1, 5, 1, 1, 1, so the amortised cost is 15 / 8, which is less than 2. The aggregate proof of 3 is too loose." What is wrong with this argument, and what does it show about the bound?
Show answer
Those eight appends are only a prefix of the sequence, and they stop just before the expensive append 9, which costs 9. The aggregate bound must hold for every n, and for n = 9 the total is 24, which is 2.67 per append. Choosing a convenient n does not show that the bound is loose. It shows that the true average varies with n, and the proof bounds the worst case over all n.