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 builds the data structure that the rest of the tutorial analyses. Here you learn what a dynamic array stores, how an append works, when it resizes, and what one append can cost.
Why a fixed-size array is not enough
A fixed-size array is a block of contiguous memory with a length chosen at allocation time. Reading or writing position i is O(1) because the address is start + i * element_size. The block cannot grow in place. The memory next to it may already belong to something else.
Many programs do not know in advance how many items they will store. You might read lines from a file, collect search results, or accumulate events. Allocating a huge array "just in case" wastes memory. Allocating a small one fails when it fills up.
A dynamic array solves this by hiding a fixed-size array behind an interface that appears to grow. Python's list, Java's ArrayList, C++'s std::vector, Go's slices, and Rust's Vec are all dynamic arrays.
The three pieces of state
A dynamic array keeps three things:
- Backing array: a fixed-size array that holds the elements.
- Capacity: the length of the backing array, meaning how many elements fit before it must be replaced.
- Size: how many slots currently hold real elements. It is also the index where the next append goes.
The invariant is 0 <= size <= capacity. Slots at indexes size and above are spare room. They hold placeholders that callers must never see.
Capacity and size are different numbers. Confusing them is the most common mistake when people first implement this structure. Indexing is checked against size, not capacity. Reading index 5 of an array with size 3 and capacity 8 must raise an error, even though the backing array has a slot there.
The append algorithm
Appending follows two cases:
- If
size < capacity, write the value at indexsizeand increasesizeby one. This is a single write. - If
size == capacity, allocate a new backing array with a larger capacity. Copy allsizeelements into it and discard the old array. Then do case 1.
The only question left is how much larger the new capacity should be. A later chapter compares strategies. This chapter uses the classic rule: double the capacity.
A working implementation
The class below counts every element copy caused by resizing. The copies counter is not part of a real dynamic array. It lets you measure the cost of resizing.
class DynamicArray:
def __init__(self):
self._capacity = 1
self._size = 0
self._data = [None] * self._capacity
self.copies = 0 # element copies caused by resizing
@property
def capacity(self):
return self._capacity
def __len__(self):
return self._size
def __getitem__(self, index):
if not 0 <= index < self._size:
raise IndexError(f"index {index} out of range for size {self._size}")
return self._data[index]
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
arr = DynamicArray()
for n in range(1, 18):
before = arr.capacity
arr.append(n * 10)
if arr.capacity != before:
print(f"append #{n}: capacity {before} -> {arr.capacity}, "
f"copies so far {arr.copies}")
print("size:", len(arr), "capacity:", arr.capacity)Running it prints:
append #2: capacity 1 -> 2, copies so far 1
append #3: capacity 2 -> 4, copies so far 3
append #5: capacity 4 -> 8, copies so far 7
append #9: capacity 8 -> 16, copies so far 15
append #17: capacity 16 -> 32, copies so far 31
size: 17 capacity: 32The [None] * new_capacity line stands in for allocating a raw block. In a language like C, you would call malloc or realloc. Python's own list does this work in C, so the class above only imitates it.
Reading the trace
Resizes happen at appends 2, 3, 5, 9, and 17. Each one falls just after the size reaches a power of two. The array was full, so the next append triggered a copy of exactly that many elements.
| Append number | Size before | Capacity before | Elements copied | Capacity after |
|---|---|---|---|---|
| 1 | 0 | 1 | 0 | 1 |
| 2 | 1 | 1 | 1 | 2 |
| 3 | 2 | 2 | 2 | 4 |
| 4 | 3 | 4 | 0 | 4 |
| 5 | 4 | 4 | 4 | 8 |
| 9 | 8 | 8 | 8 | 16 |
| 17 | 16 | 16 | 16 | 32 |
Appends that are not shown (6, 7, 8, 10 to 16) copy nothing. The expensive appends become rarer as the array grows, and each one copies a number of elements equal to its own capacity. This pattern is what makes the amortised analysis work. The aggregate method chapter turns the observation into a proof.
What a single append costs
Take "cost" to mean the number of element writes and copies. Then:
- An append with spare room costs 1.
- An append that triggers a resize costs
size + 1:sizecopies plus the new write.
So the worst case for one append is Θ(n), where n is the current size. A function that promises O(1) per append in the worst case cannot use this design. The best case is Θ(1), and most appends hit it.
Neither number describes the experience of running many appends in a row. The worst case is too pessimistic, because it cannot happen twice in a row. After a resize to capacity 2c, at least c - 1 cheap appends must follow before the next resize. The best case is too optimistic, because it hides the copying. Amortised analysis gives a bound on total cost over a sequence that is honest about both.
Details that affect correctness
Capacity zero
If an empty array starts with capacity 0, then 2 * 0 is still 0, and the array never grows. The append then writes past the end of the backing array. Start at capacity 1, or compute the new capacity as max(1, 2 * capacity). Real libraries often start at 0 and handle the first allocation as a special case.
References to elements stay valid, references to the array do not
In languages with pointers, a resize moves the elements to new memory. A pointer or reference into the old backing array then dangles. In C++, appending to a std::vector can invalidate every iterator and pointer into it. Python hides this because a list holds references to objects, and those objects do not move. A stored lst[0] is the same object before and after the resize.
Memory during the resize
At the moment of copying, the old and new arrays both exist. With doubling, a full array of n elements briefly sits next to a new block of 2n slots, so peak usage is about 3n slots. Right after a resize, up to half the capacity is spare. Dynamic arrays trade memory for time. The spare room is what makes appends cheap.
Capacity is not a promise
Library growth rules differ and are implementation details. Java's ArrayList grows by about 1.5 times. Many C++ standard libraries use 2 times, and some use 1.5. CPython's list over-allocates by a smaller proportion, roughly an eighth of the size plus a constant. You can see it with sys.getsizeof:
import sys
items = []
last = sys.getsizeof(items)
print(0, last)
for i in range(64):
items.append(i)
current = sys.getsizeof(items)
if current != last:
print(len(items), current)
last = currentThe exact byte counts depend on the Python version and platform. Every version shows the same shape: the reported size stays flat for several appends, then jumps. Each jump is a resize. The jumps spread further apart as the list grows, which shows that growth is proportional to the current size. The next chapters explain why proportional growth matters and why a small proportion still works.
Common mistakes
- Checking bounds against capacity. Reads must be limited to
size, or callers will see placeholder values. - Growing by a constant. Adding a fixed number of slots on each resize looks harmless, but it makes n appends cost Θ(n²) in total. A later chapter shows this with measurements.
- Forgetting that resize invalidates references. In low-level languages, hold indexes, not pointers, across appends.
- Assuming each append is O(1) in the strict sense. Each append is O(1) amortised. A single append can still take O(n).
- Treating the spare capacity as free. If you build an array of a million elements and keep it for a long time, capacity may exceed size by up to a factor of two. Some libraries offer a shrink-to-fit call for this reason.
Summary
A dynamic array keeps a fixed-size backing array, a capacity, and a size. It appends in O(1) while there is spare room. When the array is full, it allocates a larger backing array, copies everything, and then appends. A single append can cost Θ(n), yet resizes become rarer as the array grows. The next chapter totals the cost of n appends with the aggregate method.
Exercise
Starting from an empty DynamicArray with capacity 1, which uses the doubling rule above, you append 20 elements. At which append numbers do resizes occur, how many element copies happen in total, and what is the final capacity?
Show answer
Resizes occur at appends 2, 3, 5, 9, and 17. They copy 1, 2, 4, 8, and 16 elements, so the total is 31 copies. The final capacity is 32, because the 17th append doubles the capacity from 16 to 32 and 20 elements fit in 32 slots.
Exercise
Suppose the constructor sets capacity to 0 and the resize rule is new_capacity = 2 * capacity. What goes wrong on the first append, and what is a minimal fix?
Show answer
The array is full, since size 0 equals capacity 0, so append calls resize. Resize computes 2 0 = 0 and allocates another empty array. The write at index 0 then falls outside the backing array, which raises an IndexError in Python or corrupts memory in a language without bounds checks. A minimal fix is new_capacity = max(1, 2 capacity), or starting with capacity 1.