Dynamic Tables: Contraction and the Quarter Rule
A table that only grows can waste memory: after a burst of insertions and then mass deletions, a block sized for a million items may hold ten. So tables should also contract, allocating a smaller block and copying the survivors when the load factor gets low. The obvious rule, "halve when less than half full", is a trap: it lets an adversary force a copy on almost every operation. This lesson shows the trap, fixes it with the quarter rule, and proves with a two-piece potential function that every insertion and deletion then costs amortized.
The obvious rule thrashes
Use the doubling insertion of the previous lesson, and contract to half the size whenever a deletion leaves the table less than half full. Now take a table with and , full, and alternate:
- insert: the table is full, so it doubles to and copies items;
- delete, delete: now , so it halves back to and copies items;
- insert: the table holds items in slots, full again, and the pattern repeats.
The table bounces between sizes and , and every few operations copy about items. With , operations cost .
def run(ops, shrink_below):
"""doubling on insert; halving when num < shrink_below * size after a delete"""
num = size = 0
total = resizes = 0
for op in ops:
cost = 1
if op == "I":
if size == 0:
size = 1
if num == size:
cost += num; size *= 2; resizes += 1
num += 1
else:
num -= 1
if num == 0:
size = 0
elif num < shrink_below * size:
cost += num; size //= 2; resizes += 1
total += cost
return total, resizes
m = 1024
fill = ["I"] * m # a full table of size 1024
bounce = ["I", "D", "D", "I"] * 500 # the adversary's pattern
for rule, frac in [("halve below 1/2", 1 / 2), ("halve below 1/4", 1 / 4)]:
base, _ = run(fill, frac)
total, resizes = run(fill + bounce, frac)
print(f"{rule}: 2000 bouncing operations cost {total - base:7}, resizes {resizes - 10}")halve below 1/2: 2000 bouncing operations cost 1025500, resizes 1000
halve below 1/4: 2000 bouncing operations cost 3024, resizes 1
With the half rule every round of four operations triggers a doubling and a halving, about a thousand copies each time. With the quarter rule only the very first insertion resizes (one doubling, 1024 copies); after it the table is half full, and the bouncing never takes it near a quarter again.
The quarter rule
Double the table when an insertion finds it full; halve it when a deletion leaves it less than a quarter full (and free it when it becomes empty). After either kind of resize the load factor is exactly (or the table is empty), so at least about operations must happen before the next resize, enough to pay for copying the to items involved. The load factor always stays between and 1, so the memory used is at most four times what the items need.
The potential function
A single linear potential cannot work any more: it must grow as the table fills toward an expansion and as it empties toward a contraction. Use a function with two pieces that meet at , the load factor right after any resize:
It is 0 at , grows to when the table is full (enough to pay for copying everything at the next expansion), and also grows to when reaches (since then ), enough to pay for the copies of the next contraction. It is never negative, and it is 0 for the empty table, so the total amortized cost bounds the total actual cost.
The case analysis: insertion at most 3, deletion at most 2
Write , for the values before the operation.
Insertion.
- before: exactly the analysis of the expanding table, (with or without expansion).
- before and after: and falls by 1, so .
- before, after: goes from to 0, so .
Deletion.
- before and after: and falls by 2, so .
- before, after: goes from 0 to 1, so .
- before, no contraction: and rises by 1, so .
- Contraction: before, , so . After, items in a block of , so . The cost is , so .
The small cases (sizes 1 and 2, and freeing the empty table) are checked the same way and give .
So every insertion has amortized cost at most 3 and every deletion at most 2, and any sequence of operations on an initially empty table costs at most . The program checks the two maxima over thousands of random sequences, including adversarial bouncing, with exact fractions for .
import random
from fractions import Fraction
def phi(num, size):
if size == 0:
return 0
return 2 * num - size if 2 * num >= size else Fraction(size, 2) - num
def step(num, size, op):
cost = 1
if op == "I":
if size == 0:
size = 1
if num == size:
cost += num; size *= 2
num += 1
else:
num -= 1
if num == 0:
size = 0
elif 4 * num < size:
cost += num; size //= 2
return num, size, cost
rng = random.Random(21)
worst = {"I": None, "D": None}
total_actual = total_ops = 0
for trial in range(300):
bias = [0.3, 0.5, 0.7][trial % 3] # shrinking, balanced and growing phases
num = size = 0
for _ in range(300):
op = "I" if num == 0 or rng.random() < bias else "D"
before = phi(num, size)
num, size, cost = step(num, size, op)
amortized = cost + phi(num, size) - before
worst[op] = amortized if worst[op] is None else max(worst[op], amortized)
assert phi(num, size) >= 0 and (size == 0 or Fraction(1, 4) <= Fraction(num, size) <= 1)
total_actual += cost; total_ops += 1
print("largest amortized insertion:", worst["I"], " largest amortized deletion:", worst["D"])
print(f"{total_ops} operations, actual cost {total_actual} <= 3 per operation: {total_actual <= 3 * total_ops}")largest amortized insertion: 3 largest amortized deletion: 2
90000 operations, actual cost 118232 <= 3 per operation: True
The assertion also confirms the load-factor invariant after every operation of every run.
In C++
A minimal dynamic table of int with the quarter rule, counting the elements copied by resizes over a long random sequence that grows to about 100,000 items and shrinks back.
#include <cstdio>
#include <memory>
#include <random>
struct Table {
std::unique_ptr<int[]> data;
long long num = 0, size = 0, copies = 0;
void resize(long long new_size) {
std::unique_ptr<int[]> fresh(new_size ? new int[new_size] : nullptr);
for (long long i = 0; i < num; ++i) fresh[i] = data[i];
copies += num;
data = std::move(fresh);
size = new_size;
}
void insert(int x) {
if (num == size) resize(size ? 2 * size : 1);
data[num++] = x;
}
void erase_last() {
--num;
if (num == 0) resize(0);
else if (4 * num < size) resize(size / 2);
}
};
int main() {
Table t;
std::mt19937 rng(3);
long long ops = 0;
long long peak = 0;
for (int phase = 0; phase < 2; ++phase)
for (int i = 0; i < 400000; ++i, ++ops) {
bool grow = phase == 0 ? rng() % 100 < 63 : rng() % 100 < 37;
if (t.num == 0 || grow) t.insert(i);
else t.erase_last();
if (t.num > peak) peak = t.num;
}
std::printf("%lld operations, peak %lld items, final %lld items in %lld slots\n", ops, peak, t.num, t.size);
std::printf("elements copied by resizes: %lld (%.3f per operation)\n", t.copies,
static_cast<double>(t.copies) / ops);
}800000 operations, peak 104397 items, final 0 items in 0 slots
elements copied by resizes: 196717 (0.246 per operation)
The copying work stays a small constant per operation over a growth to the peak and a shrink back down, as the potential argument guarantees.
In practice:
std::vectornever shrinks on its own;shrink_to_fit()is a non-binding request to release unused capacity. Hash tables often shrink with a hysteresis gap like the quarter rule, for the same reason: without the gap, an adversary alternating insertions and deletions at the threshold forces a rehash every time.
Test yourself
Why does 'halve when less than half full' lead to worst-case cost?
- Because halving copies all items twice
- Because right after an expansion the table is exactly half full, so one or two deletions trigger a contraction and the next insertions an expansion again
- Because the load factor can exceed 1
- Because deletions are expensive
With the quarter rule, between which bounds does the load factor of a nonempty table always stay?
- and 1
- and 1
- and
- 0 and 1
What is for a table with and ?