Exercise 23 of 30 · intermediate · amortized · dynamic arrays · linear
n appends to a doubling dynamic array
The code
arr = DynamicArray() # capacity doubles when full
for i in range(n):
arr.append(i)Some appends copy everything. What is the total?
Count: element writes (new elements + resize copies).
Measured counts
Table
| n | count |
|---|---|
| 8 | 15 |
| 16 | 31 |
| 32 | 63 |
| 64 | 127 |
| 128 | 255 |
| 256 | 511 |
| 512 | 1,023 |
| 1024 | 2,047 |
| 2048 | 4,095 |
| 4096 | 8,191 |
Try to name the class from the shape before opening the answer.
Show the answer and derivation
- Time
- Θ(n) total, amortized O(1) per append
- Extra space
- Θ(n)
- Exact count
- n + (1 + 2 + 4 + … + 2^⌊log₂(n−1)⌋) < 3n
- Resizes happen at sizes 1, 2, 4, 8, …, each copying that many elements.
- Copies: 1 + 2 + 4 + … < 2n (a geometric series). Plus n writes of new elements: < 3n.
- Total Θ(n), so the amortized cost per append is O(1), even though one append can cost Θ(n).
Common mistake: Multiplying the worst single append (Θ(n)) by n to get Θ(n²). Amortized analysis sums the actual costs.
Check: measured count ÷ (n) settles near 2.00 for large n.