Data Structures & AlgorithmsVery hardProduct company OA

Total element copies when a dynamic array is filled with 100 items under three growth rules (cost, final capacity). What is printed?

Total element copies when a dynamic array is filled with 100 items under three growth rules (cost, final capacity). What is printed?
def copies(n, grow):
    cap, size, cost = 1, 0, 0
    for _ in range(n):
        if size == cap:
            cost += size
            cap = grow(cap)
        size += 1
    return cost, cap
print(copies(100, lambda c: 2 * c), copies(100, lambda c: c + c // 2 + 1), copies(100, lambda c: c + 10))
  1. A. (127, 128) (196, 139) (460, 101)
  2. B. (127, 128) (261, 139) (460, 101)
  3. C. (99, 128) (261, 139) (4950, 101)
  4. D. (127, 128) (261, 139) (500, 110)

Correct answer: B. (127, 128) (261, 139) (460, 101)

A copy of all current items happens whenever size reaches capacity. Doubling: 1+2+4+…+64 = 127, about n – O(1) amortised. Growth by ×1.5 (+1) still copies a geometric series, 261 here, a larger constant but still O(1) amortised. Growing by a constant 10 copies 1, 11, 21, …, 91 = 460 for only 100 items, and in general Θ(n²/10) – O(n) amortised per insert. A constant increment is the trap even though it wastes the least memory.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic