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.
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.
Run the simulation
Watch grow and shrink (allocate + copy), plus insert and delete shifts.
Append until it grows
Append past the limit to grow. Delete until length ≤ capacity/4 to shrink into a smaller block.
Dynamic array mental model
Contiguous · shift to insert/delete · grow and shrink by copy.
Still one block
Index access stays O(1). Middle insert/delete still shifts the tail.
Allocate + copy
Full → larger block. Length ≤ capacity/4 → smaller block. Both copy live values and free the old memory.
Rare expensive steps
One resize costs O(n), but doubling/halving makes those steps rare — average cost stays low.