/ THE IDEA
A dynamic array stores items in a contiguous block with some spare capacity. An append fills the next empty slot. When the block is full, the implementation can allocate a block twice as large, copy the existing items, then append the new one. Copying is expensive, but the new spare room buys many cheap appends before another resize. The copied block sizes form a geometric sequence: 1, 2, 4, 8 and so on. Each new term is twice the previous term, so their sum remains within a constant multiple of the last scale.
THE FORMAL IDEA
total writes < 3N; amortized append work = O(1)
| N = a positive number of appends starting from an empty array with capacity 1. | | Count one unit for storing a new item and one for copying an old item. O(1) means a constant bound per append after total work is spread over the sequence; it is not a stopwatch guarantee for each append. |
|
RUN THE TINY EXAMPLE
Change one thing. Predict what happens.
Append 8 items: ordinary stores cost 8 writes. Resizes copy 1 + 2 + 4 = 7 items; total = 15 writes. Change N from 8 to 9: the next append copies 8 and stores 1, costing 9 writes by itself. Total for 9 appends = 24 writes, still less than 3 × 9 = 27.
|
The expensive ninth action does not violate the bound. Earlier actions created a sequence whose combined cost can pay for that resize. For any prefix, copied powers of two sum to less than 2N; adding N ordinary stores gives the stated bound.
/ SO WHAT?
Growing capacity by just one slot instead would copy 1 + 2 + 3 and so on, causing quadratic total copying. Doubling spends extra memory to avoid that pattern. Reserving capacity ahead of time can also move the allocation cost away from an interactive action when the final size is predictable.
ONE CAVEAT |
| The toy count omits allocation time and assumes each item copy has constant cost. Real growth factors vary, and deletion policies must avoid repeatedly shrinking and regrowing around one threshold. Amortized bounds require no random inputs; they are not average-case probability claims. |
KEEP THIS
Large growth steps create enough cheap future operations to bound total copying, even though an individual resize remains expensive.
|
NEXT: Why a shorter light flash can reveal two surfaces
|