TExcelTAD
Home › Design Techniques: Dynamic Programming, Greedy & Amortized Analysis › Dynamic Tables: Contraction and the Quarter Rule

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 O(1)O(1) 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 size=m\mathit{size} = m and num=m\mathit{num} = m, full, and alternate:

  • insert: the table is full, so it doubles to 2m2m and copies mm items;
  • delete, delete: now num=m−1<m=2m2\mathit{num} = m - 1 < m = \frac{2m}{2}, so it halves back to mm and copies m−1m - 1 items;
  • insert: the table holds mm items in mm slots, full again, and the pattern repeats.

The table bounces between sizes mm and 2m2m, and every few operations copy about mm items. With m≈n/2m \approx n/2, nn operations cost Θ(n2)\Theta(n^2).

python · try it yourself
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 12\frac{1}{2} (or the table is empty), so at least about size4\frac{\mathit{size}}{4} operations must happen before the next resize, enough to pay for copying the size4\frac{\mathit{size}}{4} to size2\frac{\mathit{size}}{2} items involved. The load factor always stays between 14\frac{1}{4} 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 α=12\alpha = \frac{1}{2}, the load factor right after any resize:

Φ(T)={2⋅T.num−T.sizeif α(T)≥12,12 T.size−T.numif α(T)<12.\Phi(T) = \begin{cases} 2 \cdot T.\mathit{num} - T.\mathit{size} & \text{if } \alpha(T) \ge \frac{1}{2}, \\ \frac{1}{2}\, T.\mathit{size} - T.\mathit{num} & \text{if } \alpha(T) < \frac{1}{2}. \end{cases}

It is 0 at α=12\alpha = \frac{1}{2}, grows to num\mathit{num} when the table is full (enough to pay for copying everything at the next expansion), and also grows to num\mathit{num} when α\alpha reaches 14\frac{1}{4} (since then 12size−num=2 num−num\frac{1}{2}\mathit{size} - \mathit{num} = 2\,\mathit{num} - \mathit{num}), 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 num\mathit{num}, size\mathit{size} for the values before the operation.

Insertion.

  • α≥12\alpha \ge \frac{1}{2} before: exactly the analysis of the expanding table, c^=3\hat{c} = 3 (with or without expansion).
  • α<12\alpha < \frac{1}{2} before and after: c=1c = 1 and Φ\Phi falls by 1, so c^=0\hat{c} = 0.
  • α<12\alpha < \frac{1}{2} before, α=12\alpha = \frac{1}{2} after: Φ\Phi goes from 12size−num=1\frac{1}{2}\mathit{size} - \mathit{num} = 1 to 0, so c^=1−1=0\hat{c} = 1 - 1 = 0.

Deletion.

  • α≥12\alpha \ge \frac{1}{2} before and after: c=1c = 1 and Φ\Phi falls by 2, so c^=−1\hat{c} = -1.
  • α=12\alpha = \frac{1}{2} before, α<12\alpha < \frac{1}{2} after: Φ\Phi goes from 0 to 1, so c^=2\hat{c} = 2.
  • α<12\alpha < \frac{1}{2} before, no contraction: c=1c = 1 and Φ\Phi rises by 1, so c^=2\hat{c} = 2.
  • Contraction: before, num=size4\mathit{num} = \frac{\mathit{size}}{4}, so Φ=size4\Phi = \frac{\mathit{size}}{4}. After, num′=size4−1\mathit{num}' = \frac{\mathit{size}}{4} - 1 items in a block of size2\frac{\mathit{size}}{2}, so Φ′=size4−num′=1\Phi' = \frac{\mathit{size}}{4} - \mathit{num}' = 1. The cost is c=1+num′c = 1 + \mathit{num}', so c^=1+size4−1+1−size4=1\hat{c} = 1 + \frac{\mathit{size}}{4} - 1 + 1 - \frac{\mathit{size}}{4} = 1.

The small cases (sizes 1 and 2, and freeing the empty table) are checked the same way and give c^≤1\hat{c} \le 1.

So every insertion has amortized cost at most 3 and every deletion at most 2, and any sequence of nn operations on an initially empty table costs at most 3n3n. The program checks the two maxima over thousands of random sequences, including adversarial bouncing, with exact fractions for Φ\Phi.

python · try it yourself
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 14≤α≤1\frac{1}{4} \le \alpha \le 1 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.

cpp · try it yourself
#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::vector never 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 Θ(n2)\Theta(n^2) worst-case cost?

  1. Because halving copies all items twice
  2. 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
  3. Because the load factor can exceed 1
  4. Because deletions are expensive

With the quarter rule, between which bounds does the load factor of a nonempty table always stay?

  1. 12\frac{1}{2} and 1
  2. 14\frac{1}{4} and 1
  3. 14\frac{1}{4} and 12\frac{1}{2}
  4. 0 and 1

What is Φ\Phi for a table with size=64\mathit{size} = 64 and num=20\mathit{num} = 20?

  1. −24-24
  2. 88
  3. 1212
  4. 2020