Dynamic arrays
easy 16 minA dynamic array is an array that grows by itself.
See it run
Watch an array fill its capacity, double and copy, shift for middle edits, shrink at a quarter full, and see why all that copying still averages out to O(1) per append.
Operations
Append with resize
Push 10, 20, 30, 40 into an array of capacity 4, then push 50. The fifth push finds no free slot, so the array doubles to capacity 8 and copies everything first.
Step 1 of 9
An empty array of capacity 4
- —0
- —1
- —2
- —3
The array owns 4 slots of contiguous memory but holds nothing yet. Two numbers describe it: size = 0 (items stored) and capacity = 4 (slots allocated). size is also the index of the next free slot.
Step 1: An empty array of capacity 4
def append(self, value): if self.size == self.capacity: # no free slot left? self._resize(2 * self.capacity) # double: copy all n items self.data[self.size] = value # write into the next free slot self.size += 1- Time
- O(1) amortised, O(n) worst
- Space
- O(n) during a resize
- no resize
- O(1): one write
- with resize
- O(n): n copies + one write
Say amortised O(1), not O(1). A single append can cost O(n) when it triggers a resize; the average over many appends is constant.
In the real world
The same dynamic arrays doing real jobs. Pick one and step through it.
Items added to a cart: it grows as the user shops.
Step 1 of 3
Three items in a cart of 4
- 250
- 151
- 402
- —3
The cart holds prices 25, 15, 40. The list reserved 4 slots, so one more item fits without any copying. The shopper never sees capacity; they just keep adding.
Step 1: Three items in a cart of 4
cart = [25, 15, 40] # prices, capacity 4 behind the scenescart.append(30) # fills the last free slotcart.append(12) # full: grows, copies 4, then writesCommon mistakes
The bugs interviewers watch for, with the fix beside each.
Calling append O(1) without saying amortised
criticalA single append can be O(n) when it triggers a resize. Interviewers test whether you know the difference between amortised and worst case, so say amortised O(1) explicitly.
Wrong# "append is always O(1)"arr.append(x) # this particular append may copy n itemsRight# amortised O(1): average over many appends# worst case O(n): the append that triggers a resizearr.append(x)Shrinking at half full
majorWith grow-at-full and shrink-at-half, alternating push and pop at the boundary resizes on every operation. Shrinking at a quarter leaves room on both sides.
Wrongif self.size == self.capacity // 2: self._resize(self.capacity // 2)# push -> grow, pop -> shrink, push -> grow ...Rightif 0 < self.size <= self.capacity // 4: self._resize(self.capacity // 2)# after any resize the array is half fullGrowing by a constant amount
majorAdding k slots means a resize every k pushes, each copying everything: k + 2k + 3k + ... is about n squared over 2k. Doubling gives about log n resizes and under 2n copies in total. Resizing is never free.
Wrongif self.size == self.capacity: self._resize(self.capacity + 10)# 1,000 pushes: about 50,000 copiesRightif self.size == self.capacity: self._resize(self.capacity * 2)# 1,000 pushes: about 1,000 copiesUsing capacity where you mean size
majorSlots between size and capacity are allocated but hold no elements. Loops, bounds checks and len must all use size; valid indexes are 0 to size - 1.
Wrongfor i in range(self.capacity): print(self.data[i]) # prints empty slotsif index < self.capacity: # lets get(5) through on size 2 return self.data[index]Rightfor i in range(self.size): print(self.data[i])if not 0 <= index < self.size: raise IndexError("index out of range")Not clearing the slot on pop
minorIn a garbage-collected language, the array still references the popped object, so it cannot be freed until the slot is overwritten.
Wrongdef pop(self): self.size -= 1 return self.data[self.size] # reference still heldRightdef pop(self): self.size -= 1 value = self.data[self.size] self.data[self.size] = None # let the object be collected return valueAssuming every list operation is cheap
minorPython's list is a dynamic array: append and pop() are amortised O(1), but insert(0, x) and pop(0) shift every element. Know what your language's list really is.
Wrongqueue = []queue.insert(0, x) # O(n)queue.pop(0) # O(n)Rightfrom collections import dequequeue = deque()queue.appendleft(x) # O(1)queue.popleft() # O(1)
Interview tips
Perfect for
- Building a list of unknown length.
- Implementing a stack: push and pop at the end.
- Collecting results during a traversal.
- A cache or buffer that grows and shrinks.
- Anything where order matters and you need random access.
Avoid when
- Frequent insert or delete at the front: use a deque.
- First-in, first-out queues: use a deque or queue.
- Size known and fixed: a static array has less overhead.
- Frequent middle insertions with a cursor: consider a linked list.
- Fast membership tests: use a set.
Master amortised thinking
- Accounting: charge 3 credits per push, 1 to write it, 1 to copy it later, 1 to copy an older element.
- Aggregate: copies 1 + 2 + 4 + ... < 2n, plus n writes, under 3n in total.
- Amortised per push: 3n / n = O(1).
- Geometric growth means about log n resizes.
Patterns built on dynamic arrays
- Two pointers: left and right indexes moving inward.
- Sliding window over a subarray.
- Stack: push and pop at the end only.
- Building a result array during traversal or filtering.