AlgoFrames

Count the copies of n appends

Warm-up · Write code · about 6 min

A dynamic array starts empty with capacity 1. Before an append that finds the block full, it doubles the capacity and copies every stored value into the new block.

Return how many values are copied in total during n appends.

Example 1

Input:

[5]

Output:

7

Resizes happen at sizes 1, 2 and 4: 1 + 2 + 4 = 7.

Example 2

Input:

[1]

Output:

0

The first value fits in capacity 1.

Constraints

  • 0 ≤ n ≤ 1,000,000

Learn the idea first: Dynamic arrays: capacity, growth, amortized append, a visual lesson.

More Dynamic arrays: capacity, growth, amortized append problems