The Aggregate Method
Some operations are usually cheap and occasionally expensive. Appending to a dynamic array is 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 , any sequence of operations takes at most time in total. Then the amortized cost of each operation is . 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:
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 - 1Its cost is for a stack of size . A single MULTIPOP on a stack of objects costs , so the naive bound for operations is : each could be a MULTIPOP of cost up to .
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 . With the pushes themselves, the total cost of any sequence of operations on an initially empty stack is at most , and the amortized cost per operation is .
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 , 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 .
Example 2: a binary counter
A -bit counter is an array of bits, the least significant. INCREMENT adds 1 modulo :
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 oneThe cost of an increment is the number of bits it flips. Going from to flips all bits, so the worst case is , and the naive bound for increments is .
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 flips times in increments starting from 0. So the total is
The amortized cost of an increment is less than 2 flips, independent of . In fact the sum is exactly , where is the number of 1 bits in the binary representation of : the program checks both.
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 bits when ends in ones. Expensive increments are rare in exactly the proportion that makes the average constant.
The closed form makes the total computable in 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).
#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 to ).
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 cost 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 per operation guarantee?
- Every operation takes time
- Any sequence of operations takes time in total
- The expected time of an operation is for random inputs
- Most operations take time
In increments of a counter starting at 0, how many times does bit 3 flip?
- 3
- 8
- 16
- 32
How many bit flips do 12 increments make, starting from 0?
- 12
- 20
- 22
- 24
Why can a sequence of stack operations (push, pop, multipop) on an empty stack cost at most ?
- Because multipop is
- Because every object is popped at most once per push, so pops are at most the number of pushes
- Because the stack has at most elements
- Because multipop is rare