Sub topic 6
How Dynamic Arrays Grow and Why Appends Are Amortized O(1)
This chapter assumes you know basic Big-O notation, understand references, and have seen how an array stores its elements in one contiguous block of memory. It explains what happens when that block fills up, and why appending is still cheap on average.
The problem: a fixed block fills up
A plain array has a fixed capacity. If you reserved room for 4 elements and want a fifth, you cannot extend the block in place, because the memory right after it may belong to something else.
A dynamic array hides this limit. It keeps two numbers:
- size: how many elements you have stored.
- capacity: how many slots the current block can hold.
When size == capacity and you append, the array allocates a larger block, copies every element into it, and releases the old block. That one append costs O(n). Every other append just writes into a free slot and costs O(1).
A working implementation
This class doubles the capacity whenever the buffer is full.
class DynamicArray:
def __init__(self):
self._capacity = 1
self._size = 0
self._items = [None] * self._capacity
def append(self, value):
if self._size == self._capacity:
self._resize(2 * self._capacity)
self._items[self._size] = value
self._size += 1
def _resize(self, new_capacity):
new_items = [None] * new_capacity
for i in range(self._size):
new_items[i] = self._items[i]
self._items = new_items
self._capacity = new_capacity
def __getitem__(self, index):
if not 0 <= index < self._size:
raise IndexError(index)
return self._items[index]
def __len__(self):
return self._sizeTrace eight appends. The capacity starts at 1 and the resizes happen when the size is 1, 2 and 4:
| Append # | Size before | Capacity before | Resize? | Elements copied |
|---|---|---|---|---|
| 1 | 0 | 1 | No | 0 |
| 2 | 1 | 1 | Yes, to 2 | 1 |
| 3 | 2 | 2 | Yes, to 4 | 2 |
| 4 | 3 | 4 | No | 0 |
| 5 | 4 | 4 | Yes, to 8 | 4 |
| 6 to 8 | 5 to 7 | 8 | No | 0 |
Why the average is O(1)
Amortized cost means the total cost of a sequence of operations divided by the number of operations. It is not a probability and it is not an average over random inputs. It is a guarantee about the worst-case total.
Suppose you append n elements, starting from capacity 1 and doubling. The resizes copy 1, 2, 4, 8, and so on, up to at most n/2... in general less than n elements. That sum is a geometric series:
1 + 2 + 4 + ... + 2^k < 2^(k+1) ≤ 2n
So the copying across all n appends is at most about 2n element moves. Add the n plain writes and the total is at most about 3n. Dividing by n gives a constant: each append costs O(1) amortized.
Why doubling matters
The growth must be multiplicative. If you grow by a fixed amount, such as 10 slots each time, resizes happen every 10 appends. Each one copies a number of elements that keeps growing, so the total work is quadratic and the amortized cost per append becomes O(n).
Real implementations often use a factor below 2, for example about 1.125 in CPython's list and 1.5 in some C++ standard library implementations. A smaller factor wastes less unused capacity and lets freed blocks be reused. It also copies more often. The amortized cost stays O(1) for any constant factor greater than 1. Only the constant changes.
Common errors
- Treating amortized as worst case. A single append can still take O(n). In latency-sensitive code, such as a real-time loop, one long copy can cause a visible pause. If you know the final size, reserve capacity up front.
- Assuming shrinking is free. Repeatedly growing and shrinking at the same boundary can force a resize on every operation. Implementations usually shrink only when the array is well under half full.
- Applying the guarantee to inserts in the middle. Amortization covers appends at the end. Inserting at the front or middle still shifts later elements and costs O(n).
- Forgetting that resizing moves data. After a resize, the elements live at new addresses, so any reference to an old slot is stale. The reference stability chapter covers this in detail.
Exercise
A dynamic array starts at capacity 1 and doubles when full. You append 16 elements one at a time. How many element copies do the resizes perform in total, and what is the average number of copies per append?
Show answer
Resizes happen when the size is 1, 2, 4 and 8, copying 1 + 2 + 4 + 8 = 15 elements. The average is 15 / 16, which is under 1 copy per append. This stays below 2 copies per append for any n, which is why appends are amortized O(1).
Exercise
A developer changes the growth rule from "double the capacity" to "add 100 slots". Is append still amortized O(1)? Explain.
Show answer
No. Resizes occur every 100 appends, and each copies all current elements. For n appends, the copy total is roughly 100 + 200 + ... + n, which is about n^2 / 200. Dividing by n gives O(n) per append. Only multiplicative growth keeps the total copying proportional to n.