1 + 2 + 4 + … + n < 2n
Doubling sizes add up to less than twice the last one. That's why dynamic arrays are per append and a full tree has 2ʰ⁺¹ − 1 .
The idea
Each power of two is one more than the sum of all the smaller ones: 1 + 2 + 4 = 7 = 8 − 1. So 1 + 2 + … + 2ᵏ = 2ᵏ⁺¹ − 1, less than twice the last term.
A dynamic array (Python list, ArrayList) doubles when full and copies everything. Copies cost 1 + 2 + 4 + … + n < 2n in total, so n appends cost : O(1) each on average. A perfect of height h has 1 + 2 + … + 2ʰ = 2ʰ⁺¹ − 1 nodes, half of them .
Worked example
Appending 16 items to a list that starts with room for 1
- Resizes copy 1, 2, 4 and 8 items: 15 copies.
- Plus 16 writes. 31 operations for 16 appends: under 2 per append.
Pseudocode
The steps in plain words. ← means “set to”; indentation shows what's inside what.
See it run
The worked example, step by step, beside the Python. The highlighted line is the one running.
Step-by-step
16 appends, starting with room for 1
Solution · Pythonline 2
def resize_copies(n):capacity, copies = 1, 0for size in range(1, n + 1):if size > capacity:copies += capacity # copy everything into a twice-as-big arraycapacity *= 2return copies # resize_copies(16) == 15; always under 2nStep 1 of 6· line 2
When the array is full, make one twice as big and copy everything over. Copies look expensive, but they add up to less than the number of appends.
Total work for n doubling steps is O(n).
How to spot it
- Anything that doubles: dynamic arrays, tree levels, repeated squaring, 's levels.
Common mistakes
- Calling append O(n) because a single resize is O(n): the average is O(1).
- Forgetting a complete tree's last level holds about half its nodes.
Where it comes up
Go further
Up next for you · Beginner
“Have I seen this?” is a set →