Sub topic 2
How a dynamic array grows
This chapter assumes you know Big-O notation, how fixed-size arrays are allocated and indexed, and how to read short Python programs. It explains the mechanism that the later amortised proofs analyse.
The problem a dynamic array solves
A fixed-size array needs its length at allocation time, and it cannot be extended in place. The memory next to it may belong to something else. A program that collects an unknown number of items needs an array that appears to grow.
A dynamic array is a fixed-size array plus a bookkeeping rule for replacing it with a bigger one. Python's list, Java's ArrayList and C++'s std::vector all work this way. It tracks two numbers:
- size is how many elements the user has stored.
- capacity is how many slots the underlying fixed array has. Size never exceeds capacity.
The append rule
Appending follows two cases:
- If size is less than capacity, write the value into slot
sizeand increase size by one. This costs one write. - If size equals capacity, the array is full. Allocate a new array with a larger capacity, copy every element across, discard the old array, then do the write from case 1.
The copy in case 2 is the expensive step. It touches every stored element, so that append costs proportional to the current size.
Watching it happen
The next program doubles the capacity when the array is full. Each append returns the number of elements it copied.
class DynamicArray:
def __init__(self):
self._capacity = 1
self._size = 0
self._data = [None] * self._capacity
@property
def capacity(self):
return self._capacity
def append(self, value):
copied = 0
if self._size == self._capacity:
copied = self._resize(2 * self._capacity)
self._data[self._size] = value
self._size += 1
return copied
def _resize(self, new_capacity):
new_data = [None] * new_capacity
for i in range(self._size):
new_data[i] = self._data[i]
self._data = new_data
self._capacity = new_capacity
return self._size
arr = DynamicArray()
for k in range(1, 11):
copied = arr.append(k)
print(f"append {k:2d}: copied {copied}, capacity {arr.capacity}")The copy counts are 0, 1, 2, 0, 4, 0, 0, 0, 8, 0 for appends 1 to 10. Capacity goes 1, 2, 4, 8, 16.
| Append number | Elements copied | Capacity afterwards |
|---|---|---|
| 1 | 0 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 4 |
| 5 | 4 | 8 |
| 9 | 8 | 16 |
Most appends copy nothing. A resize happens only when the size is a power of two, and each one copies twice as much as the one before. That second fact matters, because it is what keeps the total copying small.
Worst case versus the whole run
Looking at one call, the worst-case cost of append is O(n). The call that triggers the resize at size n copies n elements, so a single append can be slow.
Now look at the whole run. The expensive calls are rare, and the gaps between them double. Ten appends cost 15 copies in total. The next chapter turns this observation into a proof that the average cost per append stays constant, for any sequence of appends.
Two details of the implementation are worth fixing in mind now:
- Reading or writing
data[i]is O(1) throughout. Resizing only affects append. - Resizing allocates a new array. Any code holding a reference to the old internal storage, such as a pointer in C++ or an iterator, becomes invalid after a resize.
Common mistakes
- Confusing size with capacity.
len(arr)reports size. Capacity is internal and usually hidden. - Calling append "O(n)" without qualification. That is true for one worst-case call, but misleading for a sequence of calls.
- Forgetting the new element. The resize makes room, and the write still has to happen afterwards.
Exercise
Start with the doubling DynamicArray above (capacity 1, size 0) and perform 100 appends. What is the final capacity, and how many element copies did the resizes cause in total?
Show answer
Resizes happen when an append finds the array full at sizes 1, 2, 4, 8, 16, 32 and 64, copying that many elements each time. The total is 1 + 2 + 4 + 8 + 16 + 32 + 64 = 127 copies. The 65th append raises capacity from 64 to 128, so the final capacity is 128.