AlgoViz

Dynamic arrays

easy 16 min

A dynamic array is an array that grows by itself.

Video lesson · Chapter 1 of 5

The fifth price tag

0:00 / 3:32

Dynamic arrays — The fifth lantern

1:25Reel

Read caption

Mavi moves four lanterns to make room for a fifth, separating length, capacity, and amortized append cost. One expensive move buys room for cheap appends.

How it works

Step through the idea, or press Play.

Step 1 of 3

Keep spare capacity. The array reserves more slots than it uses, so most appends just write into the next free slot

Understand it

Start here

What a dynamic array is

A plain array is a fixed block of memory: you choose its length when you create it and it can never grow. A dynamic array wraps that block and grows or shrinks automatically. When it is full it allocates a larger block and copies the elements over. You keep the strengths of an array, O(1)O(1) access by index and contiguous memory, without having to know the size up front.

  • O(1) access by index

    Element ii lives at base+i×width\text{base} + i \times \text{width}. One calculation, one jump.

  • Amortised O(1) append

    Most appends write one slot. The rare resize is paid for by all the cheap appends around it.

  • No size up front

    Start with a few slots and let it grow as data arrives.

  • Cache friendly

    Elements sit side by side, so the CPU reads them in fast, predictable runs.

The picture

Size versus capacity

Two numbers describe a dynamic array. Size is how many elements it holds. Capacity is how many slots it has allocated. The slots from size to capacity - 1 exist in memory but hold nothing yet; size is also the index where the next append will land.

Slot01234567
Value1020304050freefreefree
Size 5, capacity 8. Valid indexes are 0 to 4; slots 5 to 7 are spare room for the next three appends.

How full is it?

load=sizecapacity0≤size≤capacity\text{load} = \frac{\text{size}}{\text{capacity}} \qquad 0 \le \text{size} \le \text{capacity}
With doubling, the load is above 12\tfrac{1}{2} right after every grow. With the quarter-full shrink rule it never drops below 14\tfrac{1}{4}, so at most 34\tfrac{3}{4} of the block is idle.
The life of a dynamic array
  1. 1AppendWrite into the next free slot
  2. 2Full?size equals capacity
  3. 3GrowAllocate 2× and copy
  4. 4Keep appendingCheap again for a while
Repeat: back to Append

Each lap around the loop is twice as long as the last, so resizes get rarer as the array grows.

Under the hood

How append works

append(x)

The no branch is one write. The yes branch copies every element first, then does the same write.
Python
class DynamicArray:    def __init__(self):        self.capacity = 1        self.size = 0        self.data = [None] * self.capacity    def append(self, value):        if self.size == self.capacity:            self._resize(2 * self.capacity)        self.data[self.size] = value        self.size += 1    def _resize(self, new_capacity):        new_data = [None] * new_capacity        for i in range(self.size):            new_data[i] = self.data[i]        self.data = new_data        self.capacity = new_capacityarr = DynamicArray()for x in range(1, 10):    arr.append(x)    print(f"size={arr.size} capacity={arr.capacity}")
A minimal dynamic array on top of a fixed list of slots. Watch capacity jump 1, 2, 4, 8.
Edit and run it in your browser

Growth

The doubling strategy

When the array is full, double its capacity. It looks wasteful, but it is what makes append cheap on average. Capacities run 1,2,4,8,16,…1, 2, 4, 8, 16, \dots, so reaching nn elements takes only about log⁡2n\log_2 n resizes.

_resize(new_capacity)

One copy per live element: a resize is O(n)O(n) time and needs O(n)O(n) extra space while both blocks exist.

Number of resizes to reach n elements

resizes=⌈log⁡2n⌉e.g. n=1,000,000⇒20 resizes\text{resizes} = \lceil \log_2 n \rceil \qquad \text{e.g. } n = 1{,}000{,}000 \Rightarrow 20 \text{ resizes}
Starting from capacity 1. Growing by one slot at a time would need n−1n - 1 resizes instead.

Proof

Why append is amortised O(1)

Amortised cost is the total cost of a sequence of operations divided by the number of operations. One append can cost O(n)O(n), but it cannot happen often. Count everything over nn appends starting from capacity 1.

Aggregate method

1+2+4+⋯+2k⏟copies, with 2k<n  =  2k+1−1  <  2n⇒total  <  2n⏟copies+n⏟writes=3n\underbrace{1 + 2 + 4 + \dots + 2^{k}}_{\text{copies, with } 2^{k} < n} \;=\; 2^{k+1} - 1 \;<\; 2n \qquad\Rightarrow\qquad \text{total} \;<\; \underbrace{2n}_{\text{copies}} + \underbrace{n}_{\text{writes}} = 3n
So the amortised cost is 3nn=3\frac{3n}{n} = 3 per append: O(1)O(1). For 5 appends the real total is 12, an average of 2.4.

Accounting method: charge 3 credits per append

  • 1 credit: write it

    Pays for putting the new element in its slot.

  • 1 credit: move itself

    Saved on the element to pay for copying it at the next resize.

  • 1 credit: move an elder

    Pays to copy an older element that already spent its saved credit at an earlier resize.

Trade-offs

Choosing a growth factor

Total copies for growth factor r

n(1+1r+1r2+⋯ )=rr−1 nr=2:2n,r=1.5:3n,r=1.125:9nn\left(1 + \frac{1}{r} + \frac{1}{r^2} + \cdots\right) = \frac{r}{r-1}\,n \qquad r = 2: 2n,\quad r = 1.5: 3n,\quad r = 1.125: 9n
The last resize copied at most nn elements, the one before about n/rn/r, and so on. Any factor above 1 keeps append amortised O(1)O(1). A larger factor copies less but leaves up to 1−1r1 - \tfrac{1}{r} of the block idle after a grow.
LanguageTypeGrowthNote
Python (CPython)listabout 1.125×Plus a small constant; tight on memory, copies more often
JavaArrayList1.5×old + (old >> 1)
C++std::vector2× (GCC, Clang) or 1.5× (MSVC)Implementation-defined
JavaScriptArrayEngine-specificV8 grows by about 1.5× plus a constant
Goslice2× for small, about 1.25× for largeRule changes past a threshold
RustVec2×Amortised growth guaranteed

Growing by a constant k is quadratic

k+2k+3k+⋯+nk k  =  k⋅nk(nk+1)2  ≈  n22k=O(n2)k + 2k + 3k + \dots + \tfrac{n}{k}\,k \;=\; k \cdot \frac{\tfrac{n}{k}\left(\tfrac{n}{k} + 1\right)}{2} \;\approx\; \frac{n^2}{2k} = O(n^2)
For 1,000 appends from capacity 1: about 50,600 steps with +10+10, against 2,023 with doubling. The proof is an arithmetic series; doubling gives a geometric one.

Shrinking

Pop and the quarter rule

pop() removes the last element: decrement size, read the slot, clear it. Nothing moves, so it is O(1)O(1). To give memory back, an array can also shrink, and the threshold matters.

pop()

Grow at full, shrink at a quarter, and halve when shrinking. After any resize the array is half full.

Shrink at a quarter full

  • After a shrink the array is half full: room to grow and to shrink.
  • At least n/4n/4 cheap operations come before the next resize.
  • Pop stays amortised O(1)O(1).

Shrink at half full

  • A full array of 4: push grows it to 8, pop shrinks it back to 4.
  • Alternating push and pop copies nn elements every time.
  • This is called thrashing: O(n)O(n) per operation.

Middle edits

Insert and remove at an index

An array cannot hold gaps. Inserting at index ii shifts everything from ii onward one slot right, working back to front so nothing is overwritten. Removing at ii shifts everything after it one slot left, front to back.

insert(i, x) and remove_at(i)

Insert shifts right from the back; remove shifts left from the front.

Shifts per operation

insert at i:  n−i shiftsremove at i:  n−i−1 shifts\text{insert at } i: \; n - i \text{ shifts} \qquad \text{remove at } i: \; n - i - 1 \text{ shifts}
At the end (i=ni = n or i=n−1i = n - 1) that is zero shifts, so append and pop are cheap. At the front it is about nn: O(n)O(n).

Complexity

What each operation costs

OperationTypicalWorstAmortisedWhy
get(i), set(i, x)O(1)O(1)O(1)O(1)O(1)O(1)Address arithmetic
append(x)O(1)O(1)O(n)O(n)O(1)O(1)Occasional doubling copy
pop()O(1)O(1)O(n)O(n)O(1)O(1)Occasional shrink copy
insert(i, x)O(n)O(n)O(n)O(n)O(n)O(n)Shifts n−in - i elements
remove_at(i)O(n)O(n)O(n)O(n)O(n)O(n)Shifts n−i−1n - i - 1 elements
search by valueO(n)O(n)O(n)O(n)O(n)O(n)Checks each element
len()O(1)O(1)O(1)O(1)O(1)O(1)Size is stored
Space is O(n)O(n): at most a constant factor more slots than elements.

Static vs dynamic arrays

FeatureStatic arrayDynamic array
SizeFixed at creationGrows and shrinks
MemoryExactly what you asked forSome spare capacity
AppendNot possible once fullO(1)O(1) amortised
Access by indexO(1)O(1)O(1)O(1)
Use whenSize known, every byte countsSize unknown or changing
See static arrays for the block underneath.

In the wild

Watching a real list grow

CPython over-allocates a little on every grow. sys.getsizeof reports the bytes a list object reserves, so it jumps only when capacity changes, not on every append.

Python
import sysitems = []last = sys.getsizeof(items)print(f"len=0  bytes={last}")for i in range(40):    items.append(i)    now = sys.getsizeof(items)    if now != last:        print(f"len={len(items):<3} bytes={now}  (grew)")        last = now
The size in bytes stays flat between resizes, then jumps.
Edit and run it in your browser
  • Reserve up front

    If you know the final size, preallocate: [None] * n in Python, reserve(n) in C++, new ArrayList<>(n) in Java.

  • Build, then join

    Collect string pieces in a list and ''.join() once, instead of repeated += that can copy each time.

  • Stacks for free

    append and pop() at the end make a list a ready-made stack.

Pattern spotting

When to reach for a dynamic array

Which sequence structure?

In practice the dynamic array is the default; move away from it only for a clear reason.

Use a dynamic array when

  • You build a list of unknown length.
  • You need a stack: push and pop at the end.
  • You collect results during a traversal or filter.
  • Order matters and you read by index.

Pick something else when

  • You add or remove at the front often (deque).
  • You need first-in, first-out order (deque or queue).
  • You test membership constantly (set).
  • The size is fixed and memory is tight (static array).

Recap

Key takeaways

Key points

  • A dynamic array is a fixed block plus a size and a capacity; it reallocates and copies when full.
  • Doubling means about log⁡2n\log_2 n resizes and fewer than 2n2n copies, so append is amortised O(1)O(1) and worst case O(n)O(n).
  • Any growth factor above 1 works; growing by a constant makes nn appends cost O(n2)O(n^2).
  • Shrink at a quarter full and halve, never at half full, to avoid thrashing.
  • Access, set, len and pop() are O(1)O(1); insert and remove in the middle are O(n)O(n) because of shifting.
  • Valid indexes run to size - 1, never to capacity - 1.

Sources