Dynamic arrays

Same contiguous block as a static array — grow when full, and shrink into a smaller block when length falls well below capacity.

Data structures Beginner+ Resizable · Amortized ~10 min
The idea

Grow and shrink by allocate + copy

A dynamic array (Python list, Java ArrayList, C++ vector) still stores values in one contiguous block. Insert and delete shift neighbours the same way as a static array.

When length == capacity, it grows: allocate a larger block (often 2×), copy every live value, free the old block. When length falls well below capacity (here length ≤ capacity / 4), it can shrink the same way into a smaller block to free unused memory.

TipMost appends and deletes are cheap. Occasional full copies keep average cost low — that is called amortized cost.
IdeaReallocate
resize.pyPython
if length == capacity:          # grow
    new_cap = capacity * 2
elif length <= capacity // 4:  # shrink
    new_cap = capacity // 2
for i in range(length):
    new_arr[i] = arr[i]
arr, capacity = new_arr, new_cap

Same copy loop both ways — only the new capacity differs.

Interactive

Run the simulation

Watch grow and shrink (allocate + copy), plus insert and delete shifts.

Step 0 / 0
demo.pyPython
Array blockdemo
Ready
Shortcuts: Space play/pause · → step · ← back · R reset
Try it yourself

Append until it grows

Append past the limit to grow. Delete until length ≤ capacity/4 to shrink into a smaller block.

Ready
Capacity 4, length 4 — full. Press Append to grow, or choose an index to insert/delete.
Remember

Dynamic array mental model

Contiguous · shift to insert/delete · grow and shrink by copy.

Same core

Still one block

Index access stays O(1). Middle insert/delete still shifts the tail.

Resize

Allocate + copy

Full → larger block. Length ≤ capacity/4 → smaller block. Both copy live values and free the old memory.

Trade-off

Rare expensive steps

One resize costs O(n), but doubling/halving makes those steps rare — average cost stays low.

Related

Static arrays

Same shifting rules — but capacity never changes, so a full block refuses insert.

Open static arrays