DSA Factory
Free Complexity lessonsComplexity · Stage 1 · Growth in practice · Step 4

Cheap on average

A growing list doubles its space now and then, and the copying still averages out to a little per item. About 9 minutes.

How a growing list works

Python lists, C++ vectors, Java ArrayLists and JavaScript arrays all keep spare space. It is like a bus that fills up: when it runs out of seats, everyone moves to a bus twice as big, and then the new bus has lots of empty seats again.

Copying everyone across is the expensive part. After it, appends are cheap again for a while.

Full? double the space and copy what's there.
5 appends into a growing list (tinted = the space it has)
1
0
1
2
3
4
5
6
7
append
space
1
copied
0

Space for 1. Append item 1: it fits.

Move 1 of 5

Add it all up

Starting from space for 1 item, n appends copy 1 + 2 + 4 + … items, with each copy twice the last, and the final one smaller than n. That sum stays below 2n.

So a single append can be slow, but n appends cost O(n) together, which is O(1) each on average.

Growing by 1 instead: would copy 1 + 2 + 3 + …: about n²/2.
In code
copies = 0
capacity = 1
while capacity < n:
    copies += capacity
    capacity *= 2
return copies
Quick check

Space starts at 1 and doubles when full. How many items are copied in total over 5 appends?

  1. A7
  2. B15
  3. C10
Show the answer

7. Appends 2, 3 and 5 find the space full and copy 1, 2 and 4 items.

Your problem

Copies from doubling

A list starts with space for 1 item. Each append that finds the space full first doubles the space and copies every stored item into the new space. Return the total number of items copied over n appends.

Example
n = 5 → 7

0 ≤ n ≤ 2,000,000,000 · return a long

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve