Sub topic 12
Why append is amortized O(1)
This chapter assumes you know Big-O basics, and that you've seen the DynamicArray class with its size, capacity, and _resize method. Here we explain why a single append can cost O(n) while a long run of appends averages O(1) each.
Two kinds of append
Most appends are cheap. If size < capacity, the code writes one value and increments size. That is one step.
Some appends are expensive. If the block is full, _resize allocates a new block and copies every element. With n elements, that costs about n steps.
If you only look at the worst case, append is O(n). That is true for one call, but it is misleading for a sequence of calls. Amortized analysis averages the cost over a whole sequence of operations. It makes no assumption about input, and it is not an average over random cases.
Counting the copies
Take the doubling policy, starting at capacity 1. Resizes happen when the size is 1, 2, 4, 8, and so on. A resize at size k copies k elements.
| Append number | Size before | Resize? | Elements copied |
|---|---|---|---|
| 1 | 0 | no | 0 |
| 2 | 1 | yes, to 2 | 1 |
| 3 | 2 | yes, to 4 | 2 |
| 4 | 3 | no | 0 |
| 5 | 4 | yes, to 8 | 4 |
| 9 | 8 | yes, to 16 | 8 |
For n appends, the total copying is at most:
1 + 2 + 4 + ... + n/2 < n
Each term is half the one after it, so the whole sum is less than the last term doubled. Add the n plain writes, and the total work is under 2n. Dividing by n appends gives under 2 steps per append. That is a constant, so append is amortized O(1).
The accounting view
Another way to see it is to charge each append a fixed budget of 3 units. One unit pays for its own write. The other two are saved as credit. When a resize from k to 2k happens, the k elements added since the last resize each hold 2 credits. That gives 2k credits, which covers copying all k old elements plus the k new ones' share. The credit never runs out, so a constant charge per append is enough.
Why geometric growth matters
The argument depends on capacity growing by a multiplicative factor. If you grew by a fixed amount, such as capacity + 10, resizes would happen every 10 appends. Each would copy about n elements, so n appends would cost O(n²) in total, or O(n) per append.
def copies_for(n, grow):
capacity, size, copies = 1, 0, 0
for _ in range(n):
if size == capacity:
copies += size
capacity = grow(capacity)
size += 1
return copies
for n in (1_000, 10_000, 100_000):
print(n, copies_for(n, lambda c: 2 * c), copies_for(n, lambda c: c + 10))The doubling column stays below n. The fixed-increment column grows roughly with n²/20.
Exercise
Exercise
A dynamic array starts with capacity 1 and doubles when full. How many element copies happen in total across 16 appends? Is that more or less than 2 × 16?
Show answer
Resizes occur when the size is 1, 2, 4 and 8, copying 1 + 2 + 4 + 8 = 15 elements. That is fewer than 32, which matches the bound of under 2n.