Doubling makes resize events increasingly rare. The total work spread across many appends stays constant on average: amortized O(1).
How it works, from first principles
Implementing a
Dynamic Array
Purpose: understand how an array can preserve fast indexed access while growing beyond its original fixed capacity.
CONTROL CONSOLE
Keep appending. Watch what changes only when the buffer is full.
The algorithm’s little promise
Fast most of the time.
Prepared for the rare expensive moment.
A dynamic array holds two facts: count is how many values are actually stored, and capacity is how many drawers have been reserved. Appending normally writes once at dynamic[count].
When count === capacity, the current buffer cannot stretch. We reserve a new one with double the capacity, copy every existing value in order, then switch the reference to that new buffer.
01append(value) {02 if (count === capacity) {03 resize();04 }05 dynamic[count] = value;06 count++;07}
Some reserved drawers stay empty. That small memory cushion buys quick appends without allocating storage every time.
Only indexes 0 through count − 1 contain valid elements. Capacity is the physical room, not the logical size.