Full answer
Problem
Implement an append-only array that grows automatically. Show that n appends do O(n) total work, so each append costs O(1) amortised.
Example: appending 1 to 5,000 into an array that starts with capacity 1.
Constraints: no built-in growth; you manage capacity and copying yourself.
Brute force: grow by one slot
Grow by one slot on every append (or by a fixed number like 10). Each resize copies all current items. Total copies: 1 + 2 + ... + (n - 1) = n(n - 1)/2, which is O(n^2) for n appends, O(n) per append on average.
Optimal approach: double the capacity
Keep a capacity. When size reaches capacity, allocate an array of twice the size and copy. Most appends just write into a free slot, O(1).
Why it works
Resizes happen at sizes 1, 2, 4, 8, ..., up to n. The total number of copies is 1 + 2 + 4 + ... + 2^k where 2^k < n, and a geometric series sums to less than twice its last term, so fewer than 2n copies in total. Add n writes, and n appends cost under 3n steps: O(n) total, O(1) amortised.
The banker's view says the same thing: charge each append 3 units. One pays for its own write, two are saved. When a resize copies the array, the saved units from items added since the last resize pay for it.
Amortised is not average over random inputs. It is a guarantee over any sequence of operations. A single append can still take O(n); real-time systems that cannot tolerate one slow operation need incremental resizing.
CPython's list uses a similar idea with a smaller growth factor (about 1.125 plus a constant), which still gives amortised O(1).
Complexity
append: O(1) amortised, O(n) worst case for one call. Indexing O(1). Space O(n), with at most 2x unused capacity.
Code
class DynamicArray:
"""Append-only array that doubles its capacity when full."""
def __init__(self):
self._capacity = 1
self._size = 0
self._data = [None] * self._capacity
self.copies = 0 # total elements copied during resizes
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
def __getitem__(self, i):
if not 0 <= i < self._size:
raise IndexError("index out of range")
return self._data[i]
def __len__(self):
return self._size
if __name__ == "__main__":
arr = DynamicArray()
for n in range(1, 5001):
arr.append(n)
assert arr.copies < 2 * n # amortised O(1): total copies stay below 2n
assert len(arr) == 5000 and arr[0] == 1 and arr[4999] == 5000
try:
arr[5000]
raise AssertionError("expected IndexError")
except IndexError:
pass
print("copies for 5000 appends:", arr.copies)
print("all tests passed")Save as a02_dynamic_array.py and run python3 a02_dynamic_array.py. It prints all tests passed (Python 3.13.5).
The run above printed copies for 5000 appends: 8191, which is 1 + 2 + ... + 4096 = 8191, below 2 x 5000.
Edge cases
First append into capacity 1. Indexing past the end must raise IndexError. Shrinking: if you also support pop, shrink only when the array is a quarter full (not half), otherwise alternating push and pop at the boundary causes repeated O(n) resizes.
Pattern
Amortised analysis with a geometric growth factor. The same reasoning explains hash table rehashing and the two-stack queue.
class DynamicArray:
"""Append-only array that doubles its capacity when full."""
def __init__(self):
self._capacity = 1
self._size = 0
self._data = [None] * self._capacity
self.copies = 0 # total elements copied during resizes
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
def __getitem__(self, i):
if not 0 <= i < self._size:
raise IndexError("index out of range")
return self._data[i]
def __len__(self):
return self._size
if __name__ == "__main__":
arr = DynamicArray()
for n in range(1, 5001):
arr.append(n)
assert arr.copies < 2 * n # amortised O(1): total copies stay below 2n
assert len(arr) == 5000 and arr[0] == 1 and arr[4999] == 5000
try:
arr[5000]
raise AssertionError("expected IndexError")
except IndexError:
pass
print("copies for 5000 appends:", arr.copies)
print("all tests passed")The test asserts that total copies stay below 2n after every append, which checks the amortised bound directly.
Complexity
Time: append O(1) amortised, O(n) worst case for a single call; get O(1). Space: O(n), with up to 2x spare capacity. Growing by a constant amount instead of a factor makes the total O(n^2).
By level
Fresher: Explains that the array doubles when full and that copying is rare, so most appends are cheap. Can state that total work for n appends is about 3n. Should know that a Python list is a dynamic array.
Mid: Proves the bound with the geometric series or the banker's method and contrasts constant growth. Explains why shrinking happens at one quarter. Can compute the exact copy count for a given number of appends.
Senior: Discusses worst-case latency concerns and incremental resizing, memory overhead of the growth factor, and how the same analysis applies to hash table rehashing. Can explain why appending at the front of a Python list is still O(n).
Key points
- Doubling makes resizes rare
- Total copies over n appends are below 2n
- Amortised is a worst-case guarantee over a sequence, not a probability average
- Fixed-size growth gives O(n^2) total
- Shrink at one quarter full to avoid thrashing
Common mistakes
- Calling amortised O(1) the same as worst-case O(1)
- Confusing amortised with average case over random inputs
- Growing by a constant amount
- Shrinking at half full and causing resize thrashing
Follow-ups
- What growth factor does CPython's list use, and does it matter?
- How would you make appends O(1) worst case?
- Where else does amortised analysis appear in hash tables?
Tips
- Write the geometric series and its bound
- Contrast with constant growth in one line
- Mention that one operation can still be slow
Evaluation rubric
- Correct implementation with doubling
- Correct geometric series argument
- Distinguishes amortised from average and worst case
- Discusses shrinking or real-time concerns