TExcelTAD

The Aggregate Method

Some operations are usually cheap and occasionally expensive. Appending to a dynamic array is O(1)O(1) until the array is full and must be copied; incrementing a binary counter flips one bit, except when it flips twenty. A worst-case bound per operation multiplied by the number of operations is then far too pessimistic. Amortized analysis bounds the total cost of a whole sequence of operations, in the worst case, and spreads it evenly. No probability is involved: an amortized bound holds for every sequence, which distinguishes it from the average-case analysis of Worst, Best and Average Case. This section presents the three standard methods, aggregate, accounting and potential, each on the same two examples. The aggregate method comes first because it is the most direct.

The method

Show that for every nn, any sequence of nn operations takes at most T(n)T(n) time in total. Then the amortized cost of each operation is T(n)/nT(n)/n. Every operation gets the same amortized cost, even if the sequence mixes several kinds of operation.

Example 1: a stack with multipop

A stack supports PUSH(x) and POP(), each costing 1, and a third operation:

text
MULTIPOP(S, k)                     // pop k objects, or all of them if fewer
1  while not STACK-EMPTY(S) and k > 0
2      POP(S)
3      k = k - 1

Its cost is min⁡(s,k)\min(s, k) for a stack of size ss. A single MULTIPOP on a stack of nn objects costs nn, so the naive bound for nn operations is O(n2)O(n^2): each could be a MULTIPOP of cost up to nn.

Aggregate argument. Each object is popped at most once for each time it is pushed. So the total number of pops, counting those inside MULTIPOP, is at most the number of pushes, which is at most nn. With the pushes themselves, the total cost of any sequence of nn operations on an initially empty stack is at most 2n2n, and the amortized cost per operation is O(1)O(1).

python · try it yourself
import random

def run(ops):
    stack, total, worst = [], 0, 0
    for op, k in ops:
        if op == "push":
            stack.append(len(stack)); cost = 1
        elif op == "pop":
            cost = 1 if stack else 0
            if stack: stack.pop()
        else:                                    # multipop k
            cost = min(k, len(stack))
            del stack[len(stack) - cost:]
        total += cost
        worst = max(worst, cost)
    return total, worst

rng = random.Random(1)
for n in [10, 1000, 100000]:
    ops = []
    for _ in range(n):
        r = rng.random()
        ops.append(("push", 0) if r < 0.6 else ("pop", 0) if r < 0.8 else ("multipop", rng.randint(1, n)))
    total, worst = run(ops)
    pushes = sum(op == "push" for op, _ in ops)
    print(f"n = {n:6}: total cost {total:6} <= 2n = {2 * n:6}, pushes {pushes:5}, most expensive single op {worst}")

# the adversary's best try: n - 1 pushes, then one huge multipop
n = 100000
total, worst = run([("push", 0)] * (n - 1) + [("multipop", n)])
print(f"n - 1 pushes + 1 multipop: total {total}, worst single op {worst}")
n =     10: total cost     12 <= 2n =     20, pushes     6, most expensive single op 3
n =   1000: total cost   1236 <= 2n =   2000, pushes   622, most expensive single op 17
n = 100000: total cost 120554 <= 2n = 200000, pushes 60278, most expensive single op 26
n - 1 pushes + 1 multipop: total 199998, worst single op 99999

The totals stay below 2n2n, as they must: a multipop can only pop what earlier pushes put there. In the random sequences the pops keep the stack short, so no single operation is very expensive; the last line is the adversary's attempt, with one operation of cost 99,999, and the total is still only 2n−22n - 2.

Example 2: a binary counter

A kk-bit counter is an array A[0..k−1]A[0..k-1] of bits, A[0]A[0] the least significant. INCREMENT adds 1 modulo 2k2^k:

text
INCREMENT(A)
1  i = 0
2  while i < k and A[i] == 1
3      A[i] = 0                    // trailing ones become zeros
4      i = i + 1
5  if i < k
6      A[i] = 1                    // the lowest zero becomes one

The cost of an increment is the number of bits it flips. Going from 0111…10111\ldots1 to 1000…01000\ldots0 flips all kk bits, so the worst case is Θ(k)\Theta(k), and the naive bound for nn increments is O(nk)O(nk).

Aggregate argument. Look at each bit separately rather than each operation. Bit 0 flips on every increment, bit 1 on every second one, bit 2 on every fourth: bit ii flips ⌊n/2i⌋\lfloor n/2^i \rfloor times in nn increments starting from 0. So the total is

∑i=0k−1⌊n2i⌋<n∑i=0∞12i=2n.\sum_{i=0}^{k-1} \left\lfloor \frac{n}{2^i} \right\rfloor < n \sum_{i=0}^{\infty} \frac{1}{2^i} = 2n.

The amortized cost of an increment is less than 2 flips, independent of kk. In fact the sum is exactly 2n−s(n)2n - s(n), where s(n)s(n) is the number of 1 bits in the binary representation of nn: the program checks both.

python · try it yourself
def increment(A):
    i, flips = 0, 0
    while i < len(A) and A[i] == 1:
        A[i] = 0; flips += 1; i += 1
    if i < len(A):
        A[i] = 1; flips += 1
    return flips

A = [0] * 8
history = []
for n in range(1, 17):
    f = increment(A)
    history.append(f)
    print(f"{n:2}: {''.join(map(str, reversed(A)))}  flips {f}")
print("total flips for 16 increments:", sum(history), " 2n - s(n) =", 2 * 16 - bin(16).count("1"))

A, total, ok = [0] * 20, 0, True
for n in range(1, 100001):
    total += increment(A)
    ok &= total == 2 * n - bin(n).count("1") == sum(n >> i for i in range(20))
print("total = 2n - s(n) = sum of floor(n / 2^i) for every n up to 100000:", ok)
 1: 00000001  flips 1
 2: 00000010  flips 2
 3: 00000011  flips 1
 4: 00000100  flips 3
 5: 00000101  flips 1
 6: 00000110  flips 2
 7: 00000111  flips 1
 8: 00001000  flips 4
 9: 00001001  flips 1
10: 00001010  flips 2
11: 00001011  flips 1
12: 00001100  flips 3
13: 00001101  flips 1
14: 00001110  flips 2
15: 00001111  flips 1
16: 00010000  flips 5
total flips for 16 increments: 31  2n - s(n) = 31
total = 2n - s(n) = sum of floor(n / 2^i) for every n up to 100000: True

The flip counts follow the "ruler" pattern 1, 2, 1, 3, 1, 2, 1, 4, ...: an increment flips t+1t + 1 bits when n−1n - 1 ends in tt ones. Expensive increments are rare in exactly the proportion that makes the average constant.

The closed form makes the total computable in O(lg⁡n)O(\lg n) time without simulating, as sum(n >> i ...): that is the practice problem Binary Counter Bit Flips.

In C++

The same counter in C++, with a std::vector<int> of bits, and the closed form computed with std::popcount from <bit> (C++20).

cpp · try it yourself
#include <bit>
#include <cstdio>
#include <vector>

int increment(std::vector<int>& A) {
    size_t i = 0;
    int flips = 0;
    while (i < A.size() && A[i] == 1) { A[i] = 0; ++flips; ++i; }
    if (i < A.size()) { A[i] = 1; ++flips; }
    return flips;
}

int main() {
    std::vector<int> A(32, 0);
    long long total = 0;
    int worst = 0;
    const unsigned long long n = 1000000;
    for (unsigned long long m = 1; m <= n; ++m) {
        int f = increment(A);
        total += f;
        if (f > worst) worst = f;
    }
    std::printf("%llu increments: %lld flips, worst single increment %d flips\n", n, total, worst);
    std::printf("2n - popcount(n) = %llu\n", 2 * n - std::popcount(n));
}
1000000 increments: 1999993 flips, worst single increment 20 flips
2n - popcount(n) = 1999993

A million increments flip just under two million bits, while the worst single increment flips 20 (from 219−1=0111…12^{19} - 1 = 0111\ldots1 to 2192^{19}).

What the aggregate method cannot say

The aggregate method gives one number for the whole sequence. It does not say that PUSH and MULTIPOP have different amortized costs, and it says nothing about a counter that starts at an arbitrary value, or one that also supports a decrement (where it fails: alternating increments and decrements at 0111…10111\ldots1 cost kk each). The next two methods assign amortized costs to each operation separately and handle such cases: the accounting method with stored credit, and the potential method with a function of the data structure's state.

Test yourself

What does an amortized bound of O(1)O(1) per operation guarantee?

  1. Every operation takes O(1)O(1) time
  2. Any sequence of nn operations takes O(n)O(n) time in total
  3. The expected time of an operation is O(1)O(1) for random inputs
  4. Most operations take O(1)O(1) time

In n=64n = 64 increments of a counter starting at 0, how many times does bit 3 flip?

  1. 3
  2. 8
  3. 16
  4. 32

How many bit flips do 12 increments make, starting from 0?

  1. 12
  2. 20
  3. 22
  4. 24

Why can a sequence of nn stack operations (push, pop, multipop) on an empty stack cost at most 2n2n?

  1. Because multipop is O(1)O(1)
  2. Because every object is popped at most once per push, so pops are at most the number of pushes
  3. Because the stack has at most lg⁡n\lg n elements
  4. Because multipop is rare