Sub topic 7
Shrinking without thrashing
This chapter assumes you know the aggregate and accounting arguments for a doubling dynamic array. It also assumes you can read short Python programs.
The problem with the obvious rule
Growing an array when it is full gives O(1) amortised appends. Deletions raise a new question. You may want to free memory after many removals. The obvious rule is to halve the capacity when the array is half full.
That rule fails at the boundary. Suppose the capacity is 16 and the array holds 9 elements.
- A
popleaves 8 elements, which is half of 16, so the array shrinks to capacity 8. It is now full. - An
appendfinds the array full, so it doubles back to 16. - The next
popshrinks it again.
Every operation copies about n elements. A sequence of m operations costs Θ(mn), so the amortised cost is Θ(n) per operation. Repeated resizing in alternating directions like this is called thrashing.
The fix: leave a gap between the two thresholds
Grow when the array is full, so size equals capacity. Shrink when the size falls to one quarter of the capacity, and then halve the capacity.
| Event | Trigger | New capacity | Fill after resize |
|---|---|---|---|
| Grow | size = capacity | 2 × capacity | about 1/2 |
| Shrink | size = capacity / 4 | capacity / 2 | 1/2 |
Both resizes leave the array half full. After a resize, the array needs at least capacity/4 operations in the right direction before the next resize. The copying cost is at most about the current size, so the resize cost is spread over many cheap operations.
Seeing it run
This program counts element copies for both rules. It fills an array, then alternates pop and append at the boundary.
class ResizingArray:
MIN_CAPACITY = 4
def __init__(self, shrink_at):
self._shrink_at = shrink_at # shrink when size <= capacity * shrink_at
self._capacity = self.MIN_CAPACITY
self._size = 0
self._data = [None] * self._capacity
self.copies = 0
def append(self, value):
if self._size == self._capacity:
self._resize(2 * self._capacity)
self._data[self._size] = value
self._size += 1
def pop(self):
if self._size == 0:
raise IndexError("pop from empty array")
self._size -= 1
value = self._data[self._size]
self._data[self._size] = None
if (self._capacity > self.MIN_CAPACITY
and self._size <= self._capacity * self._shrink_at):
self._resize(self._capacity // 2)
return value
def _resize(self, new_capacity):
new_data = [None] * new_capacity
for i in range(self._size):
new_data[i] = self._data[i]
self.copies += 1
self._data = new_data
self._capacity = new_capacity
def boundary_copies(shrink_at, rounds=1000):
arr = ResizingArray(shrink_at)
for i in range(1025): # capacity becomes 2048
arr.append(i)
arr.copies = 0
for _ in range(rounds):
arr.pop()
arr.append(0)
return arr.copies
naive = boundary_copies(0.5)
safe = boundary_copies(0.25)
print("shrink at 1/2:", naive)
print("shrink at 1/4:", safe)
assert naive == 1000 * 2048
assert safe == 0The naive rule copies 2048 elements per pop and append pair. The quarter rule copies nothing, because the array never reaches a threshold.
Why the bound holds
Use the potential method with a function that is zero when the array is exactly half full:
- If size ≥ capacity/2, then Φ = 2 · size − capacity.
- If size < capacity/2, then Φ = capacity/2 − size.
Each ordinary operation changes Φ by at most 2, so its amortised cost is constant. A grow happens at size = capacity, where Φ = capacity. That drop in potential pays for the copy. A shrink happens at size = capacity/4, where Φ = capacity/4. That again matches the copy cost. After either resize, Φ is 0. The total amortised cost of any sequence of appends and pops is therefore O(1) per operation.
Design checks
- Use a shrink threshold below the post-shrink fill level. The 1/4 threshold with a halving step satisfies this.
- Keep a minimum capacity so tiny arrays do not resize constantly.
- Shrinking is optional. If memory is not scarce, never shrinking is also O(1) amortised.
Exercise
A dynamic array doubles when full and halves when its size drops to 1/3 of the capacity. After a shrink, how full is the array? Can a single pop followed by a single append cause two resizes in a row?
Show answer
After the shrink, capacity is halved and size is capacity/3, so the new fill is (1/3)/(1/2) = 2/3. A grow needs the array to be full, which takes about capacity/3 more appends from there. A shrink needs size to fall to 1/3 of the new capacity, which takes about capacity/6 more pops. A single pop and append cannot cause two resizes in a row, so the array does not thrash at this boundary.