Dynamic arrays & resizing
Implement a growable array and prove append is amortised O(1).
By Invicly Tech, , in Data Structures & Algorithms. About 9 minutes to read.
In short
A dynamic array wraps a fixed-size array and tracks size and capacity separately. When it fills up it allocates a bigger array, usually about double, and copies the items across. Python's list works this way, which is why append is amortised O(1).
Explained simply
A dynamic array is an array that grows by itself. You keep appending, and it never says "full". Python's list, Java's ArrayList and C++'s vector are all dynamic arrays.
Underneath, it is still a plain fixed-size array. The trick is that it keeps two numbers: size, how many items you stored, and capacity, how many slots it has. When size reaches capacity, it gets a bigger array, usually twice as big, copies everything across, and throws the old one away.
It is like a family moving house. Most days, a new item just goes into a free cupboard. When the house is full, they move to a house twice the size, which is a big job. But because each move doubles the space, moves become rarer and rarer.
So most appends are instant, and the occasional slow one is paid for by all the fast ones. On average, appending costs a constant amount of work. Reading and writing by index stay instant, just like a normal array.
Press Play on a diagram to walk through it one step at a time.
- 1Append
Write at index size if there is room.
- 2Full?
size equals capacity.
- 3Grow
Allocate about 2x capacity.
- 4Copy
Move all items, O(n) once.
- Back to step 1
- 10 resizes
- 1,023 items copied
- Up to 50% unused space
- About 16 resizes
- Roughly 2,000 items copied
- Up to 33% unused space
- 100 resizes
- About 50,000 items copied
- O(n) per append, avoid
In depth
Size versus capacity
Size is what the user sees: len(xs). Capacity is hidden: the number of slots really allocated. Slots between size and capacity hold junk and must never be read.
This is why get(i) must check i < size, not i < capacity. A bug here returns leftover data that looks real. Every method in a dynamic array keeps one rule true: items live at indexes 0 to size - 1, and size is at most capacity.
- 0 <= size <= capacity, always
- Bounds checks use size
- Slots from size to capacity - 1 are free space
Why doubling gives amortised O(1)
Count the copies. Starting at capacity 1, resizes copy 1, 2, 4, 8 and so on, up to the largest power of two below n. That adds to less than 2n. Add the n normal writes and the total is under 3n.
Another way to see it: after a resize to capacity 2k, the next k appends are cheap. Charge each of those appends 2 extra coins, and you have exactly 2k coins saved when the next resize copies 2k items. Every append pays a constant, so the cost is O(1) amortised.
Choosing the growth factor
Any factor above 1 gives amortised O(1). Bigger factors mean fewer copies but more wasted space. Factor 2 can waste up to half the memory right after a resize. Factor 1.5 wastes less and lets old memory blocks be reused more easily.
CPython grows lists by about 1.125 times plus a small constant. Java's ArrayList uses 1.5. Many C++ vectors use 2. The choice is an engineering trade-off, not a correctness rule.
Shrinking without thrashing
If you pop many items, you may want to give memory back. The naive rule "halve when half full" has a trap. At exactly the boundary, one push grows the array and one pop shrinks it, so alternating push and pop costs O(n) every time.
The fix is a gap: grow when full, but only halve when size drops to a quarter of capacity. After a shrink, the array is half full, so it takes many operations to reach either boundary again. Python lists do shrink, using a similar safe margin.
- One push at the boundary grows
- The next pop shrinks again
- Alternating push and pop: O(n) each
- Gap between grow and shrink points
- After a shrink, array is half full
- Amortised O(1) is kept
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Track size versus capacity~45m
- 2Grow by doubling and copy~45m
- 3Implement append, pop, get and set~45m
- 4Prove amortised O(1) append~45m
Key points
- get and set by index: O(1).
- append: amortised O(1), occasionally O(n) when resizing.
- Growing by a constant amount instead of a factor makes appends O(n) amortised.
- Some implementations shrink when size drops below a quarter of capacity.
Key terms
Tap a card to flip it. 0/4 known
Examples
class DynArray:
def __init__(self):
self.size, self.cap = 0, 1
self.data = [None] * self.cap
def append(self, x): # amortised O(1)
if self.size == self.cap:
self.cap *= 2
new = [None] * self.cap
new[:self.size] = self.data[:self.size]
self.data = new
self.data[self.size] = x
self.size += 1Watching CPython lists grow
sys.getsizeof shows the bytes a list object uses, including spare capacity. If we append one item at a time and print only when the size jumps, we see resizes happening at lengths 1, 5, 9, 17, 25, 33 and so on. The jumps get further apart as the list grows, which is the geometric growth that makes append cheap on average. Exact numbers can differ by Python version.
import sys
xs, last = [], sys.getsizeof([])
for i in range(40):
xs.append(i)
now = sys.getsizeof(xs)
if now != last:
print(f"len {len(xs):2d}: {now} bytes")
last = nowA tiny dynamic array with insert
This class doubles when full and supports insert at any index. Insert [10, 20] then insert 15 at index 1: capacity grows 1 -> 2 -> 4, and 20 shifts right to make room. The result is [10, 15, 20] with capacity 4. Note how insert reuses the same grow step as append.
class DynArray:
def __init__(self):
self.size, self.cap, self.data = 0, 1, [None]
def _grow(self):
self.cap *= 2
self.data = self.data + [None] * (self.cap - len(self.data))
def insert(self, i, x):
if self.size == self.cap:
self._grow()
for j in range(self.size, i, -1):
self.data[j] = self.data[j - 1]
self.data[i] = x
self.size += 1
a = DynArray(); a.insert(0, 10); a.insert(1, 20); a.insert(1, 15)
print(a.data[:a.size], a.cap) # [10, 15, 20] 4Quick reference
- size = items stored; capacity = slots allocated
- Grow by a factor (1.5 or 2), never by a fixed amount
- append: O(1) amortised, O(n) on the resizing call
- get/set by index: O(1); insert/delete in middle: O(n)
- Shrink at 1/4 full, not 1/2, to avoid thrashing
- Pre-size when you know n: [0] * n avoids repeated growth
Common mistakes
- Forgetting to bounds-check against size rather than capacity in get.
- Shrinking at half full, which can thrash between grow and shrink.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write resizes_needed(n) that returns how many times a doubling array starting at capacity 1 must resize to hold n items. Example: n = 9 needs 4 resizes (1 -> 2 -> 4 -> 8 -> 16).
- Exercise 2medium
Write a Stack class on top of a fixed-size Python list that doubles when full and halves when only a quarter full (minimum capacity 1). Support push, pop and len. Example: push 1..5 gives capacity 8; pop 4 times gives capacity 2.
- Exercise 3hard
Write merge_sorted_in_place(a, m, b) where list a has m real items followed by len(b) spare slots, and both parts are sorted. Fill a with all items sorted, without extra lists. Example: a = [1, 4, 7, 0, 0], m = 3, b = [2, 5] gives [1, 2, 4, 5, 7].
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- If append is O(1), why is my loop of appends sometimes slow?
- The rare resize copies everything, which can cause a small pause. Over the whole loop it averages out, but if you know the final size, building [None] * n first avoids resizes entirely.
- Does Python ever shrink a list?
- Yes. When a list loses many items, CPython may reallocate it smaller, using a margin so it does not grow and shrink back and forth.
- Is a dynamic array better than a linked list?
- For most tasks, yes: indexing is O(1) and memory is cache friendly. Linked lists win only when you insert or delete in the middle often and already hold a pointer to the spot.