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

0500020004000ncount
Measured
Table
ncount
815
1631
3263
64127
128255
256511
5121,023
10242,047
20484,095
40968,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
  1. Resizes happen at sizes 1, 2, 4, 8, …, each copying that many elements.
  2. Copies: 1 + 2 + 4 + … < 2n (a geometric series). Plus n writes of new elements: < 3n.
  3. 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.