Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: A dynamic array doubles its capacity when full (starting at capacity 1), copying all elements to the new storage. Count element copies caused by 1000 appends.

Problem: A dynamic array doubles its capacity when full (starting at capacity 1), copying all elements to the new storage. Count element copies caused by 1000 appends.
cap, size, copies = 1, 0, 0
for _ in range(1000):
    if size == cap:
        copies += size; cap *= 2
    size += 1
print(copies)
What is printed?
  1. A. 1000
  2. B. 999
  3. C. 1023
  4. D. 2047

Correct answer: C. 1023

Resizes happen at sizes 1, 2, 4, …, 512, copying 1 + 2 + … + 512 = 1023 elements. This geometric sum is below 2n, so each append costs O(1) amortised.

More Coding Interview Problems questions

Exams that ask this topic