ProgrammingHard

A dynamic array doubles its capacity whenever it is full. Pushing N = 10^6 values costs about how many element copies in total?

  1. A. About 10^12, so the doubling is quadratic
  2. B. About 10^6 log 10^6, which is about 2 x 10^7
  3. C. Under 2 x 10^6 in total, so the amortised cost per push is O(1)
  4. D. About 500 000 because only half are copied

Correct answer: C. Under 2 x 10^6 in total, so the amortised cost per push is O(1)

The copies form a geometric series: 1 + 2 + 4 + ... < 2N. Each element is copied only a constant number of times on average, so each push is O(1) amortised.

More C Programming questions

Exams that ask this topic