Data Structures and Algorithms
A dynamic array, when an element is added while it is full, allocates a new area with twice the capacity and copies all elements into it. If 1,000 elements are added one at a time to an empty array of capacity 1, how many element copies are made in total?
- A10
- B1,023
- C499,500
Show answer and explanation
Answer: B. 1,023
The capacity doubles each time it fills up, going 1, 2, 4, …, 512, and each time all current elements are copied, so the total number of copies is 1 + 2 + 4 + … + 512 = 1,023. For 1,000 additions that is about one copy per element, so the cost per addition is constant on average: amortized O(1). If the capacity grew by only 1 each time, the copies would total 1 + 2 + … + 999 = 499,500, which is O(n²). 10 is the number of reallocations, not the number of elements copied.
- A. This is the number of reallocations (10, from 1→2 up to 512→1024), not the number of elements copied.
- B. Correct. 1 + 2 + 4 + … + 512 = 1,023, about one copy per addition on average.
- C. This is the total number of copies if the capacity grew by 1 each time.